@protomaze/demo-engine 0.0.0-stage → 0.1.0

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