@protomaze/demo-engine 0.1.9 → 0.1.11

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 p,estimate as l}from"../model/Timing.js";import{parseDemo as d,validate as c}from"../model/Validate.js";import{Hand as m}from"../page/Input.js";import{Overlay as g}from"../page/Overlay.js";import{stillPage as u}from"../page/Still.js";import{Targets as y}from"../page/Targets.js";import{Speech as f}from"../speech/Speech.js";import{narrationFor as w,transcribe as v}from"../speech/Transcribe.js";import{Store as k}from"../store/Store.js";import{demoFromLink as S,download as b,fileName as P,linkTo as T,shareFiles as x}from"../store/Share.js";import{extensionOf as E,recordMicrophone as R,startFilming as j,videoSize as $}from"../video/Film.js";import{renderMusic as M}from"../speech/Music.js";import{readPack as L,writePack as K}from"../speech/Pack.js";import{Player as N}from"./Player.js";import{Recorder as B}from"./Recorder.js";import{readAction as D}from"./Read.js";import{mountUI as I}from"../ui/EngineUI.js";import{agentTools as O}from"../agent/Agent.js";import{openPresenter as A}from"../ui/Presenter.js";import{DEFAULT_RELAY as F,qrSvg as C,RemoteLink as J}from"../remote/Remote.js";import{DEFAULT_SETTINGS as U,loadSettings as z,saveSettings as V}from"./Settings.js";const Q=["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.remoteSent="",this.remoteTimer=0,this.getState=()=>this.state,this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e)),this.hintTimer=0,this.targets=new y({...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:z(this.settingsKey),speech:{}},this.speech=new f(()=>this.state.settings.speech,()=>this.set({speech:{...this.speech.state}})),this.store=new k(`protomaze-demo-engine:${e.app}`),this.store.subscribe(()=>this.emit()),this.plugins=e.plugins??[]}emit(){this.state={...this.state},this.listeners.forEach(e=>e()),this.toRemote()}set(e){this.state={...this.state,...e},this.listeners.forEach(e=>e()),this.toRemote()}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};V(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 D(e,this.options.labels,this.plugins,t)}async mount(){if(this.unmount)return;this.overlay.mount();const e=I(this),t=e=>this.key(e);window.addEventListener("keydown",t,!0);const s=e=>this.gate(e);Q.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]=O(this)),this.unmount=()=>{e(),window.removeEventListener("keydown",t,!0),Q.forEach(e=>window.removeEventListener(e,s,{capture:!0})),i&&delete window[i],this.overlay.unmount()},await this.arrived()}destroy(){this.closeRemote(),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)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=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 d(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),presenting:Boolean(t.presenting),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 A(this,e)}presenterKey(e){this.key(e)}present(e,t={}){this.openDialog({kind:"present",demo:e,from:t.from})}openDialog(e){this.set({dialog:e,...this.state.library&&this.options.launcher?{library:void 0}:{}})}closeDialog(){this.set({dialog:void 0})}openSettings(){this.set({library:"settings"})}showLibrary(e){this.set({library:e})}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()}async openRemote(){if(!1===this.options.remote)throw new Error("No phone remote in this app");if(this.state.remote)return this.state.remote;const e=this.options.remote?.relay??F;this.remoteLink=await J.open(e,{command:e=>this.fromRemote(e),hello:()=>this.remoteSent="",peers:e=>this.state.remote&&this.set({remote:{...this.state.remote,peers:e}})});const t={url:this.remoteLink.url,svg:C(this.remoteLink.url),peers:0};return this.set({remote:t}),this.remoteTimer=window.setInterval(()=>this.toRemote(!0),1e3),t}closeRemote(){window.clearInterval(this.remoteTimer),this.remoteLink?.close(),this.remoteLink=void 0,this.remoteSent="",this.set({remote:void 0})}fromRemote(e){const t=this.state.session;"playing"===t.mode&&("next"===e.do?t.player.next():"back"===e.do?t.player.back():"goto"===e.do&&void 0!==e.step?t.player.goTo(e.step):"stop"===e.do?this.stop():"toggle"===e.do&&(t.waiting?t.player.next():this.togglePause()))}toRemote(e=!1){if(!this.remoteLink)return;const t=this.remoteState(),{at:s,elapsed:i,stepElapsed:o,...n}=t,a=JSON.stringify(n);(a!==this.remoteSent||e&&t.playing)&&(this.remoteSent=a,this.remoteLink.send(t))}remoteState(){const e=this.state.session,t=Date.now();if("playing"!==e.mode||e.checking)return{playing:!1,title:"",steps:[],step:0,caption:"",paused:!1,waiting:!1,filming:!1,elapsed:0,stepElapsed:0,planned:0,at:t};const s=this.language(),o=this.timing(e.demo,s),a=o.steps.find(t=>t.step===e.step),r=e.player.elapsed();return{playing:!0,title:e.demo.title,steps:e.demo.steps.map((e,t)=>({title:e.title??`Step ${t+1}`,script:n(i(e,s)),...e.notes?{notes:e.notes}:{}})),step:e.step,caption:e.caption,paused:e.paused,waiting:e.waiting,filming:e.filming,elapsed:r,stepElapsed:r-e.player.stepStartedAt,planned:o.duration,...a?{plannedStep:a.end-a.start}:{},at:t}}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 L(await t.arrayBuffer());const s=this.options.narration?.(e);if(!s)return;const i=await fetch(s);return i.ok?L(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)},l=["pointerdown","keydown","wheel","touchstart"];l.forEach(e=>window.addEventListener(e,p,{capture:!0,passive:!0}));this.looping={demos:e,options:t,stop:()=>{i=!0,l.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 d=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 d(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 d(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}`};const{animations:i,fromStart:o,...n}=t,a=i?()=>{}:u();try{if(!1!==o&&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 t=await this.run(e,{...n,speed:n.speed??8,keepGoing:!0,checking:!0,catchUp:!0,subtitles:!1}),i=t.failures.map(t=>({...t,action:e.steps[t.step].actions[t.index]}));return{ok:!t.error&&0===i.length,error:t.error,failures:i,problems:s,duration:t.timing.duration}}finally{a()}}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:l(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 j({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:l}=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 d=r.timing.cues;l&&"off"===this.state.settings.speech.voice&&(this.setSession({mode:"preparing",title:e.title,text:"Transcribing what was said"}),d=await this.transcribe(l,s).catch(()=>d),this.setSession({mode:"idle"}));const c={id:e.id,blob:p,at:Date.now(),json:JSON.stringify(e),vtt:h(d),timing:r.timing,language:s,look:this.look(s),...l?{voice:l}:{}};return await this.store.saveVideo(c),this.say(`Filmed "${e.title}": ${Math.round(p.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:$(s,i)}:{}}}look(e){const{settings:t}=this.state,s=this.options.appTheme?.(),i=this.options.language?.();return{...s?{theme:s}:{},...i?{locale:i}:{},voice:t.speech.voice,language:e,subtitles:t.subtitles}}async transcribe(e,t=this.language()){const{settings:s}=this.state;return v(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 j({soundtrack:this.speech.soundtrack(),microphone:o.microphone,crop:this.options.filmElement?.(),...this.filmQuality(),onEnded:()=>{this.stopRecording?.()}}):o.microphone&&(r=await R())}catch(e){return this.say(`Could not start: ${e.message}`,!0),i()}const p=this.options.start?.current(),l=new B(this.targets,this.plugins,n,e=>this.updateSession("recording",e));a?.resume();const d=performance.now();this.setSession({mode:"recording",filming:Boolean(a),microphone:Boolean(r||a&&o.microphone),step:0,caption:"",actions:0}),this.nextStepRecording=()=>l.nextStep(),this.sayRecording=e=>l.say(e),this.stopRecording=async()=>{this.stopRecording=this.nextStepRecording=this.sayRecording=void 0;const c=Boolean(r||a&&o.microphone),m=l.stop(c),g=performance.now()-d;this.setSession({mode:"preparing",title:"Recording",text:"Keeping what was recorded"});try{const[i,o]=await Promise.all([r?.stop(),a?.stop()]),l=i??o?.voice;let d=[];if(l){this.updateSession("preparing",{text:"Transcribing what was said"});try{d=await this.transcribe(l,n);const e=w(m.stepStarts,d);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",p),steps:[]},y=t.after??u.steps.length-1,f={...u,steps:[...u.steps.slice(0,y+1),...c,...u.steps.slice(y+1)]};0===f.steps.length&&f.steps.push({say:{},actions:[]}),o&&await this.store.saveVideo({id:f.id,blob:o.video,at:Date.now(),json:JSON.stringify(f),vtt:h(d),language:n,look:{...this.look(n),voice:"off",subtitles:!1},timing:{duration:g,steps:m.stepStarts.map((e,t)=>({step:t,start:e,end:m.stepStarts[t+1]??g})),cues:d.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:f.steps,at:Date.now()}}}):this.openStudio(f)}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 T(e)}downloadDemo(e,t="json"){if("md"===t)return b(e.scenario??o(e,this.language()),P(e.id,"md"),"text/markdown");const{scenario:s,savedAt:i,...n}=e;b(JSON.stringify(n,null,2)+"\n",P(e.id,"demo.json"),"application/json")}downloadVideo(e,t,s=!1){return"vtt"===s?b(e.vtt,P(t,"vtt"),"text/vtt"):"srt"===s?b(r(a(e.vtt)),P(t,"srt"),"application/x-subrip"):void b(e.blob,P(t,E(e.blob)))}shareVideo(e,t){return x([new File([e.blob],P(t,E(e.blob)),{type:e.blob.type}),new File([e.vtt],P(t,"vtt"),{type:"text/vtt"})],t)}languagesOf(e){return t(e)}}export{U as DEFAULT_SETTINGS};
1
+ import{copyOf as t,languagesOf as e,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 l}from"../model/Timing.js";import{parseDemo as d,validate as c}from"../model/Validate.js";import{Hand as m}from"../page/Input.js";import{Overlay as g}from"../page/Overlay.js";import{stillPage as u}from"../page/Still.js";import{Targets as y}from"../page/Targets.js";import{Speech as f}from"../speech/Speech.js";import{narrationFor as w,transcribe as v}from"../speech/Transcribe.js";import{Store as k}from"../store/Store.js";import{demoFromLink as S,download as b,fileName as P,linkTo as E,shareFiles as T}from"../store/Share.js";import{extensionOf as x,recordMicrophone as R,startFilming as j,videoSize as $}from"../video/Film.js";import{renderMusic as L}from"../speech/Music.js";import{readPack as M,writePack as N}from"../speech/Pack.js";import{Player as K}from"./Player.js";import{Recorder as B}from"./Recorder.js";import{readAction as D}from"./Read.js";import{mountUI as A}from"../ui/EngineUI.js";import{agentTools as I,promptForClaude as O}from"../agent/Agent.js";import{Assistant as F,EMPTY_ASSISTANT as C}from"../agent/Assistant.js";import{openPresenter as J}from"../ui/Presenter.js";import{DEFAULT_RELAY as U,qrSvg as z,RemoteLink as V}from"../remote/Remote.js";import{DEFAULT_SETTINGS as Q,loadSettings as H,saveSettings as G}from"./Settings.js";const q=["pointerdown","pointerup","pointermove","pointerover","pointerout","mousedown","mouseup","mousemove","mouseover","mouseout","click","dblclick","contextmenu","wheel","touchstart","touchmove","touchend","keydown","keyup","keypress"];export class DemoEngine{constructor(t){this.options=t,this.listeners=new Set,this.packs=new Map,this.remoteSent="",this.remoteTimer=0,this.getState=()=>this.state,this.subscribe=t=>(this.listeners.add(t),()=>this.listeners.delete(t)),this.hintTimer=0,this.targets=new y({...t.targets,labels:t.labels}),this.overlay=new g(t.overlay),this.hand=new m(this.overlay.cursor,()=>this.player?.speedNow??1),this.settingsKey=`protomaze-demo-engine:${t.app}:settings`,this.state={session:{mode:"idle"},settings:H(this.settingsKey),speech:{},assistant:C},this.assistant=new F(this,()=>this.state.settings.claude,t=>this.set({assistant:t})),this.speech=new f(()=>this.state.settings.speech,()=>this.set({speech:{...this.speech.state}})),this.store=new k(`protomaze-demo-engine:${t.app}`),this.store.subscribe(()=>this.emit()),this.plugins=t.plugins??[]}emit(){this.state={...this.state},this.listeners.forEach(t=>t()),this.toRemote()}set(t){this.state={...this.state,...t},this.listeners.forEach(t=>t()),this.toRemote()}setSession(t){this.set({session:t})}updateSession(t,e){this.state.session.mode===t&&this.setSession({...this.state.session,...e})}say(t,e=!1){this.set({message:t?{text:t,error:e}:void 0})}changeSettings(t){const e={...this.state.settings,...t};G(this.settingsKey,e),this.set({settings:e}),t.music?.on&&this.loadMusic().catch(()=>{})}language(){const t=this.state.settings.language;return"page"!==t?t:this.options.language?.()??this.options.languages?.[0]??(navigator.language.split("-")[0]||"en")}languages(){return this.options.languages??[this.language()]}pluginKinds(){return this.plugins.flatMap(t=>Object.keys(t.actions??{}))}pluginAction(t){return this.plugins.map(e=>e.actions?.[t]).find(Boolean)}read(t,e){return D(t,this.options.labels,this.plugins,e,this.language())}async mount(){if(this.unmount)return;this.overlay.mount();const t=A(this),e=t=>this.key(t);window.addEventListener("keydown",e,!0);const s=t=>this.gate(t);q.forEach(t=>window.addEventListener(t,s,{capture:!0,passive:!1})),this.state.settings.music.on&&this.loadMusic().catch(()=>{});const i=()=>{this.takeLink()};window.addEventListener("hashchange",i);const o=this.agentName();let n;o&&(window[o]=I(this),n=document.createElement("meta"),n.name="demo-engine",n.content=`window.${o}: tools to make, clone and change demos of this app. ${o}.help() says how.`,document.head.append(n)),this.unmount=()=>{t(),window.removeEventListener("keydown",e,!0),window.removeEventListener("hashchange",i),q.forEach(t=>window.removeEventListener(t,s,{capture:!0})),o&&delete window[o],n?.remove(),this.overlay.unmount()},await this.arrived()}destroy(){this.closeRemote(),this.stopLoop(),this.stop(),this.unmount?.(),this.unmount=void 0}async arrived(){const t=sessionStorage.getItem(this.pendingKey());if(sessionStorage.removeItem(this.pendingKey()),t){const{demo:e,verb:s,from:i,loop:o}=JSON.parse(t);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(e.title,"film"===s?"Film":"Play",()=>"film"===s?this.film(e):this.play(e,{from:i}),!0)}if(await this.takeLink())return;const e=new URL(window.location.href),s=e.searchParams.get("demo");if(s){e.searchParams.delete("demo"),window.history.replaceState(window.history.state,"",e.toString());const t=(await this.entries()).find(t=>t.demo.id===s);t&&this.whenClicked(t.demo.title,"Play",()=>this.play(t.demo),!0)}}async takeLink(){const t=await S();if(!t)return!1;const e=c(t,this.pluginKinds());return e.length?(this.say(`The link's demo: ${e[0].path} ${e[0].message}`,!0),!0):(await this.save(t),this.say(`"${t.title}" came with the link: it is kept here.`),"idle"===this.state.session.mode&&this.openStudio(t),!0)}agentName(){const t="function"==typeof this.options.agent?this.options.agent():this.options.agent;return!1===t?void 0:t??"demoEngine"}async claudePrompt(t){const e=this.agentName();if(e)return O({url:window.location.href.replace(/#.*$/,""),agent:e,demo:t,link:t&&await this.link(t)})}gate(t){const e=this.state.session;if(!t.isTrusted||"playing"!==e.mode||e.paused||e.looping)return;const s=t.composedPath();if(s.includes(this.overlay.host))return;if(e.guided&&e.instruction){const i=e.player.viewerTarget();if(i&&(s.includes(i)||t instanceof KeyboardEvent&&i.contains(document.activeElement)))return;if(!i&&t instanceof KeyboardEvent)return}const i=t.defaultPrevented;t.cancelable&&t.preventDefault(),t.stopImmediatePropagation(),i||"pointerdown"!==t.type&&"keydown"!==t.type&&"wheel"!==t.type||this.hint(e.guided?'Only the ringed part now: or "Do it for me"':"Playing: Space pauses, and the app is yours then. Esc stops.")}hint(t){window.clearTimeout(this.hintTimer),this.set({hint:t}),this.hintTimer=window.setTimeout(()=>this.set({hint:void 0}),3e3)}pendingKey(){return`protomaze-demo-engine:${this.options.app}:pending`}key(t){if(!t.isTrusted)return;const e=t.composedPath(),s=e.some(t=>t instanceof HTMLElement&&(t.isContentEditable||t.matches("input, textarea, select"))),i=e.includes(this.overlay.host),o=this.state.session,n=()=>{t.preventDefault(),t.stopPropagation()};if("ready"!==o.mode)if("recording"!==o.mode){if("l"===t.key.toLowerCase()&&t.ctrlKey&&t.shiftKey&&this.looping)return n(),this.stopLoop();if(!("playing"!==o.mode||o.looping||o.checking||s&&(i||o.guided&&o.instruction))){if("Escape"===t.key)this.stop();else if(" "===t.key||"b"===t.key||"."===t.key)this.togglePause();else if("ArrowRight"===t.key||"Enter"===t.key||"PageDown"===t.key)o.player.next();else if("ArrowLeft"===t.key||"PageUp"===t.key)o.player.back();else if("Home"===t.key)o.player.goTo(0);else if("End"===t.key)o.player.goTo(o.steps-1);else{if(!/^[1-9]$/.test(t.key)||t.ctrlKey||t.metaKey||t.altKey)return;o.player.goTo(Number(t.key)-1)}n()}}else"Escape"!==t.key||s||(n(),this.stopRecording?.());else"Escape"===t.key&&(n(),o.cancel())}async entries(){return await this.store.ready(),this.entriesNow()}entriesNow(){const{demos:t,videos:e}=this.store.get(),s=new Map(t.map(t=>[t.id,t])),i=this.language(),n=(this.options.demos??[]).map(t=>"demo"in t?t:{demo:t,scenario:void 0});return[...n.map(({demo:t,scenario:n})=>{const a=s.get(t.id);return a?{demo:a,scenario:a.scenario??n??o(a,i),origin:"edited",video:e.get(t.id)}:{demo:t,scenario:n??o(t,i),origin:"app",video:e.get(t.id)}}),...t.filter(t=>!n.some(e=>e.demo.id===t.id)).map(t=>({demo:t,scenario:t.scenario??o(t,i),origin:"here",video:e.get(t.id)}))]}async save(e){const s=c(e,this.pluginKinds());if(s.length)throw new Error(`Not a demo: ${s.map(t=>`${t.path} ${t.message}`).join("; ")}`);await this.store.saveDemo(t(e))}async remove(t){await this.store.deleteDemo(t),this.state.studio?.demo.id===t&&this.closeStudio()}parse(t){return d(t,this.pluginKinds())}create(t){return s(t,this.options.start?.current())}openStudio(e){this.set({studio:{demo:t(e),opened:Date.now()}})}closeStudio(){this.set({studio:void 0})}activated(){const t=navigator.userActivation;return!t||t.isActive}whenClicked(t,e,s,i=!1){const o=()=>{this.setSession({mode:"idle"}),this.speech.wake(),s().catch(t=>this.say(t.message,!0))};if(!i&&this.activated())return o();this.setSession({mode:"ready",title:t,verb:e,go:o,cancel:()=>this.setSession({mode:"idle"})})}async goToStart(t,e,s,i){if(!t.start||!this.options.start)return!0;sessionStorage.setItem(this.pendingKey(),JSON.stringify({demo:t,verb:e,from:s,loop:i}));return"reload"!==await this.options.start.go(t.start)&&(sessionStorage.removeItem(this.pendingKey()),!0)}busy(){return"idle"!==this.state.session.mode&&"ready"!==this.state.session.mode}play(t,e={}){return new Promise(s=>this.whenClicked(t.title,"Play",async()=>{if(this.busy())return s(void 0);if(this.say(void 0),!await this.goToStart(t,"play",e.from))return s(void 0);const i=await this.run(t,e);s(i)}))}async run(t,e={}){const{settings:s}=this.state,i=e.language??this.language(),o=s.music.on&&!e.checking&&!e.guided&&await Promise.race([this.loadMusic(),new Promise(t=>setTimeout(()=>t(!1),e.filming?6e4:1500))]);this.speech.setPack(s.usePacks?await this.pack(t):void 0);const n=new K(t,{language:i,subtitles:s.subtitles,waitForPresenter:s.waitForPresenter&&!e.looping,catchUp:s.catchUp,music:Boolean(o),...e},{hand:this.hand,targets:this.targets,overlay:this.overlay,speech:this.speech,plugins:this.plugins,ready:this.options.ready,read:(t,e)=>this.read(t,e),reset:async()=>!t.start||!this.options.start||"reload"!==await this.options.start.go(t.start),update:t=>this.updateSession("playing",t)});this.setSession({mode:"playing",title:t.title,demo:t,steps:t.steps.length,filming:Boolean(e.filming),checking:Boolean(e.checking),guided:Boolean(e.guided),looping:Boolean(e.looping),presenting:Boolean(e.presenting),player:n,step:e.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"}),e.checking||a.navigated||(this.set({lastRun:{json:JSON.stringify(t),language:i,timing:a.timing}}),a.error&&"Stopped."!==a.error&&this.say(a.error,!0)),a}stop(){const t=this.state.session;"playing"===t.mode&&t.player.stop(),"recording"===t.mode&&this.stopRecording?.(),"ready"!==t.mode&&"preparing"!==t.mode||this.setSession({mode:"idle"})}togglePause(){const t=this.state.session;"playing"===t.mode&&(t.paused?t.player.resume():t.player.pause())}resume(){const t=this.state.session;"playing"===t.mode&&t.player.resume()}next(){const t=this.state.session;"playing"===t.mode&&t.player.next()}back(){const t=this.state.session;"playing"===t.mode&&t.player.back()}openPresenter(t={}){return J(this,t)}presenterKey(t){this.key(t)}present(t,e={}){this.openDialog({kind:"present",demo:t,from:e.from})}openDialog(t){this.set({dialog:t,...this.state.library&&this.options.launcher?{library:void 0}:{}})}closeDialog(){this.set({dialog:void 0})}openSettings(){this.set({library:"settings"})}showLibrary(t){this.set({library:t})}openAssistant(t){!0===this.options.assistant&&this.assistant.open(t)}goTo(t){const e=this.state.session;return"playing"===e.mode&&e.player.goTo(t)}guide(t,e={}){return this.play(t,{...e,guided:!0})}doItForMe(){const t=this.state.session;"playing"===t.mode&&t.player.doItForMe()}async openRemote(){if(!1===this.options.remote)throw new Error("No phone remote in this app");if(this.state.remote)return this.state.remote;const t=this.options.remote?.relay??U;this.remoteLink=await V.open(t,{command:t=>this.fromRemote(t),hello:()=>this.remoteSent="",peers:t=>this.state.remote&&this.set({remote:{...this.state.remote,peers:t}})});const e={url:this.remoteLink.url,svg:z(this.remoteLink.url),peers:0};return this.set({remote:e}),this.remoteTimer=window.setInterval(()=>this.toRemote(!0),1e3),e}closeRemote(){window.clearInterval(this.remoteTimer),this.remoteLink?.close(),this.remoteLink=void 0,this.remoteSent="",this.set({remote:void 0})}fromRemote(t){const e=this.state.session;"playing"===e.mode&&("next"===t.do?e.player.next():"back"===t.do?e.player.back():"goto"===t.do&&void 0!==t.step?e.player.goTo(t.step):"stop"===t.do?this.stop():"toggle"===t.do&&(e.waiting?e.player.next():this.togglePause()))}toRemote(t=!1){if(!this.remoteLink)return;const e=this.remoteState(),{at:s,elapsed:i,stepElapsed:o,...n}=e,a=JSON.stringify(n);(a!==this.remoteSent||t&&e.playing)&&(this.remoteSent=a,this.remoteLink.send(e))}remoteState(){const t=this.state.session,e=Date.now();if("playing"!==t.mode||t.checking)return{playing:!1,title:"",steps:[],step:0,caption:"",paused:!1,waiting:!1,filming:!1,elapsed:0,stepElapsed:0,planned:0,at:e};const s=this.language(),o=this.timing(t.demo,s),a=o.steps.find(e=>e.step===t.step),r=t.player.elapsed();return{playing:!0,title:t.demo.title,steps:t.demo.steps.map((t,e)=>({title:t.title??`Step ${e+1}`,script:n(i(t,s)),...t.notes?{notes:t.notes}:{}})),step:t.step,caption:t.caption,paused:t.paused,waiting:t.waiting,filming:t.filming,elapsed:r,stepElapsed:r-t.player.stepStartedAt,planned:o.duration,...a?{plannedStep:a.end-a.start}:{},at:e}}pack(t){let e=this.packs.get(t.id);return e||(e=(async()=>{const e=await this.store.asset(`narration:${t.id}`);if(e)return M(await e.arrayBuffer());const s=this.options.narration?.(t);if(!s)return;const i=await fetch(s);return i.ok?M(await i.arrayBuffer()):void 0})().catch(()=>{}),this.packs.set(t.id,e)),e}async makePack(t,s=()=>{}){const i=await this.pack(t);this.speech.setPack(i);const o=e(t).flatMap(e=>t.steps.flatMap(t=>n(t.say[e]??"").map(t=>({language:e,text:t})))),a=o.filter((t,e)=>o.findIndex(e=>e.language===t.language&&e.text===t.text)===e),r=[];for(const t of a)s(r.length,a.length),r.push({...await this.speech.packable(t.text,t.language),...t});s(r.length,a.length);const h=N(t.id,r);return await this.store.saveAsset(`narration:${t.id}`,h),this.packs.delete(t.id),h}async downloadPack(t){try{const e=await this.makePack(t,(t,e)=>this.say(`Making the narration pack: ${t} / ${e}`));b(e,`${t.id}.narration.zip`),this.say(`Narration pack: ${Math.round(e.size/1e5)/10} MB, kept here too. Check it in beside ${t.id}.demo.json, for every viewer.`)}catch(t){this.say(`Narration pack: ${t.message}`,!0)}}async dropPack(t){await this.store.saveAsset(`narration:${t.id}`,void 0),this.packs.delete(t.id)}async setMusic(t){await this.store.saveAsset("music",t),this.musicLoaded=void 0;const{music:e}=this.state.settings;this.changeSettings({music:t?{...e,on:!0,track:"file",name:t.name??"music"}:{...e,track:"calm",name:void 0}})}async loadMusic(){const{music:t}=this.state.settings,e="file"===t.track?`file:${t.name}`:t.track;if(this.musicLoaded!==e){if("file"===t.track){const e=await this.store.asset("music");if(!e)return!1;await this.speech.setMusic(e,t.volume).catch(()=>{})}else this.speech.setMusicBuffer(await L(t.track),t.volume);this.musicLoaded=e}return this.speech.setMusicVolume(t.volume),this.speech.hasMusic}async listenToMusic(t=20){if(this.speech.wake(),!await this.loadMusic())return()=>{};this.speech.startMusic();const e=setTimeout(()=>this.speech.stopMusic(),1e3*t);return()=>{clearTimeout(e),this.speech.stopMusic(.6)}}async loop(t,e={},s=0){if(0===t.length)return;this.stopLoop();let i=!1,o=0,n=s;const a=e.idle??this.state.settings.loopIdle,r=e.gap??1500,h=t.map(t=>t.title),p=t=>{if(!t.isTrusted||t.composedPath().includes(this.overlay.host))return;o=performance.now();const e=this.state.session;"playing"===e.mode&&e.looping&&e.player.stop(!0)},l=["pointerdown","keydown","wheel","touchstart"];l.forEach(t=>window.addEventListener(t,p,{capture:!0,passive:!0}));this.looping={demos:t,options:e,stop:()=>{i=!0,l.forEach(t=>window.removeEventListener(t,p,{capture:!0}));const t=this.state.session;"playing"===t.mode&&t.looping&&t.player.stop(),this.set({loop:void 0})}};const d=t=>new Promise(e=>setTimeout(e,t));for(;!i;){const s=t[n%t.length];this.set({loop:{titles:h,index:n%t.length,visitor:!1}});if(!await this.goToStart(s,"loop",void 0,{demos:t,index:n%t.length,gap:e.gap,idle:e.idle,reload:"reload"===e.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%t.length,visitor:!0,resumesAt:Date.now()+a-(performance.now()-o)}}),await d(1e3);if(i)break;if("reload"===e.reset)return sessionStorage.setItem(this.pendingKey(),JSON.stringify({demo:s,verb:"loop",loop:{demos:t,index:n%t.length,gap:e.gap,idle:e.idle,reload:!0}})),window.location.reload();await(e.reset?.())}else n++,await d(r)}}stopLoop(){this.looping?.stop(),this.looping=void 0}elapsed(){const t=this.state.session;return"playing"===t.mode?t.player.elapsed():void 0}async check(t,e={}){const s=c(t,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}`};const{animations:i,fromStart:o,...n}=e,a=i?()=>{}:u(document,[this.overlay.root]);try{if(!1!==o&&t.start&&this.options.start){if("reload"===await this.options.start.go(t.start))return{ok:!1,problems:s,failures:[],duration:0,error:"Its start reloads the page: check again once it is back"}}const e=await this.run(t,{...n,speed:n.speed??8,keepGoing:!0,checking:!0,catchUp:!0,subtitles:!1}),i=e.failures.map(e=>({...e,action:t.steps[e.step].actions[e.index]}));return{ok:!e.error&&0===i.length,error:e.error,failures:i,problems:s,duration:e.timing.duration}}finally{a()}}timing(t,e=this.language()){const s=this.state.lastRun;return s&&s.language===e&&s.json===JSON.stringify(t)&&s.timing.steps.length===t.steps.length?s.timing:l(t,{language:e,sayTime:t=>this.speech.duration(t,e),actionTime:t=>{const e=this.pluginAction(t.do);return e?.duration?.(t)??p(t)}})}film(t,e={}){return new Promise(s=>this.whenClicked(t.title,"Film",async()=>this.busy()?s(void 0):(this.say(void 0),await this.goToStart(t,"film")?void s(await this.filmNow(t,e)):s(void 0))))}async filmNow(t,e){const s=e.language??this.language();let o=!1;const a=await j({soundtrack:this.speech.soundtrack(),microphone:e.microphone,crop:this.options.filmElement?.(),...this.filmQuality(),onEnded:()=>{o=!0,this.stop()}});let r;try{const e=t.steps.flatMap(t=>n(i(t,s)));this.setSession({mode:"preparing",title:t.title,text:"Preparing the narration"}),await this.speech.prepare(e,s,(t,e)=>this.updateSession("preparing",{text:`Preparing the narration: ${t} / ${e}`})),o||"preparing"!==this.state.session.mode||(r=await this.run(t,{language:s,filming:a}))}finally{"preparing"===this.state.session.mode&&this.setSession({mode:"idle"})}const{video:p,voice:l}=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 d=r.timing.cues;l&&"off"===this.state.settings.speech.voice&&(this.setSession({mode:"preparing",title:t.title,text:"Transcribing what was said"}),d=await this.transcribe(l,s).catch(()=>d),this.setSession({mode:"idle"}));const c={id:t.id,blob:p,at:Date.now(),json:JSON.stringify(t),vtt:h(d),timing:r.timing,language:s,look:this.look(s),...l?{voice:l}:{}};return await this.store.saveVideo(c),this.say(`Filmed "${t.title}": ${Math.round(p.size/1e6)} MB, kept here.`),c}filmQuality(){const{frameRate:t,bitrate:e,lines:s,aspect:i,fit:o}=this.state.settings.film;return{frameRate:t,bitrate:e,fit:o,...s?{size:$(s,i)}:{}}}look(t){const{settings:e}=this.state,s=this.options.appTheme?.(),i=this.options.language?.();return{...s?{theme:s}:{},...i?{locale:i}:{},voice:e.speech.voice,language:t,subtitles:e.subtitles}}async transcribe(t,e=this.language()){const{settings:s}=this.state;return v(t,{language:e,with:s.transcriber,model:s.whisperModel,elevenLabsKey:s.speech.elevenlabs.key,progress:t=>this.set({speech:t<1?{loading:t}:{}})})}record(t={}){return new Promise(e=>this.whenClicked(t.into?.title??"New demo","Record",async()=>{if(this.busy())return e();this.say(void 0),await this.recordNow(t,e)}))}async recordNow(e,i){const{settings:o}=this.state,n=this.language();let a,r;try{o.filmRecording?a=await j({soundtrack:this.speech.soundtrack(),microphone:o.microphone,crop:this.options.filmElement?.(),...this.filmQuality(),onEnded:()=>{this.stopRecording?.()}}):o.microphone&&(r=await R())}catch(t){return this.say(`Could not start: ${t.message}`,!0),i()}const p=this.options.start?.current(),l=new B(this.targets,this.plugins,n,t=>this.updateSession("recording",t));a?.resume();const d=performance.now();this.setSession({mode:"recording",filming:Boolean(a),microphone:Boolean(r||a&&o.microphone),step:0,caption:"",actions:0}),this.nextStepRecording=()=>l.nextStep(),this.sayRecording=t=>l.say(t),this.stopRecording=async()=>{this.stopRecording=this.nextStepRecording=this.sayRecording=void 0;const c=Boolean(r||a&&o.microphone),m=l.stop(c),g=performance.now()-d;this.setSession({mode:"preparing",title:"Recording",text:"Keeping what was recorded"});try{const[i,o]=await Promise.all([r?.stop(),a?.stop()]),l=i??o?.voice;let d=[];if(l){this.updateSession("preparing",{text:"Transcribing what was said"});try{d=await this.transcribe(l,n);const t=w(m.stepStarts,d);m.steps.forEach((e,s)=>{!e.say[n]&&t[s]&&(e.say[n]=t[s])})}catch(t){this.say(`Transcribing failed: ${t.message}`,!0)}}const c=m.steps.filter(t=>t.actions.length>0||Object.values(t.say).some(Boolean)),u=e.into?t(e.into):{...s("Recorded demo",p),steps:[]},y=e.after??u.steps.length-1,f={...u,steps:[...u.steps.slice(0,y+1),...c,...u.steps.slice(y+1)]};0===f.steps.length&&f.steps.push({say:{},actions:[]}),o&&await this.store.saveVideo({id:f.id,blob:o.video,at:Date.now(),json:JSON.stringify(f),vtt:h(d),language:n,look:{...this.look(n),voice:"off",subtitles:!1},timing:{duration:g,steps:m.stepStarts.map((t,e)=>({step:e,start:t,end:m.stepStarts[e+1]??g})),cues:d.map(t=>({...t,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":""}.`),e.into&&this.state.studio?.demo.id===e.into.id?this.set({studio:{...this.state.studio,recorded:{steps:f.steps,at:Date.now()}}}):this.openStudio(f)}catch(t){this.setSession({mode:"idle"}),this.say(t.message,!0)}i()}}nextStep(){this.nextStepRecording?.()}narrate(t){this.sayRecording?.(t)}async finishRecording(){await(this.stopRecording?.())}link(t){return E(t)}downloadDemo(t,e="json"){if("md"===e)return b(t.scenario??o(t,this.language()),P(t.id,"md"),"text/markdown");const{scenario:s,savedAt:i,...n}=t;b(JSON.stringify(n,null,2)+"\n",P(t.id,"demo.json"),"application/json")}downloadVideo(t,e,s=!1){return"vtt"===s?b(t.vtt,P(e,"vtt"),"text/vtt"):"srt"===s?b(r(a(t.vtt)),P(e,"srt"),"application/x-subrip"):void b(t.blob,P(e,x(t.blob)))}shareVideo(t,e){return T([new File([t.blob],P(e,x(t.blob)),{type:t.blob.type}),new File([t.vtt],P(e,"vtt"),{type:"text/vtt"})],e)}languagesOf(t){return e(t)}}export{Q as DEFAULT_SETTINGS};
@@ -80,7 +80,7 @@ export declare class Player {
80
80
  private t0;
81
81
  private silence;
82
82
  private speed;
83
- /** How long a target may take to show: shorter in the cleanup, where what is absent is skipped. */
83
+ /** How long a target may take to show: shorter in the cleanup, where what is absent is skipped, and after a failure. */
84
84
  private findTimeout;
85
85
  /** On to the next step: what is left of this one quickly, silently. */
86
86
  private hurrying;
package/engine/Player.js CHANGED
@@ -1 +1 @@
1
- import{DEFAULT_WAIT as t,isBuiltIn as e,isPresent as s,sayOf as i,sentences as o}from"../model/Demo.js";import{readingTime as a}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.findTimeout=1e4,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,this.findTimeout,()=>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?[]:o(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 o=this.elapsed();this.stepStart=o;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(a(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,o]of i.actions.entries()){if(this.stopped||this.dropping)break;if(void 0===o.cue||v||u||await(y[o.cue]??b),await this.sleep(o.wait??t),await this.whilePaused(),this.stopped||this.dropping)break;if(this.hurrying&&s(o))continue;const i=this.elapsed(),a={step:x,index:e,start:i,end:i};w.actions.push(a);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,p);if(a.end=this.elapsed(),e){const t=()=>{m.delete(t)&&(e(),a.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(a.end=this.elapsed(),a.error=s,this.stopped)break;if(!n.keepGoing)throw new Error(`Step ${x+1}, action ${e+1} (${o.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:o,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 o=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 a=p(t,this.context.targets);let n=!1;this.skipViewer=()=>{n=!0,a.cancel()},await a.done,this.target=void 0,this.skipViewer=()=>{},o.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,o]=[this.stopped,this.speed];this.stopped=!1,this.hurrying=!1,this.speed=Math.max(o,12),this.findTimeout=500,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.findTimeout=1e4,[this.stopped,this.speed]=[i,o]}}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 o=this.speed;this.speed=Math.max(o,12),this.context.update({catchingUp:!0});try{for(let o=e;o<i&&!this.stopped;o++){this.context.update({step:o});for(const e of this.demo.steps[o].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 ${o+1}: ${t.message}`)}}}}await this.sleep(1500)}finally{this.speed=o,this.context.update({catchingUp:!1})}}async perform(t,s){const{hand:i,overlay:o}=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 a={hand:i,overlay:o,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,a)}const a=t=>o.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&&o.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),o=t.to.target?await this.find(t.to.target):e;return i.drag(e,s,r(o,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??this.findTimeout);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 o.clear();case"card":return a({kind:"card",title:t.title,text:t.text});case"callout":{const e=t.target?await this.find(t.target):void 0;return a({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 a({kind:"spotlight",element:s,text:t.text,padding:t.padding});case"ring":return a({kind:"ring",element:s,text:t.text,color:t.color,shape:t.shape,padding:t.padding});case"arrow":return a({kind:"arrow",element:s,text:t.text,from:t.from,color:t.color});case"blur":return a({kind:"blur",element:s});case"zoom":{const e=a({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 o,shownIn as a}from"../model/Demo.js";import{readingTime as n}from"../model/Timing.js";import{at as r}from"../page/Input.js";import{pointIn as h}from"../page/Targets.js";import{isGuided as p,waitForViewer as c}from"./Guided.js";const d=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.findTimeout=1e4,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 d(50);continue}const t=Math.min(e,50),s=performance.now();await d(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 d(50)}async find(t){const e=await this.context.targets.find(t,this.findTimeout,()=>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:a,context:r}=this,h=a.language,c=Math.max(0,Math.min(a.from??0,e.steps.length-1)),l=Math.min(a.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,c>0&&!1!==a.catchUp&&await this.catchUp(0,c);const f=e.steps.map(t=>u?[]:o(i(t,h))),y=[...f.slice(c),...f.slice(0,c)].flat();y.forEach(t=>r.speech.make(t,h)?.catch(()=>{}));const v=y.map(t=>r.speech.make(t,h))[0]?.catch(()=>{});v&&await Promise.race([v,d(a.filming?6e5:3e3)]),await(r.ready?.()),this.t0=performance.now(),this.held=0,a.filming?.resume(),a.music&&!u&&r.speech.startMusic();let x=c;for(;x<=l&&!this.stopped;){const i=e.steps[x];this.stepNow=x,r.update({step:x,caption:""}),r.overlay.raise();const o=this.elapsed();this.stepStart=o;const d=[],y=f[x].map((t,e)=>new Promise(t=>d[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,h,a.filming?1/0:0===t&&x===c?0:1500);await this.whilePaused();const i=this.elapsed();d[t](),!1!==a.subtitles&&r.overlay.subtitle(e),r.update({caption:e}),s?(this.silence=s.stop,this.hurrying&&s.stop(),await s.done):await this.sleep(n(e)),w.cues.push({step:x,start:i,end:this.elapsed(),text:e})}v=!0,d.forEach(t=>t()),k(),r.overlay.subtitle(void 0),r.update({caption:""})},T=async()=>{for(const[e,o]of i.actions.entries()){if(this.stopped||this.dropping)break;if(void 0===o.cue||v||u||await(y[o.cue]??b),await this.sleep(o.wait??t),await this.whilePaused(),this.stopped||this.dropping)break;if(this.hurrying&&s(o))continue;const i=this.elapsed(),n={step:x,index:e,start:i,end:i};w.actions.push(n);try{const t=a.guided&&p(o)&&!this.hurrying;t&&await this.viewerDoes(o);const e=t&&this.viewerDid?void 0:await this.perform(o,h);if(n.end=this.elapsed(),e){const t=()=>{m.delete(t)&&(e(),n.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(n.end=this.elapsed(),n.error=s,this.stopped)break;if(!a.keepGoing)throw new Error(`Step ${x+1}, action ${e+1} (${o.do}): ${s}`);g.push({step:x,index:e,error:s}),this.findTimeout=Math.min(this.findTimeout,2e3)}}};if(await Promise.all([$(),T()]),i.hold&&await this.sleep(i.hold),[...m].forEach(t=>t()),w.steps.push({step:x,start:o,end:this.elapsed()}),this.hurrying=!1,void 0===this.jump&&(i.pause||a.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 o=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 a=c(t,this.context.targets);let n=!1;this.skipViewer=()=>{n=!0,a.cancel()},await a.done,this.target=void 0,this.skipViewer=()=>{},o.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,o]=[this.stopped,this.speed];this.stopped=!1,this.hurrying=!1,this.speed=Math.max(o,12),this.findTimeout=500,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.findTimeout=1e4,[this.stopped,this.speed]=[i,o]}}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 d(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 o=this.speed;this.speed=Math.max(o,12),this.context.update({catchingUp:!0});try{for(let o=e;o<i&&!this.stopped;o++){this.context.update({step:o});for(const e of this.demo.steps[o].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 ${o+1}: ${t.message}`)}}}}await this.sleep(1500)}finally{this.speed=o,this.context.update({catchingUp:!1})}}async perform(t,s){const{hand:i,overlay:o}=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 a={hand:i,overlay:o,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,a)}const n=t=>o.show(t);switch(t.do){case"click":{const e=await this.find(t.target);return e.scrollIntoView({block:"nearest",inline:"nearest"}),i.click(e,r(e,t.at),t)}case"hover":{const e=await this.find(t.target);return e.scrollIntoView({block:"nearest",inline:"nearest"}),i.point(e,r(e,t.at))}case"type":{const e=await this.find(t.target);return e.scrollIntoView({block:"nearest",inline:"nearest"}),await i.point(e,r(e)),i.type(e,t.text)}case"key":{const e=t.target?await this.find(t.target):void 0;return this.speed<=1&&o.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,r(e))}case"drag":{const e=await this.find(t.target);e.scrollIntoView({block:"nearest",inline:"nearest"});const s=r(e,t.at),o=t.to.target?await this.find(t.to.target):e;return i.drag(e,s,h(o,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??this.findTimeout);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 d(100)}return}case"clear":return void o.clear();case"card":return n({kind:"card",title:a(t.title,s)??"",text:a(t.text,s)});case"callout":{const e=t.target?await this.find(t.target):void 0;return n({kind:"callout",text:a(t.text,s)??"",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 i=this.follow(t.target,e);switch(t.do){case"spotlight":return n({kind:"spotlight",element:i,text:a(t.text,s),padding:t.padding});case"ring":return n({kind:"ring",element:i,text:a(t.text,s),color:t.color,shape:t.shape,padding:t.padding});case"arrow":return n({kind:"arrow",element:i,text:a(t.text,s),from:t.from,color:t.color});case"blur":return n({kind:"blur",element:i});case"zoom":{const e=n({kind:"zoom",element:i,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}`:""}`}
package/engine/Read.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import type { DemoAction } from '../model/Demo';
1
+ import { DemoAction, Language } from '../model/Demo';
2
2
  import type { Labels } from '../page/Targets';
3
3
  import type { DemoPlugin } from './Plugin';
4
4
  /** An action as a sentence; `shown`: its target as the page shows it now, named as it reads there. */
5
- export declare function readAction(action: DemoAction, labels?: Labels, plugins?: DemoPlugin[], shown?: Element): string;
5
+ export declare function readAction(action: DemoAction, labels?: Labels, plugins?: DemoPlugin[], shown?: Element, language?: Language): string;
package/engine/Read.js CHANGED
@@ -1 +1 @@
1
- export function readAction(t,e,r=[],a){const o=a?.innerText?.trim().replace(/\s+/g," "),n=r=>{if(!r)return"";if(r===t.target&&o&&o.length<=40)return`"${o}"`;const a=r.key?e?.textOf(r.key)??r.key:r.text;return a?`"${a}"`:r.css},c=t;switch(t.do){case"click":return`${c.double?"Double-click":c.right?"Right-click":"Click"} ${n(c.target)}`;case"hover":return`Point at ${n(c.target)}`;case"type":return`Type "${c.text}" in ${n(c.target)}`;case"key":return`Press ${c.key}${c.target?` in ${n(c.target)}`:""}`;case"select":return`Choose "${c.option}" in ${n(c.target)}`;case"drag":return`Drag ${n(c.target)}${c.to?.target?` to ${n(c.to.target)}`:""}`;case"scroll":return c.by?`Scroll by ${c.by.join(", ")}`:`Scroll to ${n(c.target)}`;case"waitFor":return`Wait ${c.gone?"till gone":"for"} ${n(c.target)}`;case"spotlight":return`Spotlight ${n(c.target)}`;case"ring":return`Ring ${n(c.target)}`;case"arrow":return`Arrow at ${n(c.target)}${c.text?`: ${c.text}`:""}`;case"callout":return`Note: ${c.text}`;case"blur":return`Blur ${n(c.target)}`;case"card":return`Card: ${c.title}`;case"zoom":return`Zoom to ${n(c.target)}`;case"clear":return"Clear effects";default:return r.map(e=>e.actions?.[t.do]).find(Boolean)?.read?.(t)??t.do}}
1
+ import{shownIn as t}from"../model/Demo.js";export function readAction(e,r,a=[],o,n="en"){const c=o?.innerText?.trim().replace(/\s+/g," "),s=t=>{if(!t)return"";if(t===e.target&&c&&c.length<=40)return`"${c}"`;const a=t.key?r?.textOf(t.key)??t.key:t.text;return a?`"${a}"`:t.css},i=e;switch(e.do){case"click":return`${i.double?"Double-click":i.right?"Right-click":"Click"} ${s(i.target)}`;case"hover":return`Point at ${s(i.target)}`;case"type":return`Type "${i.text}" in ${s(i.target)}`;case"key":return`Press ${i.key}${i.target?` in ${s(i.target)}`:""}`;case"select":return`Choose "${i.option}" in ${s(i.target)}`;case"drag":return`Drag ${s(i.target)}${i.to?.target?` to ${s(i.to.target)}`:""}`;case"scroll":return i.by?`Scroll by ${i.by.join(", ")}`:`Scroll to ${s(i.target)}`;case"waitFor":return`Wait ${i.gone?"till gone":"for"} ${s(i.target)}`;case"spotlight":return`Spotlight ${s(i.target)}`;case"ring":return`Ring ${s(i.target)}`;case"arrow":return`Arrow at ${s(i.target)}${i.text?`: ${t(i.text,n)}`:""}`;case"callout":return`Note: ${t(i.text,n)??""}`;case"blur":return`Blur ${s(i.target)}`;case"card":return`Card: ${t(i.title,n)??""}`;case"zoom":return`Zoom to ${s(i.target)}`;case"clear":return"Clear effects";default:return a.map(t=>t.actions?.[e.do]).find(Boolean)?.read?.(e)??e.do}}
@@ -1,3 +1,4 @@
1
+ import { ClaudeSettings } from '../agent/Assistant';
1
2
  import type { Language } from '../model/Demo';
2
3
  import { SpeechSettings } from '../speech/Speech';
3
4
  import type { MusicTrack } from '../speech/Music';
@@ -47,6 +48,8 @@ export type DemoSettings = {
47
48
  usePacks: boolean;
48
49
  /** Presenting, the presenter's screen: a window, always on top, the phone, or none. */
49
50
  presenterScreen: 'window' | 'onTop' | 'phone' | 'none';
51
+ /** "Ask Claude": the person's own API key, the model, how hard it thinks. */
52
+ claude: ClaudeSettings;
50
53
  };
51
54
  export declare const DEFAULT_SETTINGS: DemoSettings;
52
55
  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,usePacks:!0,presenterScreen:"window"};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_CLAUDE as e}from"../agent/Assistant.js";import{DEFAULT_SPEECH as t}from"../speech/Speech.js";export const DEFAULT_SETTINGS={speech:t,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,presenterScreen:"window",claude:e};export function loadSettings(s){try{const c=JSON.parse(localStorage.getItem(s)??"{}");return{...DEFAULT_SETTINGS,...c,speech:{...t,...c.speech,elevenlabs:{...t.elevenlabs,...c.speech?.elevenlabs}},music:{...DEFAULT_SETTINGS.music,...c.music?.name?{track:"file"}:{},...c.music},film:{...DEFAULT_SETTINGS.film,...c.film},claude:{...e,...c.claude}}}catch{return DEFAULT_SETTINGS}}export function saveSettings(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch{}}
package/index.d.ts CHANGED
@@ -19,10 +19,12 @@ export * from './video/Film';
19
19
  export * from './store/Store';
20
20
  export * from './store/Share';
21
21
  export * from './agent/Agent';
22
+ export * from './agent/Assistant';
22
23
  export { GUIDE } from './agent/Guide';
23
24
  export { DemoLibrary, Library, Settings, Shadow } from './ui/Library';
24
25
  export { Dialog } from './ui/Dialogs';
25
26
  export { Studio } from './ui/Studio';
27
+ export { AssistantPanel } from './ui/Assistant';
26
28
  export { Timeline } from './ui/Timeline';
27
29
  export { openPresenter, mountPresenter } from './ui/Presenter';
28
30
  export { useEngine, useDemos } from './ui/Hooks';
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"./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,Settings,Shadow}from"./ui/Library.js";export{Dialog}from"./ui/Dialogs.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";
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*from"./agent/Assistant.js";export{GUIDE}from"./agent/Guide.js";export{DemoLibrary,Library,Settings,Shadow}from"./ui/Library.js";export{Dialog}from"./ui/Dialogs.js";export{Studio}from"./ui/Studio.js";export{AssistantPanel}from"./ui/Assistant.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
@@ -117,14 +117,14 @@ export type Lasting = {
117
117
  export type SpotlightAction = ActionBase & Lasting & {
118
118
  do: 'spotlight';
119
119
  target: DemoTarget;
120
- text?: string;
120
+ text?: Shown;
121
121
  padding?: number;
122
122
  };
123
123
  /** A ring around the target; `shape` 'circle' for round things. */
124
124
  export type RingAction = ActionBase & Lasting & {
125
125
  do: 'ring';
126
126
  target: DemoTarget;
127
- text?: string;
127
+ text?: Shown;
128
128
  color?: string;
129
129
  shape?: 'box' | 'circle';
130
130
  padding?: number;
@@ -133,14 +133,14 @@ export type RingAction = ActionBase & Lasting & {
133
133
  export type ArrowAction = ActionBase & Lasting & {
134
134
  do: 'arrow';
135
135
  target: DemoTarget;
136
- text?: string;
136
+ text?: Shown;
137
137
  from?: Side;
138
138
  color?: string;
139
139
  };
140
140
  /** A note: at the target, or in a corner of the screen. */
141
141
  export type CalloutAction = ActionBase & Lasting & {
142
142
  do: 'callout';
143
- text: string;
143
+ text: Shown;
144
144
  target?: DemoTarget;
145
145
  side?: Side;
146
146
  corner?: Corner;
@@ -153,8 +153,8 @@ export type BlurAction = ActionBase & Lasting & {
153
153
  /** A full-screen card: a title to open, a chapter, an end. */
154
154
  export type CardAction = ActionBase & Lasting & {
155
155
  do: 'card';
156
- title: string;
157
- text?: string;
156
+ title: Shown;
157
+ text?: Shown;
158
158
  };
159
159
  /** Magnifies the page around the target. */
160
160
  export type ZoomAction = ActionBase & Lasting & {
@@ -187,6 +187,14 @@ export declare const DEFAULT_WAIT = 800;
187
187
  /** The actions that take a target, and their targets; `drag` may have a second. */
188
188
  export declare function targetsOf(action: DemoAction): DemoTarget[];
189
189
  export declare function isTarget(value: unknown): value is DemoTarget;
190
+ /**
191
+ * Text on the screen - a card's, a note's, a label's: one for every language, or one per language
192
+ * as narration is, `{ en: '…', de: '…' }`.
193
+ */
194
+ export type Shown = string | Partial<Record<Language, string>>;
195
+ /** `text` in `language`: its own, else its base language's ("de" for "de-CH"), else the first it has. */
196
+ export declare function shownIn(text: Shown | undefined, language: Language): string | undefined;
197
+ export declare function isShown(value: unknown): value is Shown;
190
198
  /** A step's narration in `language`, else in the first language it has. */
191
199
  export declare function sayOf(step: DemoStep, language: Language): string;
192
200
  /** The languages a demo is narrated in, most used first. */
package/model/Demo.js CHANGED
@@ -1 +1 @@
1
- export const INTERACT_KINDS=["click","hover","type","key","select","drag","scroll","waitFor"];export const PRESENT_KINDS=["spotlight","ring","arrow","callout","blur","card","zoom","clear"];export const BUILT_IN_KINDS=[...INTERACT_KINDS,...PRESENT_KINDS];export function isBuiltIn(t){return BUILT_IN_KINDS.includes(t.do)}export function isPresent(t){return PRESENT_KINDS.includes(t.do)}export const DEFAULT_WAIT=800;export function targetsOf(t){const e=[],r=t.target;isTarget(r)&&e.push(r);const o=t.to?.target;return isTarget(o)&&e.push(o),e}export function isTarget(t){return"object"==typeof t&&null!==t&&"string"==typeof t.css}export function sayOf(t,e){return t.say[e]??Object.values(t.say).find(t=>t)??""}export function languagesOf(t){const e=new Map;return t.steps.forEach(t=>Object.entries(t.say).forEach(([t,r])=>{r&&e.set(t,(e.get(t)??0)+1)})),[...e.entries()].sort((t,e)=>e[1]-t[1]).map(([t])=>t)}export function sentences(t){return t.split(/(?<=[.!?…]["')\]]*)\s+/).map(t=>t.trim()).filter(Boolean)}export function scenarioOf(t,e){return[`# ${t.title}`,"",...t.description?[t.description,""]:[],...t.steps.map((t,r)=>`${r+1}. ${t.title?`**${t.title}.** `:""}${sayOf(t,e)||"…"}`),""].join("\n")}export function newDemo(t="New demo",e){return{id:idFrom(t),title:t,description:"",...e?{start:e}:{},steps:[{say:{},actions:[]}]}}export function idFrom(t){return`${t.toLowerCase().normalize("NFKD").replace(/[^\w\s-]/g,"").trim().replace(/[\s_]+/g,"-").slice(0,40)||"demo"}-${Math.random().toString(36).slice(2,6)}`}export function copyOf(t){return JSON.parse(JSON.stringify(t))}
1
+ export const INTERACT_KINDS=["click","hover","type","key","select","drag","scroll","waitFor"];export const PRESENT_KINDS=["spotlight","ring","arrow","callout","blur","card","zoom","clear"];export const BUILT_IN_KINDS=[...INTERACT_KINDS,...PRESENT_KINDS];export function isBuiltIn(t){return BUILT_IN_KINDS.includes(t.do)}export function isPresent(t){return PRESENT_KINDS.includes(t.do)}export const DEFAULT_WAIT=800;export function targetsOf(t){const e=[],r=t.target;isTarget(r)&&e.push(r);const o=t.to?.target;return isTarget(o)&&e.push(o),e}export function isTarget(t){return"object"==typeof t&&null!==t&&"string"==typeof t.css}export function shownIn(t,e){return void 0===t||"string"==typeof t?t:t[e]??t[e.split("-")[0]]??Object.values(t).find(Boolean)}export function isShown(t){return"string"==typeof t||"object"==typeof t&&null!==t&&!Array.isArray(t)&&Object.values(t).every(t=>"string"==typeof t)}export function sayOf(t,e){return t.say[e]??Object.values(t.say).find(t=>t)??""}export function languagesOf(t){const e=new Map;return t.steps.forEach(t=>Object.entries(t.say).forEach(([t,r])=>{r&&e.set(t,(e.get(t)??0)+1)})),[...e.entries()].sort((t,e)=>e[1]-t[1]).map(([t])=>t)}export function sentences(t){return t.split(/(?<=[.!?…]["')\]]*)\s+/).map(t=>t.trim()).filter(Boolean)}export function scenarioOf(t,e){return[`# ${t.title}`,"",...t.description?[t.description,""]:[],...t.steps.map((t,r)=>`${r+1}. ${t.title?`**${t.title}.** `:""}${sayOf(t,e)||"…"}`),""].join("\n")}export function newDemo(t="New demo",e){return{id:idFrom(t),title:t,description:"",...e?{start:e}:{},steps:[{say:{},actions:[]}]}}export function idFrom(t){return`${t.toLowerCase().normalize("NFKD").replace(/[^\w\s-]/g,"").trim().replace(/[\s_]+/g,"-").slice(0,40)||"demo"}-${Math.random().toString(36).slice(2,6)}`}export function copyOf(t){return JSON.parse(JSON.stringify(t))}
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")}),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}}
1
+ import{BUILT_IN_KINDS as t,isShown as e,isTarget as o}from"./Demo.js";const r={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:[]},n=new Set(["target"]),a=new Set(["spotlight","ring","arrow","callout","card"]),s=["top","right","bottom","left"],i=["top-left","top-right","bottom-left","bottom-right"];export function validate(d,f=[]){const g=[],l=(t,e)=>g.push({path:t,message:e});if("object"!=typeof d||null===d)return[{path:"",message:"not an object"}];const p=d;if("string"==typeof p.id&&p.id||l("id","needs a string"),"string"==typeof p.title&&p.title||l("title","needs a string"),void 0!==p.description&&"string"!=typeof p.description&&l("description","is a string"),void 0===p.start||"object"==typeof p.start&&!Object.values(p.start).some(t=>"string"!=typeof t)||l("start","is an object of strings"),!Array.isArray(p.steps))return l("steps","needs an array"),g;const u=[...t,...f];return p.steps.forEach((t,e)=>{const o=`steps[${e}]`;return"object"!=typeof t||null===t?l(o,"not an object"):("object"!=typeof t.say||null===t.say||Array.isArray(t.say)?l(`${o}.say`,"needs an object: language → narration, {} for none"):Object.entries(t.say).forEach(([t,e])=>{"string"!=typeof e&&l(`${o}.say.${t}`,"is a string")}),void 0!==t.notes&&"string"!=typeof t.notes&&l(`${o}.notes`,"is a string"),Array.isArray(t.actions)?void t.actions.forEach((t,e)=>y(t,`${o}.actions[${e}]`)):l(`${o}.actions`,"needs an array, [] for none"))}),void 0!==p.cleanup&&(Array.isArray(p.cleanup)?p.cleanup.forEach((t,e)=>y(t,`cleanup[${e}]`)):l("cleanup","needs an array of actions")),g;function y(t,d){if("object"!=typeof t||null===t)return l(d,"not an object");if(!u.includes(t.do))return l(`${d}.do`,`unknown action "${t.do}": one of ${u.join(", ")}`);for(const e of r[t.do]??[]){const r=t[e];void 0===r||""===r&&"text"!==e?l(`${d}.${e}`,"is required"):n.has(e)&&!o(r)&&l(`${d}.${e}`,"needs { css, text?, key?, index? }")}if(a.has(t.do))for(const o of["title","text"]){const r=t[o];void 0===r||e(r)||l(`${d}.${o}`,"is a text, or one per language: { en: '…', de: '…' }")}void 0!==t.wait&&("number"!=typeof t.wait||t.wait<0)&&l(`${d}.wait`,"is ms, 0 or more"),void 0!==t.cue&&(!Number.isInteger(t.cue)||t.cue<0)&&l(`${d}.cue`,"is a sentence's index, 0 or more");const f=t;if(void 0===f.at||c(f.at)||l(`${d}.at`,"is [x, y], fractions of the box"),void 0===f.from||s.includes(f.from)||l(`${d}.from`,`one of ${s.join(", ")}`),void 0===f.side||s.includes(f.side)||l(`${d}.side`,`one of ${s.join(", ")}`),void 0===f.corner||i.includes(f.corner)||l(`${d}.corner`,`one of ${i.join(", ")}`),"drag"===t.do){const t=f.to;t&&void 0!==t.target&&!o(t.target)&&l(`${d}.to.target`,"needs { css, text?, key?, index? }"),t&&void 0!==t.at&&!c(t.at)&&l(`${d}.to.at`,"is [x, y], fractions of the box"),t&&void 0===t.target&&void 0===t.at&&l(`${d}.to`,"needs a target, an at, or both")}}}function c(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.9",
3
+ "version": "0.1.11",
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",
@@ -35,6 +35,7 @@
35
35
  ],
36
36
  "author": "Tom Crauwels",
37
37
  "dependencies": {
38
+ "@anthropic-ai/sdk": "^1.12.0",
38
39
  "@protomaze/time": "^1.16.1",
39
40
  "qrcode-generator": "^2.0.4"
40
41
  },
package/page/Still.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  /**
2
- * Turns the page's CSS transitions and animations off until the returned function is called. A page
3
- * in a hidden tab never finishes them: what fades in would stay at opacity 0, and not be found.
4
- * The engine's own overlay is in a shadow root, which this does not reach.
2
+ * Turns CSS transitions and animations off until the returned function is called: the page's, and
3
+ * in `roots` - shadow roots such as the engine's overlay, which the page's styles do not reach. A
4
+ * page in a hidden tab never finishes them: what fades in would stay at opacity 0, and not be found
5
+ * or seen.
5
6
  */
6
- export declare function stillPage(document?: Document): () => void;
7
+ export declare function stillPage(document?: Document, roots?: ShadowRoot[]): () => void;
package/page/Still.js CHANGED
@@ -1 +1 @@
1
- export function stillPage(t=window.document){const e=t.createElement("style");return e.setAttribute("data-demo-ignore",""),e.textContent="*, *::before, *::after { transition: none !important; animation: none !important; }",t.head.append(e),()=>e.remove()}
1
+ export function stillPage(t=window.document,e=[]){const n=[t.head,...e].map(e=>{const n=t.createElement("style");return n.setAttribute("data-demo-ignore",""),n.textContent="*, *::before, *::after { transition: none !important; animation: none !important; }",e.append(n),n});return()=>n.forEach(t=>t.remove())}
package/page/Targets.js CHANGED
@@ -1 +1 @@
1
- export const IGNORED="[data-demo-ignore]";const t=["button","a[href]","input","textarea","select","summary","canvas","video",'[contenteditable=""]','[contenteditable="true"]','[role="button"]','[role="link"]','[role="tab"]','[role="option"]','[role="menuitem"]','[role="menuitemcheckbox"]','[role="menuitemradio"]','[role="switch"]','[role="checkbox"]','[role="radio"]','[role="slider"]','[role="combobox"]','[role="treeitem"]','[role="gridcell"]','[role="row"]',"li[role]","[data-demo]"];export function normal(t){return t.replace(/\s+/g," ").replace(/\d[\d.,]*/g,"#").trim().toLowerCase().slice(0,80)}export function dictionaryLabels(t,e){let n;const r=()=>{const e=t();if(n?.from===e)return n;const r=new Map,i=new Map,o=(t,e)=>Object.entries(t).forEach(([t,n])=>{const s=e+t;if("object"==typeof n&&n)o(n,s+".");else if("string"==typeof n&&!n.includes("{{")){const t=normal(n);r.set(t,r.has(t)?null:s),i.set(s,n)}});return o(e,""),n={from:e,keys:r,texts:i}};return{keyOf:t=>r().keys.get(normal(t))??void 0,textOf:t=>e?.(t)??r().texts.get(t)}}export class Targets{constructor(e={}){this.options=e,this.interactive=[...t,...e.interactive??[]].join(","),this.attributes=["aria-label","title",...e.labelAttributes??[]]}labelOf(t){const e=t,n=t.getAttribute("aria-labelledby")?.split(/\s+/).map(e=>t.ownerDocument.getElementById(e)?.textContent??"").join(" "),r=t.matches("input, select, textarea"),i=r?t.closest("label"):null,o=r?"":e.innerText?.trim()??"",s=t.getAttribute("data-demo")||(t instanceof HTMLInputElement&&["button","submit","reset"].includes(t.type)?t.value:"")||(/[\p{L}\p{N}]/u.test(o)?o:"")||n?.trim()||this.attributes.map(e=>t.getAttribute(e)).find(Boolean)||t.placeholder||t.alt||t.id&&t.ownerDocument.querySelector(`label[for="${CSS.escape(t.id)}"]`)?.textContent||i&&Array.from(i.childNodes).filter(t=>t.nodeType===Node.TEXT_NODE).map(t=>t.textContent).join(" ").trim()||t.name||o;if(s.trim())return normal(s);const a=t.querySelector("svg[data-testid], [data-icon]"),l=a?.getAttribute("data-testid")??a?.getAttribute("data-icon");if(l)return normal(l);let c=t.parentElement;for(let t=0;c&&t<4;t++,c=c.parentElement){const t=c.innerText??"";if(t.trim())return normal(t)}return""}cssOf(t){const e=t.tagName.toLowerCase(),n=t.getAttribute("role"),r="input"===e?t.getAttribute("type"):null,i=this.options.stableClass&&Array.from(t.classList).find(t=>this.options.stableClass.test(t));return e+(i?`.${CSS.escape(i)}`:"")+(n?`[role="${n}"]`:"")+(r?`[type="${r}"]`:"")}labelIn(t){if(t.key){const e=this.options.labels?.textOf(t.key);if(void 0!==e)return normal(e)}return void 0===t.text?void 0:normal(t.text)}targetElement(t){return!t||t.closest(IGNORED)?null:t.closest(this.interactive)??t}matches(t){const e=this.labelIn(t);let n;try{n=Array.from(document.querySelectorAll(t.css))}catch{return[]}return n.filter(t=>!t.closest(IGNORED)&&(void 0===e||this.labelOf(t)===e))}describe(t){const r=this.cssOf(t),i=this.labelOf(t),o=i&&!t.getAttribute("data-demo")?this.options.labels?.keyOf(i):void 0,s=t=>({css:t,...o?{key:o}:i?{text:i}:{}}),a=s(r);if(this.matches(a).length<=1)return a;for(let i=t.parentElement;i&&i!==document.body;i=i.parentElement){const o=n(i);if(!o)continue;const a=s(`${o} ${r}`),l=this.matches(a);if(1===l.length)return a;if(l.length>1)return{...a,...e(l,t)}}return{...a,...e(this.matches(a),t)}}async find(t,e=1e4,n=()=>!1){const r=performance.now()+e;do{const e=this.matches(t)[t.index??0];if(e&&shown(e))return e;await new Promise(t=>setTimeout(t,100))}while(performance.now()<r&&!n())}list({within:t,query:e,limit:n=400}={}){const i=t?Array.from(document.querySelectorAll(t)):[document.body],o=new Set,s=[],a=e?normal(e):void 0;for(const t of i)for(const e of Array.from(t.querySelectorAll(this.interactive))){if(s.length>=n)break;if(o.has(e)||e.closest(IGNORED)||!shown(e))continue;const i=e.parentElement?.closest(this.interactive);if(i&&!i.closest(IGNORED)&&t.contains(i)&&this.labelOf(i)===this.labelOf(e)&&!e.matches("input, select, textarea, canvas"))continue;o.add(e);const l=this.labelOf(e);if(a&&!l.includes(a))continue;const c=e.getBoundingClientRect();s.push({target:this.describe(e),label:l,tag:e.tagName.toLowerCase(),...e.getAttribute("role")?{role:e.getAttribute("role")}:{},...r(e),box:{x:Math.round(c.x),y:Math.round(c.y),width:Math.round(c.width),height:Math.round(c.height)}})}return s}}function e(t,e){const n=t.indexOf(e);return n>0?{index:n}:{}}function n(t){const e=t.getAttribute("data-demo");if(e)return`[data-demo="${e.replace(/"/g,'\\"')}"]`;const n=t.id;return n&&/^[a-z][\w-]*$/i.test(n)&&!/\d{3,}|[:]|^(mui|radix|react|headlessui|rc)-?/i.test(n)?`#${CSS.escape(n)}`:void 0}export function shown(t){const e=t.checkVisibility;if(e){if(!e.call(t,{checkVisibilityCSS:!0}))return!1;if(!e.call(t,{checkOpacity:!0,checkVisibilityCSS:!0})){const e=t.parentElement;if(!t.matches("input, select, textarea")||!e||!shown(e))return!1}}return t.getClientRects().length>0}function r(t){const e=[],n=t;t.matches("input[type=checkbox], input[type=radio]")?e.push(n.checked?"checked":"unchecked"):t.matches("input, textarea")?e.push(`value "${n.value.slice(0,60)}"`):t instanceof HTMLSelectElement&&e.push(`value "${t.selectedOptions[0]?.text??""}"`);for(const n of["aria-checked","aria-selected","aria-expanded","aria-pressed","aria-current"]){const r=t.getAttribute(n);r&&"false"!==r&&e.push(`${n.slice(5)}${"true"===r?"":`=${r}`}`)}return(t.disabled||"true"===t.getAttribute("aria-disabled"))&&e.push("disabled"),e.length?{state:e.join(", ")}:{}}export function fractionIn(t,e,n){const r=t.getBoundingClientRect(),i=t=>Math.round(1e3*t)/1e3;return[i((e-r.left)/(r.width||1)),i((n-r.top)/(r.height||1))]}export function pointIn(t,e=[.5,.5]){const n=t.getBoundingClientRect();return{x:n.left+e[0]*n.width,y:n.top+e[1]*n.height}}
1
+ export const IGNORED="[data-demo-ignore]";const t=["button","a[href]","input","textarea","select","summary","canvas","video",'[contenteditable=""]','[contenteditable="true"]','[role="button"]','[role="link"]','[role="tab"]','[role="option"]','[role="menuitem"]','[role="menuitemcheckbox"]','[role="menuitemradio"]','[role="switch"]','[role="checkbox"]','[role="radio"]','[role="slider"]','[role="combobox"]','[role="treeitem"]','[role="gridcell"]','[role="row"]',"li[role]","[data-demo]"];function e(t){const e=t.getAttribute("aria-label");return e?normal(e):""}export function normal(t){return t.replace(/\s+/g," ").replace(/\d[\d.,]*/g,"#").trim().toLowerCase().slice(0,80)}export function dictionaryLabels(t,e){let n;const r=()=>{const e=t();if(n?.from===e)return n;const r=new Map,i=new Map,o=(t,e)=>Object.entries(t).forEach(([t,n])=>{const s=e+t;if("object"==typeof n&&n)o(n,s+".");else if("string"==typeof n&&!n.includes("{{")){const t=normal(n);r.set(t,r.has(t)?null:s),i.set(s,n)}});return o(e,""),n={from:e,keys:r,texts:i}};return{keyOf:t=>r().keys.get(normal(t))??void 0,textOf:t=>e?.(t)??r().texts.get(t)}}export class Targets{constructor(e={}){this.options=e,this.interactive=[...t,...e.interactive??[]].join(","),this.attributes=["aria-label","title",...e.labelAttributes??[]]}labelOf(t){const e=t,n=t.getAttribute("aria-labelledby")?.split(/\s+/).map(e=>t.ownerDocument.getElementById(e)?.textContent??"").join(" "),r=t.matches("input, select, textarea"),i=r?t.closest("label"):null,o=r?"":e.innerText?.trim()??"",s=t.getAttribute("data-demo")||(t instanceof HTMLInputElement&&["button","submit","reset"].includes(t.type)?t.value:"")||(/[\p{L}\p{N}]/u.test(o)?o:"")||n?.trim()||this.attributes.map(e=>t.getAttribute(e)).find(Boolean)||t.placeholder||t.alt||t.id&&t.ownerDocument.querySelector(`label[for="${CSS.escape(t.id)}"]`)?.textContent||i&&Array.from(i.childNodes).filter(t=>t.nodeType===Node.TEXT_NODE).map(t=>t.textContent).join(" ").trim()||t.name||o;if(s.trim())return normal(s);const a=t.querySelector("svg[data-testid], [data-icon]"),l=a?.getAttribute("data-testid")??a?.getAttribute("data-icon");if(l)return normal(l);let c=t.parentElement;for(let t=0;c&&t<4;t++,c=c.parentElement){const t=c.innerText??"";if(t.trim())return normal(t)}return""}cssOf(t){const e=t.tagName.toLowerCase(),n=t.getAttribute("role"),r="input"===e?t.getAttribute("type"):null,i=this.options.stableClass&&Array.from(t.classList).find(t=>this.options.stableClass.test(t));return e+(i?`.${CSS.escape(i)}`:"")+(n?`[role="${n}"]`:"")+(r?`[type="${r}"]`:"")}labelIn(t){if(t.key){const e=this.options.labels?.textOf(t.key);if(void 0!==e)return normal(e)}return void 0===t.text?void 0:normal(t.text)}targetElement(t){return!t||t.closest(IGNORED)?null:t.closest(this.interactive)??t}matches(t){const n=this.labelIn(t);let r;try{r=Array.from(document.querySelectorAll(t.css))}catch{return[]}return r.filter(t=>!t.closest(IGNORED)&&(void 0===n||this.labelOf(t)===n||e(t)===n))}describe(t){const i=this.cssOf(t),o=e(t),s=this.labelOf(t),a=o&&s.length>40?o:s,l=a&&!t.getAttribute("data-demo")?this.options.labels?.keyOf(a):void 0,c=t=>({css:t,...l?{key:l}:a?{text:a}:{}}),u=c(i);if(this.matches(u).length<=1)return u;for(let e=t.parentElement;e&&e!==document.body;e=e.parentElement){const o=r(e);if(!o)continue;const s=c(`${o} ${i}`),a=this.matches(s);if(1===a.length)return s;if(a.length>1)return{...s,...n(a,t)}}return{...u,...n(this.matches(u),t)}}async find(t,e=1e4,n=()=>!1){const r=performance.now()+e;do{const e=this.matches(t)[t.index??0];if(e&&shown(e))return e;await new Promise(t=>setTimeout(t,100))}while(performance.now()<r&&!n())}list({within:t,query:e,limit:n=400}={}){const r=t?Array.from(document.querySelectorAll(t)):[document.body],o=new Set,s=[],a=e?normal(e):void 0;for(const t of r)for(const e of Array.from(t.querySelectorAll(this.interactive))){if(s.length>=n)break;if(o.has(e)||e.closest(IGNORED)||!shown(e))continue;const r=e.parentElement?.closest(this.interactive);if(r&&!r.closest(IGNORED)&&t.contains(r)&&this.labelOf(r)===this.labelOf(e)&&!e.matches("input, select, textarea, canvas"))continue;o.add(e);const l=this.labelOf(e);if(a&&!l.includes(a))continue;const c=e.getBoundingClientRect();s.push({target:this.describe(e),label:l,tag:e.tagName.toLowerCase(),...e.getAttribute("role")?{role:e.getAttribute("role")}:{},...i(e),box:{x:Math.round(c.x),y:Math.round(c.y),width:Math.round(c.width),height:Math.round(c.height)}})}return s}}function n(t,e){const n=t.indexOf(e);return n>0?{index:n}:{}}function r(t){const e=t.getAttribute("data-demo");if(e)return`[data-demo="${e.replace(/"/g,'\\"')}"]`;const n=t.id;return n&&/^[a-z][\w-]*$/i.test(n)&&!/\d{3,}|[:]|^(mui|radix|react|headlessui|rc)-?/i.test(n)?`#${CSS.escape(n)}`:void 0}export function shown(t){const e=t.checkVisibility;if(e){if(!e.call(t,{checkVisibilityCSS:!0}))return!1;if(!e.call(t,{checkOpacity:!0,checkVisibilityCSS:!0})){const e=t.parentElement;if(!t.matches("input, select, textarea")||!e||!shown(e))return!1}}return t.getClientRects().length>0}function i(t){const e=[],n=t;t.matches("input[type=checkbox], input[type=radio]")?e.push(n.checked?"checked":"unchecked"):t.matches("input, textarea")?e.push(`value "${n.value.slice(0,60)}"`):t instanceof HTMLSelectElement&&e.push(`value "${t.selectedOptions[0]?.text??""}"`);for(const n of["aria-checked","aria-selected","aria-expanded","aria-pressed","aria-current"]){const r=t.getAttribute(n);r&&"false"!==r&&e.push(`${n.slice(5)}${"true"===r?"":`=${r}`}`)}return(t.disabled||"true"===t.getAttribute("aria-disabled"))&&e.push("disabled"),e.length?{state:e.join(", ")}:{}}export function fractionIn(t,e,n){const r=t.getBoundingClientRect(),i=t=>Math.round(1e3*t)/1e3;return[i((e-r.left)/(r.width||1)),i((n-r.top)/(r.height||1))]}export function pointIn(t,e=[.5,.5]){const n=t.getBoundingClientRect();return{x:n.left+e[0]*n.width,y:n.top+e[1]*n.height}}
package/store/Share.d.ts CHANGED
@@ -7,6 +7,8 @@ import type { Demo } from '../model/Demo';
7
7
  export declare function linkTo(demo: Demo, base?: string): Promise<string>;
8
8
  /** The demo a link brought, taken out of the address; none without one. */
9
9
  export declare function demoFromLink(): Promise<Demo | undefined>;
10
+ /** The demo in a link `linkTo` made; none in another. */
11
+ export declare function demoIn(link: string): Promise<Demo | undefined>;
10
12
  export declare function pack(value: object): Promise<string>;
11
13
  export declare function unpack(text: string): Promise<unknown>;
12
14
  /** Saved by the browser, as a file. */
package/store/Share.js CHANGED
@@ -1 +1 @@
1
- const e=/^#demo=(.+)$/;export async function linkTo(e,t=window.location.href){const n=new URL(t);return n.hash="demo="+await pack(e),n.toString()}export async function demoFromLink(){const t=window.location.hash.match(e);if(t){window.history.replaceState(window.history.state,"",window.location.pathname+window.location.search);try{return await unpack(t[1])}catch{return}}}export async function pack(e){const t=new Blob([JSON.stringify(e)]).stream().pipeThrough(new CompressionStream("deflate-raw")),n=new Uint8Array(await new Response(t).arrayBuffer());let o="";return n.forEach(e=>o+=String.fromCharCode(e)),btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}export async function unpack(e){const t=atob(e.replace(/-/g,"+").replace(/_/g,"/")),n=Uint8Array.from(t,e=>e.charCodeAt(0)),o=new Blob([n]).stream().pipeThrough(new DecompressionStream("deflate-raw"));return JSON.parse(await new Response(o).text())}export function download(e,t,n="text/plain"){const o="string"==typeof e?new Blob([e],{type:`${n};charset=utf-8`}):e,r=URL.createObjectURL(o),a=document.createElement("a");a.href=r,a.download=t,a.style.display="none",document.body.append(a),a.click(),a.remove(),setTimeout(()=>URL.revokeObjectURL(r),6e4)}export async function shareFiles(e,t,n){const o={files:e,title:t,...n?{text:n}:{}};if(!navigator.canShare?.(o))return!1;try{return await navigator.share(o),!0}catch{return!1}}export function fileName(e,t){return`${e.replace(/[\\/:*?"<>|]+/g,"").replace(/\s+/g," ").trim()||"demo"}.${t}`}export function pickFile(e=".json,application/json"){return new Promise(t=>{const n=document.createElement("input");n.type="file",n.accept=e,n.onchange=()=>t(n.files?.[0]),n.addEventListener("cancel",()=>t(void 0)),n.click()})}
1
+ const e=/^#demo=(.+)$/;export async function linkTo(e,t=window.location.href){const n=new URL(t);return n.hash="demo="+await pack(e),n.toString()}export async function demoFromLink(){if(!e.test(window.location.hash))return;const t=await demoIn(window.location.href);return window.history.replaceState(window.history.state,"",window.location.pathname+window.location.search),t}export async function demoIn(t){const n=t.replace(/^[^#]*/,"").match(e);if(n)try{return await unpack(n[1])}catch{return}}export async function pack(e){const t=new Blob([JSON.stringify(e)]).stream().pipeThrough(new CompressionStream("deflate-raw")),n=new Uint8Array(await new Response(t).arrayBuffer());let o="";return n.forEach(e=>o+=String.fromCharCode(e)),btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}export async function unpack(e){const t=atob(e.replace(/-/g,"+").replace(/_/g,"/")),n=Uint8Array.from(t,e=>e.charCodeAt(0)),o=new Blob([n]).stream().pipeThrough(new DecompressionStream("deflate-raw"));return JSON.parse(await new Response(o).text())}export function download(e,t,n="text/plain"){const o="string"==typeof e?new Blob([e],{type:`${n};charset=utf-8`}):e,r=URL.createObjectURL(o),a=document.createElement("a");a.href=r,a.download=t,a.style.display="none",document.body.append(a),a.click(),a.remove(),setTimeout(()=>URL.revokeObjectURL(r),6e4)}export async function shareFiles(e,t,n){const o={files:e,title:t,...n?{text:n}:{}};if(!navigator.canShare?.(o))return!1;try{return await navigator.share(o),!0}catch{return!1}}export function fileName(e,t){return`${e.replace(/[\\/:*?"<>|]+/g,"").replace(/\s+/g," ").trim()||"demo"}.${t}`}export function pickFile(e=".json,application/json"){return new Promise(t=>{const n=document.createElement("input");n.type="file",n.accept=e,n.onchange=()=>t(n.files?.[0]),n.addEventListener("cancel",()=>t(void 0)),n.click()})}
package/ui/Actions.js CHANGED
@@ -1 +1 @@
1
- import e,{useState as t}from"react";import{describeTarget as a}from"../engine/Player.js";import{BUILT_IN_KINDS as l,INTERACT_KINDS as o,isPresent as r,PRESENT_KINDS as n}from"../model/Demo.js";import{fractionIn as c}from"../page/Targets.js";import{Button as s,Check as i,JsonField as d,Labelled as m,Menu as p,NumberField as h}from"./Kit.js";const u={click:{do:"click",target:{css:"button",text:""}},hover:{do:"hover",target:{css:"button",text:""}},type:{do:"type",target:{css:"input"},text:""},key:{do:"key",key:"Escape"},select:{do:"select",target:{css:"select"},option:""},drag:{do:"drag",target:{css:'[role="slider"]'},to:{at:[1,.5]}},scroll:{do:"scroll",target:{css:"main"}},waitFor:{do:"waitFor",target:{css:'[role="dialog"]'}},spotlight:{do:"spotlight",target:{css:"main"}},ring:{do:"ring",target:{css:"button",text:""}},arrow:{do:"arrow",target:{css:"button",text:""},text:""},callout:{do:"callout",text:"A note",corner:"top-right"},blur:{do:"blur",target:{css:'input[type="email"]'}},card:{do:"card",title:"Title",text:"",for:3e3},zoom:{do:"zoom",target:{css:"main"},scale:1.8},clear:{do:"clear"}},g=new Set(["click","hover","type","select","drag","waitFor","spotlight","ring","arrow","blur","zoom"]);export function readAction(e,t){return e.read(t)}export function addActionItems(e,t){const a=e.pluginKinds(),l=a=>({label:a,onClick:()=>t(JSON.parse(JSON.stringify(e.pluginAction(a)?.template?.()??u[a]??{do:a})))});return[{heading:"Interact"},...o.map(l),{heading:"Present"},...n.map(l),...a.length?[{heading:"App"},...a.map(l)]:[]]}export function ActionRow({engine:o,action:n,index:u,count:v,open:k,error:E,sentences:y,onOpen:w,onChange:x,onMove:f,onDelete:C,onDuplicate:N,picking:T}){const[A,S]=t(),j=n,F=e=>{const t={...n,...e};Object.keys(e).forEach(e=>(void 0===t[e]||""===t[e]||!1===t[e])&&delete t[e]),x(t)},D=l.includes(n.do),B=r(n),O=(t,l,r="Target",n=!1)=>e.createElement("div",{className:"wide col"},e.createElement("div",{className:"row"},e.createElement("span",{className:"small muted",style:{width:52}},r),e.createElement(s,{icon:"pick",small:!0,title:"Pick it on the page",onClick:()=>{(async e=>{T(!0);const t=await o.overlay.pick(e=>o.targets.targetElement(e),e=>a(o.targets.describe(e)));if(T(!1),!t)return;const l=o.targets.describe(t.element),r=t.element.matches('canvas, video, [role="slider"], input[type="range"]')||j.at?c(t.element,t.x,t.y):void 0;F("to"===e?{to:{target:l,...r?{at:r}:{}}}:{target:l,...r?{at:r}:{}})})("To"===r?"to":"target")}}),e.createElement(s,{icon:"show",small:!0,title:"Show it on the page",disabled:!t,onClick:()=>(e=>{if(!e)return;const t=o.targets.matches(e),a=t[e.index??0];S(a?`${t.length} match${1===t.length?"":"es"}`:"Not found here now"),a&&(a.scrollIntoView({block:"nearest",inline:"nearest"}),o.overlay.flash(a))})(t)}),n&&t&&e.createElement(s,{icon:"close",small:!0,kind:"bare",title:"No target",onClick:()=>l(void 0)}),A&&e.createElement("span",{className:"small muted"},A)),t&&e.createElement("div",{className:"row"},e.createElement("input",{className:"field mono grow",title:"CSS selector",placeholder:"css",value:t.css,onChange:e=>l({...t,css:e.target.value})}),e.createElement("input",{className:"field",style:{width:"24%"},title:"Its label: what it shows. Digits match any.",placeholder:"text",value:t.text??"",onChange:e=>l(b({...t,text:e.target.value}))}),e.createElement("input",{className:"field mono",style:{width:"20%"},title:"Its label by the app's locale key: found in every language",placeholder:"key",value:t.key??"",onChange:e=>l(b({...t,key:e.target.value}))}),e.createElement(h,{value:t.index,width:52,placeholder:"#",title:"Which of the matches, from 0",onChange:e=>l(b({...t,index:e}))})),!t&&n&&e.createElement(s,{small:!0,onClick:()=>l({css:"button",text:""})},"Add a target")),P=(t,a)=>e.createElement(m,{label:a},e.createElement("select",{className:"field",value:j[t]??"",onChange:e=>F({[t]:e.target.value||void 0})},e.createElement("option",{value:""},"where there is room"),["top","right","bottom","left"].map(t=>e.createElement("option",{key:t,value:t},t)))),I=(t,a,l=!1)=>e.createElement(m,{label:a,className:l?"wide":void 0},e.createElement("input",{className:"field",value:j[t]??"",onChange:e=>F({[t]:e.target.value})})),$=(t,a,l)=>e.createElement(m,{label:a},e.createElement(h,{value:j[t],width:120,placeholder:l,onChange:e=>F({[t]:e})})),z=(t,a,l="At (x, y in its box)")=>e.createElement(m,{label:l},e.createElement("div",{className:"row"},e.createElement(h,{value:t?.[0],width:60,placeholder:"0.5",onChange:e=>a(void 0===e&&void 0===t?.[1]?void 0:[e??.5,t?.[1]??.5])}),e.createElement(h,{value:t?.[1],width:60,placeholder:"0.5",onChange:e=>a(void 0===e&&void 0===t?.[0]?void 0:[t?.[0]??.5,e??.5])})));return e.createElement("div",{className:["action",k&&"on",E&&"failed"].filter(Boolean).join(" ")},e.createElement("div",{className:"row"},e.createElement(s,{icon:k?"expand":"right",small:!0,kind:"bare",title:k?"Less":"Details",onClick:w}),e.createElement("span",{className:"kind"+(B?" present":"")},n.do),e.createElement("span",{className:"grow ellipsis",title:E??readAction(o,n),onClick:w,style:{cursor:"pointer"}},readAction(o,n),E&&e.createElement("span",{className:"error"}," - ",E)),e.createElement("span",{className:"small muted",title:"ms before it"},"wait"),e.createElement(h,{value:n.wait,width:58,placeholder:"800",title:"ms before it, 800 by default",onChange:e=>F({wait:e})}),e.createElement("select",{className:"field small",style:{width:74},title:"Starts with this sentence of the step's narration",value:n.cue??"",onChange:e=>F({cue:""===e.target.value?void 0:Number(e.target.value)})},e.createElement("option",{value:""},"no cue"),y.map((t,a)=>e.createElement("option",{key:a,value:a,title:t},`cue ${a+1}`)),void 0!==n.cue&&n.cue>=y.length&&e.createElement("option",{value:n.cue},`cue ${n.cue+1}?`)),e.createElement(s,{icon:"play",small:!0,kind:"bare",title:"Try it now",onClick:()=>{o.check({id:"test",title:"Test",steps:[{say:{},actions:[{...n,wait:0}],hold:B?2500:0}]},{speed:1}).then(e=>S(e.ok?"Played":e.failures[0]?.error??e.error))}}),e.createElement(p,{title:"More",items:[{label:"Earlier",icon:"up",disabled:0===u,onClick:()=>f(-1)},{label:"Later",icon:"down",disabled:u===v-1,onClick:()=>f(1)},{label:"Duplicate",icon:"duplicate",onClick:N},{label:"Delete",icon:"delete",onClick:C}]})),k&&e.createElement("div",{className:"details"},(()=>{if(!D){const{do:t,wait:a,cue:l,...o}=j;return e.createElement(m,{label:`${n.do}: its details`,className:"wide"},e.createElement(d,{rows:3,value:o,onChange:e=>e&&"object"==typeof e&&x({do:n.do,...void 0!==j.wait?{wait:j.wait}:{},...void 0!==j.cue?{cue:j.cue}:{},...e})}))}const t=[];switch("callout"===n.do||"key"===n.do||"scroll"===n.do?t.push(O(j.target,e=>F({target:e}),"Target",!0)):g.has(n.do)&&t.push(O(j.target,e=>e&&F({target:e}))),n.do){case"click":t.push(z(j.at,e=>F({at:e}))),t.push(e.createElement("div",{className:"row",key:"mods",style:{flexWrap:"wrap",gap:10}},e.createElement(i,{label:"double",checked:Boolean(j.double),onChange:e=>F({double:e})}),e.createElement(i,{label:"right",checked:Boolean(j.right),onChange:e=>F({right:e})}),["shift","ctrl","alt","meta"].map(t=>e.createElement(i,{key:t,label:t,checked:Boolean(j[t]),onChange:e=>F({[t]:e})}))));break;case"hover":t.push(z(j.at,e=>F({at:e})));break;case"type":t.push(I("text","Text",!0));break;case"key":t.push(I("key","Key or chord: 'Enter', 'Control+K'"));break;case"select":t.push(I("option","Option, by its text or value"));break;case"drag":t.push(z(j.at,e=>F({at:e}),"From (x, y in its box)")),t.push(O(j.to?.target,e=>F({to:b({...j.to,target:e})}),"To",!0)),t.push(z(j.to?.at,e=>F({to:b({...j.to,at:e})}),"To (x, y in its box)"));break;case"scroll":t.push(e.createElement(m,{label:"By (x, y px)",key:"by"},e.createElement(d,{value:j.by,onChange:e=>F({by:e})})));break;case"waitFor":t.push(e.createElement(i,{key:"gone",label:"till it is gone",checked:Boolean(j.gone),onChange:e=>F({gone:e})})),t.push($("timeout","Timeout ms","10000"));break;case"spotlight":t.push(I("text","Note",!0),$("padding","Padding px","8"));break;case"ring":t.push(I("text","Label"),I("color","Colour"),$("padding","Padding px","6")),t.push(e.createElement(m,{label:"Shape",key:"shape"},e.createElement("select",{className:"field",value:j.shape??"box",onChange:e=>F({shape:"box"===e.target.value?void 0:e.target.value})},e.createElement("option",null,"box"),e.createElement("option",null,"circle"))));break;case"arrow":t.push(I("text","Label"),P("from","From"),I("color","Colour"));break;case"callout":t.push(I("text","Text",!0),P("side","Side (with a target)")),t.push(e.createElement(m,{label:"Corner (without)",key:"corner"},e.createElement("select",{className:"field",value:j.corner??"",onChange:e=>F({corner:e.target.value||void 0})},e.createElement("option",{value:""},"top-right"),["top-left","top-right","bottom-left","bottom-right"].map(t=>e.createElement("option",{key:t},t)))));break;case"card":t.push(I("title","Title",!0),I("text","Text",!0));break;case"zoom":t.push($("scale","Scale","1.8"))}return B&&"clear"!==n.do&&t.push($("for","For ms (else the step)","the step")),t.map((t,a)=>e.createElement(e.Fragment,{key:a},t))})()))}function b(e){const t={};return Object.entries(e).forEach(([e,a])=>{void 0!==a&&""!==a&&(t[e]=a)}),t}export{u as TEMPLATES};
1
+ import e,{useState as t}from"react";import{describeTarget as a}from"../engine/Player.js";import{BUILT_IN_KINDS as l,INTERACT_KINDS as o,isPresent as r,PRESENT_KINDS as n}from"../model/Demo.js";import{fractionIn as c}from"../page/Targets.js";import{Button as s,Check as i,JsonField as m,Labelled as d,Menu as p,NumberField as u}from"./Kit.js";const h={click:{do:"click",target:{css:"button",text:""}},hover:{do:"hover",target:{css:"button",text:""}},type:{do:"type",target:{css:"input"},text:""},key:{do:"key",key:"Escape"},select:{do:"select",target:{css:"select"},option:""},drag:{do:"drag",target:{css:'[role="slider"]'},to:{at:[1,.5]}},scroll:{do:"scroll",target:{css:"main"}},waitFor:{do:"waitFor",target:{css:'[role="dialog"]'}},spotlight:{do:"spotlight",target:{css:"main"}},ring:{do:"ring",target:{css:"button",text:""}},arrow:{do:"arrow",target:{css:"button",text:""},text:""},callout:{do:"callout",text:"A note",corner:"top-right"},blur:{do:"blur",target:{css:'input[type="email"]'}},card:{do:"card",title:"Title",text:"",for:3e3},zoom:{do:"zoom",target:{css:"main"},scale:1.8},clear:{do:"clear"}},g=new Set(["click","hover","type","select","drag","waitFor","spotlight","ring","arrow","blur","zoom"]);export function readAction(e,t){return e.read(t)}export function addActionItems(e,t){const a=e.pluginKinds(),l=a=>({label:a,onClick:()=>t(JSON.parse(JSON.stringify(e.pluginAction(a)?.template?.()??h[a]??{do:a})))});return[{heading:"Interact"},...o.map(l),{heading:"Present"},...n.map(l),...a.length?[{heading:"App"},...a.map(l)]:[]]}export function ActionRow({engine:o,action:n,index:h,count:v,open:E,error:k,sentences:y,onOpen:w,onChange:f,onMove:x,onDelete:C,onDuplicate:N,picking:T}){const[j,A]=t(),S=n,F=e=>{const t={...n,...e};Object.keys(e).forEach(e=>(void 0===t[e]||""===t[e]||!1===t[e])&&delete t[e]),f(t)},O=l.includes(n.do),D=r(n),$=(t,l,r="Target",n=!1)=>e.createElement("div",{className:"wide col"},e.createElement("div",{className:"row"},e.createElement("span",{className:"small muted",style:{width:52}},r),e.createElement(s,{icon:"pick",small:!0,title:"Pick it on the page",onClick:()=>{(async e=>{T(!0);const t=await o.overlay.pick(e=>o.targets.targetElement(e),e=>a(o.targets.describe(e)));if(T(!1),!t)return;const l=o.targets.describe(t.element),r=t.element.matches('canvas, video, [role="slider"], input[type="range"]')||S.at?c(t.element,t.x,t.y):void 0;F("to"===e?{to:{target:l,...r?{at:r}:{}}}:{target:l,...r?{at:r}:{}})})("To"===r?"to":"target")}}),e.createElement(s,{icon:"show",small:!0,title:"Show it on the page",disabled:!t,onClick:()=>(e=>{if(!e)return;const t=o.targets.matches(e),a=t[e.index??0];A(a?`${t.length} match${1===t.length?"":"es"}`:"Not found here now"),a&&(a.scrollIntoView({block:"nearest",inline:"nearest"}),o.overlay.flash(a))})(t)}),n&&t&&e.createElement(s,{icon:"close",small:!0,kind:"bare",title:"No target",onClick:()=>l(void 0)}),j&&e.createElement("span",{className:"small muted"},j)),t&&e.createElement("div",{className:"row"},e.createElement("input",{className:"field mono grow",title:"CSS selector",placeholder:"css",value:t.css,onChange:e=>l({...t,css:e.target.value})}),e.createElement("input",{className:"field",style:{width:"24%"},title:"Its label: what it shows. Digits match any.",placeholder:"text",value:t.text??"",onChange:e=>l(b({...t,text:e.target.value}))}),e.createElement("input",{className:"field mono",style:{width:"20%"},title:"Its label by the app's locale key: found in every language",placeholder:"key",value:t.key??"",onChange:e=>l(b({...t,key:e.target.value}))}),e.createElement(u,{value:t.index,width:52,placeholder:"#",title:"Which of the matches, from 0",onChange:e=>l(b({...t,index:e}))})),!t&&n&&e.createElement(s,{small:!0,onClick:()=>l({css:"button",text:""})},"Add a target")),B=(t,a)=>e.createElement(d,{label:a},e.createElement("select",{className:"field",value:S[t]??"",onChange:e=>F({[t]:e.target.value||void 0})},e.createElement("option",{value:""},"where there is room"),["top","right","bottom","left"].map(t=>e.createElement("option",{key:t,value:t},t)))),P=(t,a,l=!1)=>e.createElement(d,{label:a,className:l?"wide":void 0},e.createElement("input",{className:"field",value:S[t]??"",onChange:e=>F({[t]:e.target.value})})),I=(t,a,l=!1)=>{const r=S[t],n=o.languages();return r&&"object"==typeof r?e.createElement(d,{label:`${a}, per language`,className:l?"wide":void 0},[...new Set([...n,...Object.keys(r)])].map(a=>e.createElement("div",{className:"row",key:a},e.createElement("span",{className:"small muted mono",style:{width:22}},a),e.createElement("input",{className:"field grow",value:r[a]??"",onChange:e=>F({[t]:{...r,[a]:e.target.value}})})))):e.createElement(d,{label:a,className:l?"wide":void 0},e.createElement("div",{className:"row"},e.createElement("input",{className:"field grow",value:r??"",onChange:e=>F({[t]:e.target.value})}),n.length>1&&e.createElement(s,{small:!0,kind:"bare",title:`A text for each language: ${n.join(", ")}`,onClick:()=>F({[t]:Object.fromEntries(n.map(e=>[e,r??""]))})},"per language")))},z=(t,a,l)=>e.createElement(d,{label:a},e.createElement(u,{value:S[t],width:120,placeholder:l,onChange:e=>F({[t]:e})})),K=(t,a,l="At (x, y in its box)")=>e.createElement(d,{label:l},e.createElement("div",{className:"row"},e.createElement(u,{value:t?.[0],width:60,placeholder:"0.5",onChange:e=>a(void 0===e&&void 0===t?.[1]?void 0:[e??.5,t?.[1]??.5])}),e.createElement(u,{value:t?.[1],width:60,placeholder:"0.5",onChange:e=>a(void 0===e&&void 0===t?.[0]?void 0:[t?.[0]??.5,e??.5])})));return e.createElement("div",{className:["action",E&&"on",k&&"failed"].filter(Boolean).join(" ")},e.createElement("div",{className:"row"},e.createElement(s,{icon:E?"expand":"right",small:!0,kind:"bare",title:E?"Less":"Details",onClick:w}),e.createElement("span",{className:"kind"+(D?" present":"")},n.do),e.createElement("span",{className:"grow ellipsis",title:k??readAction(o,n),onClick:w,style:{cursor:"pointer"}},readAction(o,n),k&&e.createElement("span",{className:"error"}," - ",k)),e.createElement("span",{className:"small muted",title:"ms before it"},"wait"),e.createElement(u,{value:n.wait,width:58,placeholder:"800",title:"ms before it, 800 by default",onChange:e=>F({wait:e})}),e.createElement("select",{className:"field small",style:{width:74},title:"Starts with this sentence of the step's narration",value:n.cue??"",onChange:e=>F({cue:""===e.target.value?void 0:Number(e.target.value)})},e.createElement("option",{value:""},"no cue"),y.map((t,a)=>e.createElement("option",{key:a,value:a,title:t},`cue ${a+1}`)),void 0!==n.cue&&n.cue>=y.length&&e.createElement("option",{value:n.cue},`cue ${n.cue+1}?`)),e.createElement(s,{icon:"play",small:!0,kind:"bare",title:"Try it now",onClick:()=>{o.check({id:"test",title:"Test",steps:[{say:{},actions:[{...n,wait:0}],hold:D?2500:0}]},{speed:1}).then(e=>A(e.ok?"Played":e.failures[0]?.error??e.error))}}),e.createElement(p,{title:"More",items:[{label:"Earlier",icon:"up",disabled:0===h,onClick:()=>x(-1)},{label:"Later",icon:"down",disabled:h===v-1,onClick:()=>x(1)},{label:"Duplicate",icon:"duplicate",onClick:N},{label:"Delete",icon:"delete",onClick:C}]})),E&&e.createElement("div",{className:"details"},(()=>{if(!O){const{do:t,wait:a,cue:l,...o}=S;return e.createElement(d,{label:`${n.do}: its details`,className:"wide"},e.createElement(m,{rows:3,value:o,onChange:e=>e&&"object"==typeof e&&f({do:n.do,...void 0!==S.wait?{wait:S.wait}:{},...void 0!==S.cue?{cue:S.cue}:{},...e})}))}const t=[];switch("callout"===n.do||"key"===n.do||"scroll"===n.do?t.push($(S.target,e=>F({target:e}),"Target",!0)):g.has(n.do)&&t.push($(S.target,e=>e&&F({target:e}))),n.do){case"click":t.push(K(S.at,e=>F({at:e}))),t.push(e.createElement("div",{className:"row",key:"mods",style:{flexWrap:"wrap",gap:10}},e.createElement(i,{label:"double",checked:Boolean(S.double),onChange:e=>F({double:e})}),e.createElement(i,{label:"right",checked:Boolean(S.right),onChange:e=>F({right:e})}),["shift","ctrl","alt","meta"].map(t=>e.createElement(i,{key:t,label:t,checked:Boolean(S[t]),onChange:e=>F({[t]:e})}))));break;case"hover":t.push(K(S.at,e=>F({at:e})));break;case"type":t.push(P("text","Text",!0));break;case"key":t.push(P("key","Key or chord: 'Enter', 'Control+K'"));break;case"select":t.push(P("option","Option, by its text or value"));break;case"drag":t.push(K(S.at,e=>F({at:e}),"From (x, y in its box)")),t.push($(S.to?.target,e=>F({to:b({...S.to,target:e})}),"To",!0)),t.push(K(S.to?.at,e=>F({to:b({...S.to,at:e})}),"To (x, y in its box)"));break;case"scroll":t.push(e.createElement(d,{label:"By (x, y px)",key:"by"},e.createElement(m,{value:S.by,onChange:e=>F({by:e})})));break;case"waitFor":t.push(e.createElement(i,{key:"gone",label:"till it is gone",checked:Boolean(S.gone),onChange:e=>F({gone:e})})),t.push(z("timeout","Timeout ms","10000"));break;case"spotlight":t.push(I("text","Note",!0),z("padding","Padding px","8"));break;case"ring":t.push(I("text","Label"),P("color","Colour"),z("padding","Padding px","6")),t.push(e.createElement(d,{label:"Shape",key:"shape"},e.createElement("select",{className:"field",value:S.shape??"box",onChange:e=>F({shape:"box"===e.target.value?void 0:e.target.value})},e.createElement("option",null,"box"),e.createElement("option",null,"circle"))));break;case"arrow":t.push(I("text","Label"),B("from","From"),P("color","Colour"));break;case"callout":t.push(I("text","Text",!0),B("side","Side (with a target)")),t.push(e.createElement(d,{label:"Corner (without)",key:"corner"},e.createElement("select",{className:"field",value:S.corner??"",onChange:e=>F({corner:e.target.value||void 0})},e.createElement("option",{value:""},"top-right"),["top-left","top-right","bottom-left","bottom-right"].map(t=>e.createElement("option",{key:t},t)))));break;case"card":t.push(I("title","Title",!0),I("text","Text",!0));break;case"zoom":t.push(z("scale","Scale","1.8"))}return D&&"clear"!==n.do&&t.push(z("for","For ms (else the step)","the step")),t.map((t,a)=>e.createElement(e.Fragment,{key:a},t))})()))}function b(e){const t={};return Object.entries(e).forEach(([e,a])=>{void 0!==a&&""!==a&&(t[e]=a)}),t}export{h as TEMPLATES};
@@ -0,0 +1,9 @@
1
+ import type { DemoEngine } from '../engine/DemoEngine';
2
+ /**
3
+ * "Ask Claude": a demo made, cloned or changed in words. Claude works in the app as the person
4
+ * watches - each thing it does a line here - and opens what it made in the studio.
5
+ */
6
+ export declare function AssistantPanel({ engine, theme }: {
7
+ engine: DemoEngine;
8
+ theme: 'light' | 'dark';
9
+ }): JSX.Element;
@@ -0,0 +1 @@
1
+ import e,{useEffect as t,useRef as a,useState as s}from"react";import{costOf as n}from"../agent/Assistant.js";import{useDemos as l,useEngine as r}from"./Hooks.js";import{Button as i,Icon as o}from"./Kit.js";export function AssistantPanel({engine:d,theme:u}){const{assistant:p,settings:h,studio:k}=r(d),E=l(d),{working:g,about:v,usage:y}=p,f=h.claude.key,[N,b]=s(""),[A,w]=s(!f),C=a(null),x=a(null),$=p.entries[p.entries.length-1],I=k?.opened;t(()=>{k&&d.assistant.setAbout({id:k.demo.id,title:k.demo.title})},[I]),t(()=>{C.current?.scrollTo({top:C.current.scrollHeight})},[p.entries.length,"claude"===$?.kind?$.text.length:0,g]),t(()=>{f&&x.current?.focus()},[f]);const K=(e=N)=>{e.trim()&&!g&&f&&(d.assistant.ask(e),b(""))},P=E[0]?.demo,S=["Make a one-minute tour of this page",...v?[`Make “${v.title}” shorter and punchier`,`Add a step to “${v.title}” that shows …`]:[],...!v&&P?[`Clone “${P.title}” as a 30-second teaser`]:[]],j=n(y,h.claude.model),D=y.input+y.written+y.cached;return e.createElement("div",{className:"pde assistant"+(k?" over-studio":""),"data-theme":u,"data-demo-ignore":!0},e.createElement("div",{className:"row"},e.createElement(o,{name:"spark"}),e.createElement("h2",{className:"grow"},"Ask Claude"),e.createElement(i,{small:!0,kind:A?"primary":"bare",title:"Your Anthropic API key",onClick:()=>w(!A)},"Key"),e.createElement(i,{icon:"add",kind:"bare",title:"A new conversation",disabled:g||0===p.entries.length,onClick:()=>d.assistant.clear()}),e.createElement(i,{icon:"close",kind:"bare",title:"Close: the conversation stays",onClick:()=>d.assistant.close()})),A&&e.createElement("div",{className:"col",style:{gap:4}},e.createElement("input",{className:"field",type:"password",autoComplete:"off",placeholder:"sk-ant-…",value:f,"aria-label":"Anthropic API key",onChange:e=>d.changeSettings({claude:{...h.claude,key:e.target.value.trim()}})}),e.createElement("div",{className:"small muted"},"Your own Anthropic API key, from the Claude Console. It stays in this browser; Claude's requests go from here to Anthropic, billed to it."),f&&e.createElement(i,{small:!0,onClick:()=>w(!1)},"Done")),e.createElement("div",{className:"entries",ref:C},0===p.entries.length&&e.createElement("div",{className:"col",style:{gap:6}},e.createElement("div",{className:"small muted"},"Say what the demo should show. Claude looks at the app, walks the path, writes the narration, checks it plays, and opens it in the studio. You see each step it takes."),e.createElement("div",{className:"suggest"},S.map(t=>e.createElement(i,{key:t,small:!0,kind:"bare",disabled:!f,onClick:()=>{b(t),x.current?.focus()}},t)))),p.entries.map((t,a)=>e.createElement(c,{key:a,entry:t})),g&&e.createElement("div",{className:"small muted working"},e.createElement("span",{className:"dot"}),"Working…")),v&&e.createElement("div",{className:"about small"},e.createElement("span",{className:"muted"},"About"),e.createElement("span",{className:"ellipsis grow"},"“",v.title,"”"),e.createElement(i,{icon:"close",small:!0,kind:"bare",title:"About nothing in particular",onClick:()=>d.assistant.setAbout(void 0)})),e.createElement("div",{className:"ask"},e.createElement("textarea",{ref:x,className:"field",rows:2,placeholder:f?"A one-minute tour of the orders, for new team members…":"Add your API key first (Key)",value:N,disabled:!f,onChange:e=>b(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),K())}}),g?e.createElement(i,{icon:"stop",onClick:()=>d.assistant.stop()},"Stop"):e.createElement(i,{icon:"send",kind:"primary",title:"Ask (Enter)",disabled:!N.trim()||!f,onClick:()=>K()})),D+y.output>0&&e.createElement("div",{className:"small muted",title:"This conversation, so far"},m(D)," tokens in (",m(y.cached)," from cache) · ",m(y.output)," out",void 0!==j?` · about $${j.toFixed(2)}`:""))}function c({entry:t}){switch(t.kind){case"you":return e.createElement("div",{className:"you"},t.text);case"claude":return e.createElement("div",{className:"claude"},t.text);case"did":return e.createElement("div",{className:"did"+(t.ok?"":" failed")},e.createElement("span",null,t.ok?"✓":"✕"),e.createElement("span",null,t.text));case"error":return e.createElement("div",{className:"small error"},t.text)}}function m(e){return e<1e3?String(e):`${(e/1e3).toFixed(e<1e4?1:0)}k`}