@protomaze/demo-engine 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/AGENTS.md +131 -0
  2. package/README.md +192 -2
  3. package/agent/Agent.d.ts +155 -0
  4. package/agent/Agent.js +1 -0
  5. package/agent/Guide.d.ts +2 -0
  6. package/agent/Guide.js +1 -0
  7. package/engine/DemoEngine.d.ts +338 -0
  8. package/engine/DemoEngine.js +1 -0
  9. package/engine/Guided.d.ts +12 -0
  10. package/engine/Guided.js +1 -0
  11. package/engine/Player.d.ts +154 -0
  12. package/engine/Player.js +1 -0
  13. package/engine/Plugin.d.ts +56 -0
  14. package/engine/Plugin.js +1 -0
  15. package/engine/Read.d.ts +5 -0
  16. package/engine/Read.js +1 -0
  17. package/engine/Recorder.d.ts +50 -0
  18. package/engine/Recorder.js +1 -0
  19. package/engine/Settings.d.ts +51 -0
  20. package/engine/Settings.js +1 -0
  21. package/index.d.ts +27 -0
  22. package/index.js +1 -0
  23. package/model/Demo.d.ts +201 -0
  24. package/model/Demo.js +1 -0
  25. package/model/Subtitles.d.ts +12 -0
  26. package/model/Subtitles.js +1 -0
  27. package/model/Timing.d.ts +45 -0
  28. package/model/Timing.js +1 -0
  29. package/model/Validate.d.ts +16 -0
  30. package/model/Validate.js +1 -0
  31. package/package.json +65 -4
  32. package/page/Input.d.ts +67 -0
  33. package/page/Input.js +1 -0
  34. package/page/Overlay.d.ts +110 -0
  35. package/page/Overlay.js +1 -0
  36. package/page/Targets.d.ts +85 -0
  37. package/page/Targets.js +1 -0
  38. package/speech/Music.d.ts +13 -0
  39. package/speech/Music.js +1 -0
  40. package/speech/Pack.d.ts +27 -0
  41. package/speech/Pack.js +1 -0
  42. package/speech/Speech.d.ts +127 -0
  43. package/speech/Speech.js +1 -0
  44. package/speech/Transcribe.d.ts +25 -0
  45. package/speech/Transcribe.js +1 -0
  46. package/speech/Workers.d.ts +22 -0
  47. package/speech/Workers.js +1 -0
  48. package/store/Share.d.ts +19 -0
  49. package/store/Share.js +1 -0
  50. package/store/Store.d.ts +55 -0
  51. package/store/Store.js +1 -0
  52. package/store/Zip.d.ts +9 -0
  53. package/store/Zip.js +1 -0
  54. package/ui/Actions.d.ts +33 -0
  55. package/ui/Actions.js +1 -0
  56. package/ui/EngineUI.d.ts +3 -0
  57. package/ui/EngineUI.js +1 -0
  58. package/ui/Hooks.d.ts +5 -0
  59. package/ui/Hooks.js +1 -0
  60. package/ui/Kit.d.ts +108 -0
  61. package/ui/Kit.js +1 -0
  62. package/ui/Library.d.ts +32 -0
  63. package/ui/Library.js +1 -0
  64. package/ui/Studio.d.ts +10 -0
  65. package/ui/Studio.js +1 -0
  66. package/ui/Styles.d.ts +2 -0
  67. package/ui/Styles.js +1 -0
  68. package/ui/Timeline.d.ts +21 -0
  69. package/ui/Timeline.js +1 -0
  70. package/video/Film.d.ts +61 -0
  71. package/video/Film.js +1 -0
@@ -0,0 +1,338 @@
1
+ import { Demo, DemoAction, DemoStep, Language } from '../model/Demo';
2
+ import { Subtitle } from '../model/Subtitles';
3
+ import { Timing } from '../model/Timing';
4
+ import { Problem } from '../model/Validate';
5
+ import { Hand } from '../page/Input';
6
+ import { Overlay, OverlayOptions } from '../page/Overlay';
7
+ import { Labels, Targets, TargetsOptions } from '../page/Targets';
8
+ import { Speech, SpeechState } from '../speech/Speech';
9
+ import { DemoVideo, KeptDemo, Store } from '../store/Store';
10
+ import { NarrationPack } from '../speech/Pack';
11
+ import { PlayOptions, Player, PlayResult, PlayState } from './Player';
12
+ import type { DemoPlugin } from './Plugin';
13
+ import { RecordState } from './Recorder';
14
+ import { DEFAULT_SETTINGS, DemoSettings } from './Settings';
15
+ export type DemoStart = {
16
+ /** Where the app is now, as a demo recorded here starts. */
17
+ current(): Record<string, string>;
18
+ /**
19
+ * Brings the app to a demo's start. 'reload' if it navigates for it: the engine plays the demo
20
+ * once the page is back, after a click.
21
+ */
22
+ go(start: Record<string, string>): Promise<void | 'reload'> | void | 'reload';
23
+ };
24
+ export type DemoEngineOptions = {
25
+ /** Names where this app's demos and settings are kept. */
26
+ app: string;
27
+ /** Demos that come with the app, and their scenarios for people. */
28
+ demos?: (Demo | {
29
+ demo: Demo;
30
+ scenario?: string;
31
+ })[];
32
+ /** The languages narration is written in; the first by default. */
33
+ languages?: Language[];
34
+ /** The page's language now. */
35
+ language?: () => Language;
36
+ /** The app's texts and their locale keys: targets found in every language. See `dictionaryLabels`. */
37
+ labels?: Labels;
38
+ targets?: Omit<TargetsOptions, 'labels'>;
39
+ /** Actions only the app knows: a map's views and points. */
40
+ plugins?: DemoPlugin[];
41
+ start?: DemoStart;
42
+ /** Before a demo plays: the app ready to show. */
43
+ ready?: () => Promise<void> | void;
44
+ /** What a video shows: the app's element, cropped to where the browser can. */
45
+ filmElement?: () => Element | undefined;
46
+ overlay?: OverlayOptions;
47
+ /** The engine's UI: 'auto' follows the system. */
48
+ theme?: 'light' | 'dark' | 'auto';
49
+ /** Tools for an AI on `window[agent]`: 'demoEngine' by default; false for none. */
50
+ agent?: string | false;
51
+ /** A "Demos" button on the page opening the library: for apps without a panel of their own. */
52
+ launcher?: boolean;
53
+ /**
54
+ * Where a demo's narration pack is (`<id>.narration.zip`, made in the studio and checked in
55
+ * beside its `.demo.json`): its audio plays before any voice, for every viewer - no key, no
56
+ * tokens, no model to download. None where it has none.
57
+ */
58
+ narration?: (demo: Demo) => string | undefined;
59
+ };
60
+ /** What the engine is doing: one thing at a time. */
61
+ export type Session = {
62
+ mode: 'idle';
63
+ }
64
+ /** Waiting for a click in the app's window: only there may sound and filming start. */
65
+ | {
66
+ mode: 'ready';
67
+ title: string;
68
+ verb: string;
69
+ go: () => void;
70
+ cancel: () => void;
71
+ } | {
72
+ mode: 'preparing';
73
+ title: string;
74
+ text: string;
75
+ } | ({
76
+ mode: 'playing';
77
+ title: string;
78
+ demo: Demo;
79
+ steps: number;
80
+ filming: boolean;
81
+ checking: boolean;
82
+ guided: boolean;
83
+ looping: boolean;
84
+ player: Player;
85
+ } & PlayState) | ({
86
+ mode: 'recording';
87
+ filming: boolean;
88
+ microphone: boolean;
89
+ } & RecordState);
90
+ /** A demo the engine knows: come with the app, edited here, or made here. */
91
+ export type DemoEntry = {
92
+ demo: KeptDemo;
93
+ scenario: string;
94
+ origin: 'app' | 'edited' | 'here';
95
+ video?: DemoVideo;
96
+ };
97
+ export type EngineState = {
98
+ session: Session;
99
+ settings: DemoSettings;
100
+ speech: SpeechState;
101
+ message?: {
102
+ text: string;
103
+ error?: boolean;
104
+ };
105
+ /** The demo open in the studio; `opened` changes every time one is opened. */
106
+ studio?: {
107
+ demo: KeptDemo;
108
+ opened: number;
109
+ recorded?: {
110
+ steps: DemoStep[];
111
+ at: number;
112
+ };
113
+ };
114
+ /** The last play's timing, for the demo as it was: the studio's timeline shows it while that is what it edits. */
115
+ lastRun?: {
116
+ json: string;
117
+ language: Language;
118
+ timing: Timing;
119
+ };
120
+ /** Playing demos on a loop, unattended: an expo booth. `visitor`: someone took over; it plays again after idle. */
121
+ loop?: {
122
+ titles: string[];
123
+ index: number;
124
+ visitor: boolean;
125
+ resumesAt?: number;
126
+ };
127
+ /** A moment's note in the bar while playing: input held back. */
128
+ hint?: string;
129
+ };
130
+ export type LoopOptions = {
131
+ /** ms of no input before the loop plays again, after a visitor. Default the setting, 30 s. */
132
+ idle?: number;
133
+ /** ms between demos. Default 1500. */
134
+ gap?: number;
135
+ /**
136
+ * After a visitor, before the loop plays on: the app as it was. 'reload' reloads the page - the
137
+ * surest - and the loop plays on after it (with sound only where the browser allows it unasked).
138
+ * Default: each demo's start, and nothing else.
139
+ */
140
+ reset?: (() => Promise<void> | void) | 'reload';
141
+ };
142
+ export type CheckReport = {
143
+ ok: boolean;
144
+ error?: string;
145
+ failures: {
146
+ step: number;
147
+ index: number;
148
+ action: DemoAction;
149
+ error: string;
150
+ }[];
151
+ problems: Problem[];
152
+ duration: number;
153
+ };
154
+ /**
155
+ * Records, edits, narrates, plays and films demos of the app it is in: everything in the browser.
156
+ * Mount it once; play demos from code, from its library (`DemoLibrary`), its studio, or an AI
157
+ * (`window.demoEngine`).
158
+ */
159
+ export declare class DemoEngine {
160
+ readonly options: DemoEngineOptions;
161
+ readonly targets: Targets;
162
+ readonly overlay: Overlay;
163
+ readonly hand: Hand;
164
+ readonly speech: Speech;
165
+ readonly store: Store;
166
+ readonly plugins: DemoPlugin[];
167
+ private state;
168
+ private listeners;
169
+ private settingsKey;
170
+ private stopRecording;
171
+ private nextStepRecording;
172
+ private sayRecording;
173
+ private unmount;
174
+ private player;
175
+ private looping;
176
+ private musicLoaded;
177
+ private packs;
178
+ constructor(options: DemoEngineOptions);
179
+ getState: () => EngineState;
180
+ subscribe: (listener: () => void) => (() => void);
181
+ private emit;
182
+ private set;
183
+ private setSession;
184
+ private updateSession;
185
+ say(text: string | undefined, error?: boolean): void;
186
+ changeSettings(change: Partial<DemoSettings>): void;
187
+ /** The narration's language now. */
188
+ language(): Language;
189
+ /** The languages to write narration in. */
190
+ languages(): Language[];
191
+ /** Action kinds plugins add. */
192
+ pluginKinds(): string[];
193
+ pluginAction(kind: string): import("./Plugin").ActionHandler<any> | undefined;
194
+ /** An action as a sentence: 'Click "Save"'; with its element, named as the page shows it. */
195
+ read(action: DemoAction, element?: Element): string;
196
+ /** On the page: the overlay and the engine's UI, its keys, shared links, the AI's tools. */
197
+ mount(): Promise<void>;
198
+ destroy(): void;
199
+ /** A demo a link brought, one asked for by `?demo=`, or one to play once back from its start's reload. */
200
+ private arrived;
201
+ /**
202
+ * While a demo plays, the viewer's own input does not reach the app: a click or a key of theirs
203
+ * would take the demo off its path. Not the engine's controls, not a presenter's keys; not while
204
+ * paused (the app is the presenter's then), not at a booth (a visitor takes over), and guided,
205
+ * what the viewer is to act on.
206
+ */
207
+ private gate;
208
+ private hintTimer;
209
+ private hint;
210
+ private pendingKey;
211
+ private key;
212
+ /** Every demo: the app's (edited here, if they were), then those made here, newest first. */
213
+ entries(): Promise<DemoEntry[]>;
214
+ /** As `entries`, from what is read so far: for views. */
215
+ entriesNow(): DemoEntry[];
216
+ /** Kept here; over an app's demo of the same id, until `revert`. */
217
+ save(demo: KeptDemo): Promise<void>;
218
+ /** Gone from here: an app's demo is as it came again. */
219
+ remove(id: string): Promise<void>;
220
+ /** Read from JSON text: a file, a paste. */
221
+ parse(text: string): {
222
+ demo?: Demo;
223
+ problems: Problem[];
224
+ };
225
+ /** A new demo, starting where the app is now. */
226
+ create(title?: string): Demo;
227
+ openStudio(demo: KeptDemo): void;
228
+ closeStudio(): void;
229
+ private activated;
230
+ /** Runs it now if a click in this window just asked for it; else from such a click (`ready`). */
231
+ private whenClicked;
232
+ /** At the demo's start: false if the page goes there by reloading, and plays it then. */
233
+ private goToStart;
234
+ private busy;
235
+ /**
236
+ * Plays it, from a click in this window - else after one. Resolves when it ends; `error` says why
237
+ * it ended early.
238
+ */
239
+ play(demo: Demo, options?: Partial<PlayOptions>): Promise<PlayResult | undefined>;
240
+ /** Runs a demo now: no click asked, no start gone to. */
241
+ private run;
242
+ stop(): void;
243
+ togglePause(): void;
244
+ /** Resumes what is paused, or what waits for the presenter. */
245
+ resume(): void;
246
+ /** The presenter's next: on from a wait, or on to the next step. */
247
+ next(): void;
248
+ /** The presenter's back: this step again, or - in its first seconds - the one before. */
249
+ back(): void;
250
+ /** To a step of what plays (0-based): forward or back. False where it cannot (filmed). */
251
+ goTo(step: number): boolean;
252
+ /**
253
+ * Guided, for tutorials and trainings: the viewer does every click, entry and choice themselves,
254
+ * each ringed with what to do; the narration explains. "Do it for me" (`doItForMe`) lets the demo.
255
+ */
256
+ guide(demo: Demo, options?: Partial<PlayOptions>): Promise<PlayResult | undefined>;
257
+ /** Guided: the demo does what the viewer was to do. */
258
+ doItForMe(): void;
259
+ /** The demo's narration pack: made here (kept in this browser), else the app's (`narration`); none without. */
260
+ pack(demo: Demo): Promise<NarrationPack | undefined>;
261
+ /**
262
+ * The demo's narration, every sentence in every language it is written in, made once with the
263
+ * voice chosen - what a pack has already from that voice kept, ElevenLabs' kept answers not paid
264
+ * again - as `<id>.narration.zip`. Kept in this browser too; check it in beside the demo.
265
+ */
266
+ makePack(demo: Demo, progress?: (done: number, total: number) => void): Promise<Blob>;
267
+ /** Makes the pack, and downloads it: `<id>.narration.zip`. */
268
+ downloadPack(demo: Demo): Promise<void>;
269
+ /** The pack made here goes: the app's own (`narration`), or the voice, plays again. */
270
+ dropPack(demo: Demo): Promise<void>;
271
+ /** The music under demos: an audio file of one's own, kept here; none to go back to a composed track. */
272
+ setMusic(file: File | Blob | undefined): Promise<void>;
273
+ /** The chosen music, made or decoded once; false if there is none. */
274
+ private loadMusic;
275
+ /** The chosen music, to hear it: plays till the returned stop, or `seconds`. */
276
+ listenToMusic(seconds?: number): Promise<() => void>;
277
+ /**
278
+ * Plays the demos one after the other, again and again, unattended: an expo booth. A visitor's
279
+ * touch, click or key stops the demo and leaves the app to them; after `idle` ms without input,
280
+ * the app goes back to the demo's start and the loop plays on. Ctrl+Shift+L or `stopLoop` ends it.
281
+ * Sound needs one click on the page first - or a browser started to allow it (kiosk mode).
282
+ */
283
+ loop(demos: Demo[], options?: LoopOptions, from?: number): Promise<void>;
284
+ stopLoop(): void;
285
+ /** ms played of what plays now. */
286
+ elapsed(): number | undefined;
287
+ /**
288
+ * Plays it quickly and silently, going past what fails: whether every target is found and every
289
+ * action plays. From its start (`fromStart: false`: from where the app is); no click needed.
290
+ */
291
+ check(demo: Demo, options?: {
292
+ from?: number;
293
+ to?: number;
294
+ speed?: number;
295
+ fromStart?: boolean;
296
+ }): Promise<CheckReport>;
297
+ /** When what happens in it, about: as last played if it has not changed since, else estimated. */
298
+ timing(demo: Demo, language?: string): Timing;
299
+ /**
300
+ * Films it: the tab - the browser asks to share it - with the narration as sound, and the
301
+ * microphone if asked. Kept here with its subtitles; returns the video.
302
+ */
303
+ film(demo: Demo, options?: {
304
+ microphone?: boolean;
305
+ language?: Language;
306
+ }): Promise<DemoVideo | undefined>;
307
+ private filmNow;
308
+ private filmQuality;
309
+ /** What was said, timed: Whisper in the browser, or ElevenLabs with the key. */
310
+ transcribe(audio: Blob, language?: string): Promise<Subtitle[]>;
311
+ /**
312
+ * Records what is done on the page as a demo's steps, with the microphone - what is said becomes
313
+ * the narration - and filmed if asked (settings). `into`: a demo the steps go into, after step
314
+ * `after`; else a new one. Opens the result in the studio.
315
+ */
316
+ record(options?: {
317
+ into?: Demo;
318
+ after?: number;
319
+ }): Promise<void>;
320
+ private recordNow;
321
+ /** Recording: the next step starts. */
322
+ nextStep(): void;
323
+ /** Recording: the current step's narration. */
324
+ narrate(text: string): void;
325
+ /** Stops recording, and keeps what was recorded. */
326
+ finishRecording(): Promise<void>;
327
+ /** A link that opens the app with the demo in it. */
328
+ link(demo: Demo): Promise<string>;
329
+ /** The demo as a file: `.demo.json`, or its scenario as `.md`. */
330
+ downloadDemo(demo: KeptDemo, as?: 'json' | 'md'): void;
331
+ /** Its video, and subtitles beside it. */
332
+ downloadVideo(video: DemoVideo, title: string, subtitles?: 'vtt' | 'srt' | false): void;
333
+ /** Through the system's share sheet: the video and its subtitles. False where there is none. */
334
+ shareVideo(video: DemoVideo, title: string): Promise<boolean>;
335
+ /** The languages a demo is narrated in. */
336
+ languagesOf(demo: Demo): string[];
337
+ }
338
+ export { DEFAULT_SETTINGS };
@@ -0,0 +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 d}from"../model/Timing.js";import{parseDemo as c,validate as l}from"../model/Validate.js";import{Hand as g}from"../page/Input.js";import{Overlay as m}from"../page/Overlay.js";import{Targets as u}from"../page/Targets.js";import{Speech as y}from"../speech/Speech.js";import{narrationFor as f,transcribe as w}from"../speech/Transcribe.js";import{Store as v}from"../store/Store.js";import{demoFromLink as k,download as b,fileName as S,linkTo as P,shareFiles as x}from"../store/Share.js";import{extensionOf as T,recordMicrophone as E,startFilming as j,videoSize as $}from"../video/Film.js";import{renderMusic as M}from"../speech/Music.js";import{readPack as R,writePack as K}from"../speech/Pack.js";import{Player as N}from"./Player.js";import{Recorder as L}from"./Recorder.js";import{readAction as B}from"./Read.js";import{mountUI as D}from"../ui/EngineUI.js";import{agentTools as I}from"../agent/Agent.js";import{DEFAULT_SETTINGS as O,loadSettings as A,saveSettings as F}from"./Settings.js";const C=["pointerdown","pointerup","pointermove","pointerover","pointerout","mousedown","mouseup","mousemove","mouseover","mouseout","click","dblclick","contextmenu","wheel","touchstart","touchmove","touchend","keydown","keyup","keypress"];export class DemoEngine{constructor(e){this.options=e,this.listeners=new Set,this.packs=new Map,this.getState=()=>this.state,this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e)),this.hintTimer=0,this.targets=new u({...e.targets,labels:e.labels}),this.overlay=new m(e.overlay),this.hand=new g(this.overlay.cursor,()=>this.player?.speedNow??1),this.settingsKey=`protomaze-demo-engine:${e.app}:settings`,this.state={session:{mode:"idle"},settings:A(this.settingsKey),speech:{}},this.speech=new y(()=>this.state.settings.speech,()=>this.set({speech:{...this.speech.state}})),this.store=new v(`protomaze-demo-engine:${e.app}`),this.store.subscribe(()=>this.emit()),this.plugins=e.plugins??[]}emit(){this.state={...this.state},this.listeners.forEach(e=>e())}set(e){this.state={...this.state,...e},this.listeners.forEach(e=>e())}setSession(e){this.set({session:e})}updateSession(e,t){this.state.session.mode===e&&this.setSession({...this.state.session,...t})}say(e,t=!1){this.set({message:e?{text:e,error:t}:void 0})}changeSettings(e){const t={...this.state.settings,...e};F(this.settingsKey,t),this.set({settings:t}),e.music?.on&&this.loadMusic().catch(()=>{})}language(){const e=this.state.settings.language;return"page"!==e?e:this.options.language?.()??this.options.languages?.[0]??(navigator.language.split("-")[0]||"en")}languages(){return this.options.languages??[this.language()]}pluginKinds(){return this.plugins.flatMap(e=>Object.keys(e.actions??{}))}pluginAction(e){return this.plugins.map(t=>t.actions?.[e]).find(Boolean)}read(e,t){return B(e,this.options.labels,this.plugins,t)}async mount(){if(this.unmount)return;this.overlay.mount();const e=D(this),t=e=>this.key(e);window.addEventListener("keydown",t,!0);const s=e=>this.gate(e);C.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]=I(this)),this.unmount=()=>{e(),window.removeEventListener("keydown",t,!0),C.forEach(e=>window.removeEventListener(e,s,{capture:!0})),i&&delete window[i],this.overlay.unmount()},await this.arrived()}destroy(){this.stopLoop(),this.stop(),this.unmount?.(),this.unmount=void 0}async arrived(){const e=sessionStorage.getItem(this.pendingKey());if(sessionStorage.removeItem(this.pendingKey()),e){const{demo:t,verb:s,from:i,loop:o}=JSON.parse(e);return"loop"===s&&o?void this.loop(o.demos,{gap:o.gap,idle:o.idle,reset:o.reload?"reload":void 0},o.index):this.whenClicked(t.title,"film"===s?"Film":"Play",()=>"film"===s?this.film(t):this.play(t,{from:i}),!0)}const t=await k();if(t){const e=l(t,this.pluginKinds());return e.length?this.say(`The link's demo: ${e[0].path} ${e[0].message}`,!0):(await this.save(t),this.say(`"${t.title}" came with the link: it is kept here.`),this.openStudio(t))}const s=new URL(window.location.href),i=s.searchParams.get("demo");if(i){s.searchParams.delete("demo"),window.history.replaceState(window.history.state,"",s.toString());const e=(await this.entries()).find(e=>e.demo.id===i);e&&this.whenClicked(e.demo.title,"Play",()=>this.play(e.demo),!0)}}gate(e){const t=this.state.session;if(!e.isTrusted||"playing"!==t.mode||t.paused||t.looping)return;const s=e.composedPath();if(s.includes(this.overlay.host))return;if(t.guided&&t.instruction){const i=t.player.viewerTarget();if(i&&(s.includes(i)||e instanceof KeyboardEvent&&i.contains(document.activeElement)))return;if(!i&&e instanceof KeyboardEvent)return}const i=e.defaultPrevented;e.cancelable&&e.preventDefault(),e.stopImmediatePropagation(),i||"pointerdown"!==e.type&&"keydown"!==e.type&&"wheel"!==e.type||this.hint(t.guided?'Only the ringed part now: or "Do it for me"':"Playing: Space pauses, and the app is yours then. Esc stops.")}hint(e){window.clearTimeout(this.hintTimer),this.set({hint:e}),this.hintTimer=window.setTimeout(()=>this.set({hint:void 0}),3e3)}pendingKey(){return`protomaze-demo-engine:${this.options.app}:pending`}key(e){if(!e.isTrusted)return;const t=e.composedPath(),s=t.some(e=>e instanceof HTMLElement&&(e.isContentEditable||e.matches("input, textarea, select"))),i=t.includes(this.overlay.host),o=this.state.session,n=()=>{e.preventDefault(),e.stopPropagation()};if("ready"!==o.mode)if("recording"!==o.mode){if("l"===e.key.toLowerCase()&&e.ctrlKey&&e.shiftKey&&this.looping)return n(),this.stopLoop();if(!("playing"!==o.mode||o.looping||o.checking||s&&(i||o.guided&&o.instruction))){if("Escape"===e.key)this.stop();else if(" "===e.key||"b"===e.key||"."===e.key)this.togglePause();else if("ArrowRight"===e.key||"Enter"===e.key||"PageDown"===e.key)o.player.next();else if("ArrowLeft"===e.key||"PageUp"===e.key)o.player.back();else if("Home"===e.key)o.player.goTo(0);else if("End"===e.key)o.player.goTo(o.steps-1);else{if(!/^[1-9]$/.test(e.key)||e.ctrlKey||e.metaKey||e.altKey)return;o.player.goTo(Number(e.key)-1)}n()}}else"Escape"!==e.key||s||(n(),this.stopRecording?.());else"Escape"===e.key&&(n(),o.cancel())}async entries(){return await this.store.ready(),this.entriesNow()}entriesNow(){const{demos:e,videos:t}=this.store.get(),s=new Map(e.map(e=>[e.id,e])),i=this.language(),n=(this.options.demos??[]).map(e=>"demo"in e?e:{demo:e,scenario:void 0});return[...n.map(({demo:e,scenario:n})=>{const a=s.get(e.id);return a?{demo:a,scenario:a.scenario??n??o(a,i),origin:"edited",video:t.get(e.id)}:{demo:e,scenario:n??o(e,i),origin:"app",video:t.get(e.id)}}),...e.filter(e=>!n.some(t=>t.demo.id===e.id)).map(e=>({demo:e,scenario:e.scenario??o(e,i),origin:"here",video:t.get(e.id)}))]}async save(t){const s=l(t,this.pluginKinds());if(s.length)throw new Error(`Not a demo: ${s.map(e=>`${e.path} ${e.message}`).join("; ")}`);await this.store.saveDemo(e(t))}async remove(e){await this.store.deleteDemo(e),this.state.studio?.demo.id===e&&this.closeStudio()}parse(e){return c(e,this.pluginKinds())}create(e){return s(e,this.options.start?.current())}openStudio(t){this.set({studio:{demo:e(t),opened:Date.now()}})}closeStudio(){this.set({studio:void 0})}activated(){const e=navigator.userActivation;return!e||e.isActive}whenClicked(e,t,s,i=!1){const o=()=>{this.setSession({mode:"idle"}),this.speech.wake(),s().catch(e=>this.say(e.message,!0))};if(!i&&this.activated())return o();this.setSession({mode:"ready",title:e,verb:t,go:o,cancel:()=>this.setSession({mode:"idle"})})}async goToStart(e,t,s,i){if(!e.start||!this.options.start)return!0;sessionStorage.setItem(this.pendingKey(),JSON.stringify({demo:e,verb:t,from:s,loop:i}));return"reload"!==await this.options.start.go(e.start)&&(sessionStorage.removeItem(this.pendingKey()),!0)}busy(){return"idle"!==this.state.session.mode&&"ready"!==this.state.session.mode}play(e,t={}){return new Promise(s=>this.whenClicked(e.title,"Play",async()=>{if(this.busy())return s(void 0);if(this.say(void 0),!await this.goToStart(e,"play",t.from))return s(void 0);const i=await this.run(e,t);s(i)}))}async run(e,t={}){const{settings:s}=this.state,i=t.language??this.language(),o=s.music.on&&!t.checking&&!t.guided&&await Promise.race([this.loadMusic(),new Promise(e=>setTimeout(()=>e(!1),t.filming?6e4:1500))]);this.speech.setPack(s.usePacks?await this.pack(e):void 0);const n=new N(e,{language:i,subtitles:s.subtitles,waitForPresenter:s.waitForPresenter&&!t.looping,catchUp:s.catchUp,music:Boolean(o),...t},{hand:this.hand,targets:this.targets,overlay:this.overlay,speech:this.speech,plugins:this.plugins,ready:this.options.ready,read:(e,t)=>this.read(e,t),reset:async()=>!e.start||!this.options.start||"reload"!==await this.options.start.go(e.start),update:e=>this.updateSession("playing",e)});this.setSession({mode:"playing",title:e.title,demo:e,steps:e.steps.length,filming:Boolean(t.filming),checking:Boolean(t.checking),guided:Boolean(t.guided),looping:Boolean(t.looping),player:n,step:t.from??0,caption:"",paused:!1,waiting:!1,catchingUp:!1}),this.player=n;const a=await n.play().finally(()=>this.player=void 0);return this.setSession({mode:"idle"}),t.checking||a.navigated||(this.set({lastRun:{json:JSON.stringify(e),language:i,timing:a.timing}}),a.error&&"Stopped."!==a.error&&this.say(a.error,!0)),a}stop(){const e=this.state.session;"playing"===e.mode&&e.player.stop(),"recording"===e.mode&&this.stopRecording?.(),"ready"!==e.mode&&"preparing"!==e.mode||this.setSession({mode:"idle"})}togglePause(){const e=this.state.session;"playing"===e.mode&&(e.paused?e.player.resume():e.player.pause())}resume(){const e=this.state.session;"playing"===e.mode&&e.player.resume()}next(){const e=this.state.session;"playing"===e.mode&&e.player.next()}back(){const e=this.state.session;"playing"===e.mode&&e.player.back()}goTo(e){const t=this.state.session;return"playing"===t.mode&&t.player.goTo(e)}guide(e,t={}){return this.play(e,{...t,guided:!0})}doItForMe(){const e=this.state.session;"playing"===e.mode&&e.player.doItForMe()}pack(e){let t=this.packs.get(e.id);return t||(t=(async()=>{const t=await this.store.asset(`narration:${e.id}`);if(t)return R(await t.arrayBuffer());const s=this.options.narration?.(e);if(!s)return;const i=await fetch(s);return i.ok?R(await i.arrayBuffer()):void 0})().catch(()=>{}),this.packs.set(e.id,t)),t}async makePack(e,s=()=>{}){const i=await this.pack(e);this.speech.setPack(i);const o=t(e).flatMap(t=>e.steps.flatMap(e=>n(e.say[t]??"").map(e=>({language:t,text:e})))),a=o.filter((e,t)=>o.findIndex(t=>t.language===e.language&&t.text===e.text)===t),r=[];for(const e of a)s(r.length,a.length),r.push({...await this.speech.packable(e.text,e.language),...e});s(r.length,a.length);const h=K(e.id,r);return await this.store.saveAsset(`narration:${e.id}`,h),this.packs.delete(e.id),h}async downloadPack(e){try{const t=await this.makePack(e,(e,t)=>this.say(`Making the narration pack: ${e} / ${t}`));b(t,`${e.id}.narration.zip`),this.say(`Narration pack: ${Math.round(t.size/1e5)/10} MB, kept here too. Check it in beside ${e.id}.demo.json, for every viewer.`)}catch(e){this.say(`Narration pack: ${e.message}`,!0)}}async dropPack(e){await this.store.saveAsset(`narration:${e.id}`,void 0),this.packs.delete(e.id)}async setMusic(e){await this.store.saveAsset("music",e),this.musicLoaded=void 0;const{music:t}=this.state.settings;this.changeSettings({music:e?{...t,on:!0,track:"file",name:e.name??"music"}:{...t,track:"calm",name:void 0}})}async loadMusic(){const{music:e}=this.state.settings,t="file"===e.track?`file:${e.name}`:e.track;if(this.musicLoaded!==t){if("file"===e.track){const t=await this.store.asset("music");if(!t)return!1;await this.speech.setMusic(t,e.volume).catch(()=>{})}else this.speech.setMusicBuffer(await M(e.track),e.volume);this.musicLoaded=t}return this.speech.setMusicVolume(e.volume),this.speech.hasMusic}async listenToMusic(e=20){if(this.speech.wake(),!await this.loadMusic())return()=>{};this.speech.startMusic();const t=setTimeout(()=>this.speech.stopMusic(),1e3*e);return()=>{clearTimeout(t),this.speech.stopMusic(.6)}}async loop(e,t={},s=0){if(0===e.length)return;this.stopLoop();let i=!1,o=0,n=s;const a=t.idle??this.state.settings.loopIdle,r=t.gap??1500,h=e.map(e=>e.title),p=e=>{if(!e.isTrusted||e.composedPath().includes(this.overlay.host))return;o=performance.now();const t=this.state.session;"playing"===t.mode&&t.looping&&t.player.stop(!0)},d=["pointerdown","keydown","wheel","touchstart"];d.forEach(e=>window.addEventListener(e,p,{capture:!0,passive:!0}));this.looping={demos:e,options:t,stop:()=>{i=!0,d.forEach(e=>window.removeEventListener(e,p,{capture:!0}));const e=this.state.session;"playing"===e.mode&&e.looping&&e.player.stop(),this.set({loop:void 0})}};const c=e=>new Promise(t=>setTimeout(t,e));for(;!i;){const s=e[n%e.length];this.set({loop:{titles:h,index:n%e.length,visitor:!1}});if(!await this.goToStart(s,"loop",void 0,{demos:e,index:n%e.length,gap:t.gap,idle:t.idle,reload:"reload"===t.reset})||i)return;const p=await this.run(s,{looping:!0,catchUp:!1});if(i)break;if(p.error&&performance.now()-o<1e3){for(;!i&&performance.now()-o<a;)this.set({loop:{titles:h,index:n%e.length,visitor:!0,resumesAt:Date.now()+a-(performance.now()-o)}}),await c(1e3);if(i)break;if("reload"===t.reset)return sessionStorage.setItem(this.pendingKey(),JSON.stringify({demo:s,verb:"loop",loop:{demos:e,index:n%e.length,gap:t.gap,idle:t.idle,reload:!0}})),window.location.reload();await(t.reset?.())}else n++,await c(r)}}stopLoop(){this.looping?.stop(),this.looping=void 0}elapsed(){const e=this.state.session;return"playing"===e.mode?e.player.elapsed():void 0}async check(e,t={}){const s=l(e,this.pluginKinds());if(s.length)return{ok:!1,problems:s,failures:[],duration:0,error:"Not a valid demo"};if(this.busy())return{ok:!1,problems:s,failures:[],duration:0,error:`Busy: ${this.state.session.mode}`};if(!1!==t.fromStart&&e.start&&this.options.start){if("reload"===await this.options.start.go(e.start))return{ok:!1,problems:s,failures:[],duration:0,error:"Its start reloads the page: check again once it is back"}}const i=await this.run(e,{...t,speed:t.speed??8,keepGoing:!0,checking:!0,catchUp:!0,subtitles:!1}),o=i.failures.map(t=>({...t,action:e.steps[t.step].actions[t.index]}));return{ok:!i.error&&0===o.length,error:i.error,failures:o,problems:s,duration:i.timing.duration}}timing(e,t=this.language()){const s=this.state.lastRun;return s&&s.language===t&&s.json===JSON.stringify(e)&&s.timing.steps.length===e.steps.length?s.timing:d(e,{language:t,sayTime:e=>this.speech.duration(e,t),actionTime:e=>{const t=this.pluginAction(e.do);return t?.duration?.(e)??p(e)}})}film(e,t={}){return new Promise(s=>this.whenClicked(e.title,"Film",async()=>this.busy()?s(void 0):(this.say(void 0),await this.goToStart(e,"film")?void s(await this.filmNow(e,t)):s(void 0))))}async filmNow(e,t){const s=t.language??this.language();let o=!1;const a=await 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:d}=await a.stop();if(!r||r.error)return void this.say("Stopped."!==r?.error&&r?`Filming failed: ${r.error}`:"Filming stopped: nothing kept.",Boolean(r?.error&&"Stopped."!==r.error));let c=r.timing.cues;d&&"off"===this.state.settings.speech.voice&&(this.setSession({mode:"preparing",title:e.title,text:"Transcribing what was said"}),c=await this.transcribe(d,s).catch(()=>c),this.setSession({mode:"idle"}));const l={id:e.id,blob:p,at:Date.now(),json:JSON.stringify(e),vtt:h(c),timing:r.timing,language:s,...d?{voice:d}:{}};return await this.store.saveVideo(l),this.say(`Filmed "${e.title}": ${Math.round(p.size/1e6)} MB, kept here.`),l}filmQuality(){const{frameRate:e,bitrate:t,lines:s,aspect:i,fit:o}=this.state.settings.film;return{frameRate:e,bitrate:t,fit:o,...s?{size:$(s,i)}:{}}}async transcribe(e,t=this.language()){const{settings:s}=this.state;return w(e,{language:t,with:s.transcriber,model:s.whisperModel,elevenLabsKey:s.speech.elevenlabs.key,progress:e=>this.set({speech:e<1?{loading:e}:{}})})}record(e={}){return new Promise(t=>this.whenClicked(e.into?.title??"New demo","Record",async()=>{if(this.busy())return t();this.say(void 0),await this.recordNow(e,t)}))}async recordNow(t,i){const{settings:o}=this.state,n=this.language();let a,r;try{o.filmRecording?a=await j({soundtrack:this.speech.soundtrack(),microphone:o.microphone,crop:this.options.filmElement?.(),...this.filmQuality(),onEnded:()=>{this.stopRecording?.()}}):o.microphone&&(r=await E())}catch(e){return this.say(`Could not start: ${e.message}`,!0),i()}const p=this.options.start?.current(),d=new L(this.targets,this.plugins,n,e=>this.updateSession("recording",e));a?.resume();const c=performance.now();this.setSession({mode:"recording",filming:Boolean(a),microphone:Boolean(r||a&&o.microphone),step:0,caption:"",actions:0}),this.nextStepRecording=()=>d.nextStep(),this.sayRecording=e=>d.say(e),this.stopRecording=async()=>{this.stopRecording=this.nextStepRecording=this.sayRecording=void 0;const l=Boolean(r||a&&o.microphone),g=d.stop(l),m=performance.now()-c;this.setSession({mode:"preparing",title:"Recording",text:"Keeping what was recorded"});try{const[i,o]=await Promise.all([r?.stop(),a?.stop()]),d=i??o?.voice;let c=[];if(d){this.updateSession("preparing",{text:"Transcribing what was said"});try{c=await this.transcribe(d,n);const e=f(g.stepStarts,c);g.steps.forEach((t,s)=>{!t.say[n]&&e[s]&&(t.say[n]=e[s])})}catch(e){this.say(`Transcribing failed: ${e.message}`,!0)}}const l=g.steps.filter(e=>e.actions.length>0||Object.values(e.say).some(Boolean)),u=t.into?e(t.into):{...s("Recorded demo",p),steps:[]},y=t.after??u.steps.length-1,w={...u,steps:[...u.steps.slice(0,y+1),...l,...u.steps.slice(y+1)]};0===w.steps.length&&w.steps.push({say:{},actions:[]}),o&&await this.store.saveVideo({id:w.id,blob:o.video,at:Date.now(),json:JSON.stringify(w),vtt:h(c),language:n,timing:{duration:m,steps:g.stepStarts.map((e,t)=>({step:t,start:e,end:g.stepStarts[t+1]??m})),cues:c.map(e=>({...e,step:0})),actions:[]},...o.voice?{voice:o.voice}:{}}),this.setSession({mode:"idle"}),this.say(`Recorded ${l.length} step${1===l.length?"":"s"}${o?", and filmed":""}.`),t.into&&this.state.studio?.demo.id===t.into.id?this.set({studio:{...this.state.studio,recorded:{steps:w.steps,at:Date.now()}}}):this.openStudio(w)}catch(e){this.setSession({mode:"idle"}),this.say(e.message,!0)}i()}}nextStep(){this.nextStepRecording?.()}narrate(e){this.sayRecording?.(e)}async finishRecording(){await(this.stopRecording?.())}link(e){return P(e)}downloadDemo(e,t="json"){if("md"===t)return b(e.scenario??o(e,this.language()),S(e.id,"md"),"text/markdown");const{scenario:s,savedAt:i,...n}=e;b(JSON.stringify(n,null,2)+"\n",S(e.id,"demo.json"),"application/json")}downloadVideo(e,t,s=!1){return"vtt"===s?b(e.vtt,S(t,"vtt"),"text/vtt"):"srt"===s?b(r(a(e.vtt)),S(t,"srt"),"application/x-subrip"):void b(e.blob,S(t,T(e.blob)))}shareVideo(e,t){return x([new File([e.blob],S(t,T(e.blob)),{type:e.blob.type}),new File([e.vtt],S(t,"vtt"),{type:"text/vtt"})],t)}languagesOf(e){return t(e)}}export{O as DEFAULT_SETTINGS};
@@ -0,0 +1,12 @@
1
+ import type { DemoAction } from '../model/Demo';
2
+ import { Targets } from '../page/Targets';
3
+ export declare function isGuided(action: DemoAction): boolean;
4
+ /**
5
+ * Resolves once the viewer has done the action on the page themselves - a real click on its
6
+ * target, its text typed, its option chosen, its key pressed - or `cancel` is called. Only real
7
+ * input counts; the demo's own does not.
8
+ */
9
+ export declare function waitForViewer(action: DemoAction, targets: Targets): {
10
+ done: Promise<void>;
11
+ cancel: () => void;
12
+ };
@@ -0,0 +1 @@
1
+ import{parseChord as e}from"../page/Input.js";import{IGNORED as t,normal as o}from"../page/Targets.js";const r=new Set(["click","hover","type","select","drag","key"]);export function isGuided(e){return r.has(e.do)}export function waitForViewer(r,n){const c=r.target,a=e=>{if(!c)return!0;const t=n.matches(c)[c.index??0];return Boolean(t&&e.composedPath().includes(t))},i=[];let s=()=>{};const l=new Promise(e=>s=e),u=()=>{i.splice(0).forEach(e=>e()),s()},d=(e,o)=>{const r=e=>{e.isTrusted&&!e.target?.closest?.(t)&&o(e)&&setTimeout(u,150)};document.addEventListener(e,r,!0),i.push(()=>document.removeEventListener(e,r,!0))},p=r;switch(r.do){case"click":d(p.right?"contextmenu":p.double?"dblclick":"click",a);break;case"hover":{let e=0;d("pointerover",t=>{window.clearTimeout(e),a(t)&&(e=window.setTimeout(u,500))}),i.push(()=>window.clearTimeout(e));break}case"type":{const e=o(String(p.text??""));d("input",t=>a(t)&&o(t.target.value??t.target.innerText??"")===e),d("keydown",e=>a(e)&&"Enter"===e.key);break}case"select":{const e=String(p.option??"").trim().toLowerCase();d("change",t=>{const o=t.target;return a(t)&&(o.value===p.option||o.selectedOptions?.[0]?.text.trim().toLowerCase()===e)});break}case"drag":{let e;d("pointerdown",t=>{e=a(t)?{x:t.clientX,y:t.clientY}:void 0}),d("pointerup",t=>Boolean(e&&Math.hypot(t.clientX-e.x,t.clientY-e.y)>5)),d("change",e=>a(e)&&"range"===e.target.type);break}case"key":{const t=e(String(p.key));d("keydown",e=>e.key.toLowerCase()===t.key.toLowerCase()&&e.ctrlKey===t.ctrlKey&&e.altKey===t.altKey&&e.metaKey===t.metaKey&&a(e));break}default:setTimeout(u,0)}return{done:l,cancel:u}}
@@ -0,0 +1,154 @@
1
+ import { Demo, DemoAction, DemoTarget, Language } from '../model/Demo';
2
+ import { Timing } from '../model/Timing';
3
+ import { Hand } from '../page/Input';
4
+ import type { Overlay } from '../page/Overlay';
5
+ import { Targets } from '../page/Targets';
6
+ import type { Speech } from '../speech/Speech';
7
+ import type { Filming } from '../video/Film';
8
+ import type { DemoPlugin } from './Plugin';
9
+ export type PlayOptions = {
10
+ language: Language;
11
+ /** The step to start at, 0-based. */
12
+ from?: number;
13
+ /** The last step to play, 0-based; all by default. */
14
+ to?: number;
15
+ /** Earlier steps' actions first, quickly and silently, so the app is where `from` expects it. Default true. */
16
+ catchUp?: boolean;
17
+ /** Faster than life: a check. Narration is left out above 1. */
18
+ speed?: number;
19
+ /** Keeps going past an action that fails, noting it: a check. */
20
+ keepGoing?: boolean;
21
+ /** Waits for the presenter after each step. */
22
+ waitForPresenter?: boolean;
23
+ filming?: Filming;
24
+ /** Subtitles shown. Default true. */
25
+ subtitles?: boolean;
26
+ /** The viewer does the clicks, typing and choices, each shown and waited for: a tutorial. */
27
+ guided?: boolean;
28
+ /** The music bed under the narration (`Speech.setMusic`). */
29
+ music?: boolean;
30
+ };
31
+ export type PlayResult = {
32
+ /** When what happened, ms from the start: the subtitles are its cues. */
33
+ timing: Timing;
34
+ /** Why it stopped early: 'Stopped.' when stopped. */
35
+ error?: string;
36
+ /** Actions that failed, where it kept going. */
37
+ failures: {
38
+ step: number;
39
+ index: number;
40
+ error: string;
41
+ }[];
42
+ /** Gone forward or back by the presenter: its timing is not the demo's. */
43
+ navigated?: boolean;
44
+ };
45
+ export type PlayState = {
46
+ step: number;
47
+ caption: string;
48
+ paused: boolean;
49
+ /** Paused for the presenter, after a step. */
50
+ waiting: boolean;
51
+ /** Catching up with `from`. */
52
+ catchingUp: boolean;
53
+ /** Guided: what the viewer is to do now. */
54
+ instruction?: string;
55
+ };
56
+ export type PlayerContext = {
57
+ hand: Hand;
58
+ targets: Targets;
59
+ overlay: Overlay;
60
+ speech: Speech;
61
+ plugins: DemoPlugin[];
62
+ /** Before the first step: the app ready to be shown. */
63
+ ready?: () => Promise<void> | void;
64
+ /** An action as an instruction to the viewer: 'Click "Save"'. */
65
+ read(action: DemoAction, element?: Element): string;
66
+ /** The app back at the demo's start (`DemoStart.go`): going back a step replays from there. False if it cannot. */
67
+ reset?: () => Promise<boolean>;
68
+ update(state: Partial<PlayState>): void;
69
+ };
70
+ /** Plays one demo: each step's narration - spoken, a sentence a subtitle - while its actions run. */
71
+ export declare class Player {
72
+ private demo;
73
+ private options;
74
+ private context;
75
+ private stopped;
76
+ private pausedAt;
77
+ private held;
78
+ private t0;
79
+ private silence;
80
+ private speed;
81
+ /** On to the next step: what is left of this one quickly, silently. */
82
+ private hurrying;
83
+ /** A step to go to, asked for by the presenter. */
84
+ private jump;
85
+ /** Going back: what is left of this step is dropped, not done. */
86
+ private dropping;
87
+ private navigated;
88
+ private stepNow;
89
+ private stepStart;
90
+ private last;
91
+ /** Guided: the viewer's turn given up, the demo does it. */
92
+ private skipViewer;
93
+ /** Whether the viewer did the last guided action, so the demo leaves it. */
94
+ private viewerDid;
95
+ private keepApp;
96
+ private target;
97
+ constructor(demo: Demo, options: PlayOptions, context: PlayerContext);
98
+ /** ms played, paused time left out. */
99
+ elapsed(): number;
100
+ get paused(): boolean;
101
+ pause(waiting?: boolean): void;
102
+ resume(): void;
103
+ /** Stops it; `keepApp`: leaves the app as it is - its cleanup not done - for whoever took it over. */
104
+ stop(keepApp?: boolean): void;
105
+ /** Guided: the element the viewer is to act on now; none while the demo acts. */
106
+ viewerTarget(): Element | undefined;
107
+ /** How fast it plays now: the hand moves as fast. */
108
+ get speedNow(): number;
109
+ /**
110
+ * The presenter's next (right arrow, PageDown, a clicker): on from a wait, else on to the next
111
+ * step - what is left of this one done quickly, so the app is where the next one expects it.
112
+ */
113
+ next(): void;
114
+ /**
115
+ * The presenter's back (left arrow, PageUp): this step again from its start - or, pressed in its
116
+ * first seconds, the one before.
117
+ */
118
+ back(): void;
119
+ /**
120
+ * To a step: forward, what is left of this one done quickly and the steps between caught up
121
+ * under a card; back, the app reset to the demo's start (its cleanup, then `reset`) and caught
122
+ * up to the step. False where it cannot: filmed, a video would show it.
123
+ */
124
+ goTo(step: number): boolean;
125
+ /** The step playing, 0-based. */
126
+ get step(): number;
127
+ private get waiting();
128
+ private waitingNow;
129
+ /** Guided: the demo does what the viewer was to do. */
130
+ doItForMe(): void;
131
+ /** ms of play, less while paused; sooner when stopped or hurried. */
132
+ private sleep;
133
+ private whilePaused;
134
+ private find;
135
+ /** An element an effect follows: found again if the app replaced it. */
136
+ private follow;
137
+ play(): Promise<PlayResult>;
138
+ /**
139
+ * Guided: the target ringed with what to do, till the viewer does it - or gives their turn up
140
+ * ("Do it for me", next), and the demo does it.
141
+ */
142
+ private viewerDoes;
143
+ /** The demo's cleanup, quick and unseen, whatever fails: the app as the demo found it. */
144
+ private cleanup;
145
+ /** Under a card naming the step: what the audience need not see happen. */
146
+ private covered;
147
+ /** Back to a step: the app as the demo found it - its cleanup, its start - then caught up to the step. */
148
+ private rewind;
149
+ /** Steps' interactions from `from` until `until`, quick and silent: the app where the step expects it. */
150
+ private catchUp;
151
+ /** Does it; a presentation effect returns how to take it down. */
152
+ private perform;
153
+ }
154
+ export declare function describeTarget(target: DemoTarget): string;
@@ -0,0 +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.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 waiting(){return void 0!==this.pausedAt&&this.waitingNow}doItForMe(){this.skipViewer()}async whilePaused(){for(;void 0!==this.pausedAt&&!this.stopped;)await c(50)}async find(t){const e=await this.context.targets.find(t,1e4,()=>this.stopped);if(!e)throw new Error(this.stopped?"Stopped.":`Not found: ${describeTarget(t)}`);return e}follow(t,e){let s=e;return()=>(s?.isConnected||(s=this.context.targets.matches(t)[t.index??0]),s)}async play(){const{demo:e,options:n,context:r}=this,p=n.language,d=Math.max(0,Math.min(n.from??0,e.steps.length-1)),l=Math.min(n.to??e.steps.length-1,e.steps.length-1),u=this.speed>1,w={duration:0,steps:[],cues:[],actions:[]},g=[];let f;const m=new Set;try{this.last=l,d>0&&!1!==n.catchUp&&await this.catchUp(0,d);const f=e.steps.map(t=>u?[]: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.context.update({caption:""}),this.context.overlay.quiet=!0;try{for(const i of e)s(i)||(await this.sleep(Math.min(i.wait??t,1e3)),await this.perform(i,this.options.language).catch(()=>{}))}finally{this.context.overlay.quiet=!1,[this.stopped,this.speed]=[i,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??1e4);for(;!this.stopped;){if(this.context.targets.matches(t.target).some(t=>t.getClientRects().length>0)!==Boolean(t.gone))return;if(performance.now()>e)throw new Error(`${t.gone?"Still there":"Not found"}: ${describeTarget(t.target)}`);await c(100)}return}case"clear":return void 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}`:""}`}
@@ -0,0 +1,56 @@
1
+ import type { DemoAction, DemoTarget, Language } from '../model/Demo';
2
+ import type { Hand } from '../page/Input';
3
+ import type { Overlay } from '../page/Overlay';
4
+ import type { Targets } from '../page/Targets';
5
+ /** What an action of a plugin plays with. */
6
+ export type PlayContext = {
7
+ /** The pointer and keyboard: moves, clicks, drags as a person would. */
8
+ hand: Hand;
9
+ targets: Targets;
10
+ overlay: Overlay;
11
+ /** The target's element once it shows; throws if it does not in time. */
12
+ find(target: DemoTarget): Promise<Element>;
13
+ /** ms, less while paused; sooner when stopped. Divided by `speed`. */
14
+ sleep(ms: number): Promise<void>;
15
+ stopped(): boolean;
16
+ /** 1 when played, more when checked or caught up with. */
17
+ speed: number;
18
+ language: Language;
19
+ };
20
+ /** What a plugin records with. */
21
+ export type RecordContext = {
22
+ /** Adds an action to the step being recorded; `at`: when it happened (performance.now()). */
23
+ push(action: DemoAction, at?: number): void;
24
+ };
25
+ /** How a plugin records: claims what is done on its part of the page. */
26
+ export type PluginRecorder = {
27
+ /** Its part of the page - a map - where the engine records nothing itself: drags there are the plugin's to see. */
28
+ claims?(element: Element): boolean;
29
+ /** A click on its part, as its own action - a map's point - or none. */
30
+ click?(element: Element, x: number, y: number, event: PointerEvent): DemoAction | undefined;
31
+ /** A hover asked for (Alt+H) on its part, as its own action, or none. */
32
+ hover?(element: Element, x: number, y: number): DemoAction | undefined;
33
+ /** Before anything else is pushed: what is pending goes first (where a map came to rest). */
34
+ flush?(): void;
35
+ stop(): void;
36
+ };
37
+ export type ActionHandler<A extends DemoAction = DemoAction> = {
38
+ play(action: A, context: PlayContext): Promise<void> | void;
39
+ /** As a sentence, for the editor: "Move the map". */
40
+ read?(action: A): string;
41
+ /** A new one, for the editor's Add menu. */
42
+ template?(): A;
43
+ /** ms it takes once started, about, for the timeline. */
44
+ duration?(action: A): number;
45
+ };
46
+ /**
47
+ * What an app adds: actions on what only it knows - a map's views and points - and how they are
48
+ * recorded.
49
+ */
50
+ export type DemoPlugin = {
51
+ name: string;
52
+ /** Its actions, by `do`. */
53
+ actions?: Record<string, ActionHandler<any>>;
54
+ /** Starts recording its part; the engine stops it. */
55
+ record?(context: RecordContext): PluginRecorder;
56
+ };
@@ -0,0 +1 @@
1
+ export{};
@@ -0,0 +1,5 @@
1
+ import type { DemoAction } from '../model/Demo';
2
+ import type { Labels } from '../page/Targets';
3
+ import type { DemoPlugin } from './Plugin';
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;
package/engine/Read.js ADDED
@@ -0,0 +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}}