@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,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
+ }
@@ -0,0 +1 @@
1
+ import{fractionIn as t,IGNORED as e}from"../page/Targets.js";const[s,i]=[300,4e3],r=new Set(["Enter","Escape","Tab","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","PageUp","PageDown","Home","End","Delete","Backspace","F1","F2"]),n=new Set(["Control","Shift","Alt","Meta","AltGraph","CapsLock"]);export class Recorder{constructor(t,e,s,i){this.targets=t,this.language=s,this.update=i,this.steps=[{say:{},actions:[]}],this.stepStarts=[0],this.since=performance.now(),this.last=performance.now(),this.pointer={x:0,y:0},this.stops=[],this.recorders=e.flatMap(t=>t.record?[t.record({push:(t,e)=>this.push(t,e,!0)})]:[]);const r=(t,e)=>{document.addEventListener(t,e,!0),this.stops.push(()=>document.removeEventListener(t,e,!0))};r("pointerdown",t=>this.down(t)),r("pointerup",t=>this.up(t)),r("pointermove",t=>this.pointer={x:t.clientX,y:t.clientY}),r("input",t=>this.input(t)),r("change",t=>this.change(t)),r("keydown",t=>this.key(t))}push(t,e=performance.now(),r=!1){r||this.recorders.forEach(t=>t.flush?.());const n=Math.round(Math.min(i,Math.max(s,e-this.last)));this.current.actions.push({...t,wait:n}),this.last=e,this.update({actions:this.steps.reduce((t,e)=>t+e.actions.length,0)})}get current(){return this.steps[this.steps.length-1]}ignored(t){const s=t.target;return!t.isTrusted||!s?.closest||Boolean(s.closest(e))}claimedBy(t){return this.recorders.find(e=>e.claims?.(t))}down(t){if(this.pressed=void 0,this.ignored(t)||0!==t.button)return;const e=t.target,s=this.claimedBy(e);if(s)return void(this.pressed={x:t.clientX,y:t.clientY,element:e,claimed:s});const i=this.targets.targetElement(e);!i||i instanceof HTMLSelectElement||(this.pressed={x:t.clientX,y:t.clientY,element:i})}up(e){const s=this.pressed;if(this.pressed=void 0,!s||!e.isTrusted)return;const i=Math.hypot(e.clientX-s.x,e.clientY-s.y)>5;if(s.claimed){if(i)return;const t=s.claimed.click?.(s.element,s.x,s.y,e);return void(t&&this.push(t))}const r=this.targets.describe(s.element),n={...e.shiftKey?{shift:!0}:{},...e.ctrlKey?{ctrl:!0}:{},...e.altKey?{alt:!0}:{},...e.metaKey?{meta:!0}:{}};if(!i){const e=s.element.matches('canvas, video, [role="slider"], input[type="range"], [role="gridcell"]')||s.element.getBoundingClientRect().width>160;return void this.push({do:"click",target:r,...e?{at:t(s.element,s.x,s.y)}:{},...n})}const o=s.element.getBoundingClientRect(),a=e.clientX>=o.left&&e.clientX<=o.right&&e.clientY>=o.top&&e.clientY<=o.bottom,c=document.elementFromPoint(e.clientX,e.clientY),h=a?void 0:this.targets.targetElement(c);this.push({do:"drag",target:r,at:t(s.element,s.x,s.y),to:h?{target:this.targets.describe(h),at:t(h,e.clientX,e.clientY)}:{at:t(s.element,e.clientX,e.clientY)},...n})}input(t){if(this.ignored(t))return;const e=t.target,s=e.isContentEditable;if(!s&&!e.matches("input, textarea"))return;if(["checkbox","radio","range","color","file"].includes(e.type))return;const i=s?this.targets.targetElement(e)??e:e,r=this.targets.describe(i),n=s?e.innerText:e.value,o=this.current.actions.at(-1),a=JSON.stringify(o?.target)===JSON.stringify(r);return"type"===o?.do&&a?(o.text=n,void(this.last=performance.now())):"click"===o?.do&&a?(this.current.actions.pop(),this.current.actions.push({do:"type",target:r,text:n,wait:o.wait}),void(this.last=performance.now())):void this.push({do:"type",target:r,text:n})}change(t){if(this.ignored(t)||!(t.target instanceof HTMLSelectElement))return;const e=t.target;this.push({do:"select",target:this.targets.describe(e),option:e.selectedOptions[0]?.text.trim()??e.value})}key(t){if(this.ignored(t)||n.has(t.key))return;if(t.altKey&&"KeyH"===t.code)return t.preventDefault(),this.hover();if(t.altKey&&"KeyN"===t.code)return t.preventDefault(),this.nextStep();const e=t.ctrlKey||t.metaKey||t.altKey&&1===t.key.length;if(!e&&!r.has(t.key))return;if(!e&&["Backspace","Delete","ArrowLeft","ArrowRight","Home","End"].includes(t.key)&&t.target.matches?.("input, textarea, [contenteditable]"))return;const s=[t.ctrlKey&&"Control",t.metaKey&&"Meta",t.altKey&&"Alt",t.shiftKey&&e&&"Shift"].filter(Boolean),i=1===t.key.length?t.key.toUpperCase():t.key;this.push({do:"key",key:[...s,i].join("+")})}hover(){const s=document.elementFromPoint(this.pointer.x,this.pointer.y);if(!s||s.closest(e))return;const i=this.claimedBy(s);if(i){const t=i.hover?.(s,this.pointer.x,this.pointer.y);return void(t&&this.push(t))}const r=this.targets.targetElement(s);if(!r)return;const n=r.matches("canvas, video")||r.getBoundingClientRect().width>160;this.push({do:"hover",target:this.targets.describe(r),...n?{at:t(r,this.pointer.x,this.pointer.y)}:{}})}nextStep(){this.recorders.forEach(t=>t.flush?.()),this.steps.push({say:{},actions:[]}),this.stepStarts.push(performance.now()-this.since),this.update({step:this.steps.length-1,caption:""})}say(t){this.current.say[this.language]=t,this.update({caption:t})}stop(t=!1){this.recorders.forEach(t=>{t.flush?.(),t.stop()}),this.stops.splice(0).forEach(t=>t());const e=this.steps.map((t,e)=>({step:t,start:this.stepStarts[e]})).filter(({step:e})=>t||e.actions.length>0||Object.values(e.say).some(Boolean));return{steps:e.map(t=>t.step),stepStarts:e.map(t=>t.start),since:this.since}}}
@@ -0,0 +1,51 @@
1
+ import type { Language } from '../model/Demo';
2
+ import { SpeechSettings } from '../speech/Speech';
3
+ import type { MusicTrack } from '../speech/Music';
4
+ import type { Transcriber } from '../speech/Transcribe';
5
+ /** A video's shape: landscape, portrait (phones, stories), square (feeds). */
6
+ export type Aspect = '16:9' | '9:16' | '1:1';
7
+ /** How demos play, film and record here: kept in this browser, per app. */
8
+ export type DemoSettings = {
9
+ speech: SpeechSettings;
10
+ /** The narration's language: the page's, unless chosen. */
11
+ language: 'page' | Language;
12
+ subtitles: boolean;
13
+ /** After each step, wait for the presenter to continue. */
14
+ waitForPresenter: boolean;
15
+ /** Playing from a step, earlier steps' actions first, quickly: the app where the step expects it. */
16
+ catchUp: boolean;
17
+ /** Recording, the microphone too: what is said becomes the narration. */
18
+ microphone: boolean;
19
+ /** Recording, the tab filmed too. */
20
+ filmRecording: boolean;
21
+ transcriber: Transcriber;
22
+ whisperModel: 'tiny' | 'base' | 'small';
23
+ /**
24
+ * A music bed under the narration: a track the engine composes, or a file of one's own - kept
25
+ * with the demos (`Store.asset('music')`), `name` its name.
26
+ */
27
+ music: {
28
+ on: boolean;
29
+ volume: number;
30
+ track: MusicTrack | 'file';
31
+ name?: string;
32
+ };
33
+ /**
34
+ * Videos: frames a second, megabits a second, and their size - exactly `lines` on the short side
35
+ * in `aspect`, the tab fitted in it (bars) or filling it (edges cut) - or the tab's own (lines 0).
36
+ */
37
+ film: {
38
+ frameRate: 30 | 60;
39
+ bitrate: number;
40
+ lines: number;
41
+ aspect: Aspect;
42
+ fit: 'fit' | 'fill';
43
+ };
44
+ /** Expo booth: after a visitor's last touch, ms till the loop plays again. */
45
+ loopIdle: number;
46
+ /** A demo's narration pack, where it has one, before any voice: made once, played by everyone. */
47
+ usePacks: boolean;
48
+ };
49
+ export declare const DEFAULT_SETTINGS: DemoSettings;
50
+ export declare function loadSettings(key: string): DemoSettings;
51
+ export declare function saveSettings(key: string, settings: DemoSettings): void;
@@ -0,0 +1 @@
1
+ import{DEFAULT_SPEECH as e}from"../speech/Speech.js";export const DEFAULT_SETTINGS={speech:e,language:"page",subtitles:!0,waitForPresenter:!1,catchUp:!0,microphone:!1,filmRecording:!1,transcriber:"whisper",whisperModel:"base",music:{on:!1,volume:.18,track:"calm"},film:{frameRate:30,bitrate:8,lines:1080,aspect:"16:9",fit:"fit"},loopIdle:3e4,usePacks:!0};export function loadSettings(t){try{const s=JSON.parse(localStorage.getItem(t)??"{}");return{...DEFAULT_SETTINGS,...s,speech:{...e,...s.speech,elevenlabs:{...e.elevenlabs,...s.speech?.elevenlabs}},music:{...DEFAULT_SETTINGS.music,...s.music?.name?{track:"file"}:{},...s.music},film:{...DEFAULT_SETTINGS.film,...s.film}}}catch{return DEFAULT_SETTINGS}}export function saveSettings(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch{}}
package/index.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ export * from './model/Demo';
2
+ export * from './model/Timing';
3
+ export * from './model/Subtitles';
4
+ export * from './model/Validate';
5
+ export * from './engine/DemoEngine';
6
+ export * from './engine/Player';
7
+ export * from './engine/Recorder';
8
+ export * from './engine/Plugin';
9
+ export * from './engine/Settings';
10
+ export * from './page/Targets';
11
+ export * from './page/Input';
12
+ export * from './page/Overlay';
13
+ export * from './speech/Speech';
14
+ export * from './speech/Transcribe';
15
+ export * from './speech/Pack';
16
+ export * from './speech/Music';
17
+ export * from './store/Zip';
18
+ export * from './video/Film';
19
+ export * from './store/Store';
20
+ export * from './store/Share';
21
+ export * from './agent/Agent';
22
+ export { GUIDE } from './agent/Guide';
23
+ export { DemoLibrary, Library, Narration, Recording, Shadow } from './ui/Library';
24
+ export { Studio } from './ui/Studio';
25
+ export { Timeline } from './ui/Timeline';
26
+ export { useEngine, useDemos } from './ui/Hooks';
27
+ export { UI_CSS } from './ui/Styles';
package/index.js ADDED
@@ -0,0 +1 @@
1
+ export*from"./model/Demo.js";export*from"./model/Timing.js";export*from"./model/Subtitles.js";export*from"./model/Validate.js";export*from"./engine/DemoEngine.js";export*from"./engine/Player.js";export*from"./engine/Recorder.js";export*from"./engine/Plugin.js";export*from"./engine/Settings.js";export*from"./page/Targets.js";export*from"./page/Input.js";export*from"./page/Overlay.js";export*from"./speech/Speech.js";export*from"./speech/Transcribe.js";export*from"./speech/Pack.js";export*from"./speech/Music.js";export*from"./store/Zip.js";export*from"./video/Film.js";export*from"./store/Store.js";export*from"./store/Share.js";export*from"./agent/Agent.js";export{GUIDE}from"./agent/Guide.js";export{DemoLibrary,Library,Narration,Recording,Shadow}from"./ui/Library.js";export{Studio}from"./ui/Studio.js";export{Timeline}from"./ui/Timeline.js";export{useEngine,useDemos}from"./ui/Hooks.js";export{UI_CSS}from"./ui/Styles.js";
@@ -0,0 +1,201 @@
1
+ /**
2
+ * A demo: steps, each a narration - spoken and subtitled - while its actions play, one after the
3
+ * other. Kept as `<id>.demo.json`. Actions find what they act on as a person would point at it: by
4
+ * what it shows (`DemoTarget`), not by where it is.
5
+ */
6
+ export type Demo = {
7
+ id: string;
8
+ title: string;
9
+ description?: string;
10
+ /** Where the app must be to play it, in the app's own terms (`DemoEngineOptions.start`). */
11
+ start?: Record<string, string>;
12
+ steps: DemoStep[];
13
+ /**
14
+ * Done after it - when it ends, or is stopped - quickly and unseen, so the app is as it found it
15
+ * and the demo plays again: filters cleared, what it opened closed, what it changed changed back.
16
+ */
17
+ cleanup?: DemoAction[];
18
+ };
19
+ /** A language code, as the app names its languages: 'en', 'de'. */
20
+ export type Language = string;
21
+ export type DemoStep = {
22
+ /** A short name, for the editor and the timeline. */
23
+ title?: string;
24
+ /** The narration, per language: spoken a sentence at a time, each a subtitle. */
25
+ say: Partial<Record<Language, string>>;
26
+ actions: DemoAction[];
27
+ /** ms to hold once narration and actions are done. */
28
+ hold?: number;
29
+ /** Wait for the presenter (→, Enter or Continue) once the step is done. */
30
+ pause?: boolean;
31
+ };
32
+ /**
33
+ * The `index`th element matching `css` whose label (`labelOf`) is the locale `key`'s text in the
34
+ * page's language, or else `text`. In labels, digits match any, case and spacing do not count.
35
+ */
36
+ export type DemoTarget = {
37
+ css: string;
38
+ key?: string;
39
+ text?: string;
40
+ index?: number;
41
+ };
42
+ /** Where in the element, as fractions of its box: a chart's bar, a slider's end. Default the middle. */
43
+ export type Fraction = [x: number, y: number];
44
+ export type ActionBase = {
45
+ /** ms before it starts, 800 by default; after `cue`, if it has one. */
46
+ wait?: number;
47
+ /** Starts no earlier than the step's sentence of this index (0-based) is spoken. */
48
+ cue?: number;
49
+ };
50
+ /** Keys held while clicking or dragging. */
51
+ export type Modifiers = {
52
+ shift?: boolean;
53
+ ctrl?: boolean;
54
+ alt?: boolean;
55
+ meta?: boolean;
56
+ };
57
+ export type ClickAction = ActionBase & Modifiers & {
58
+ do: 'click';
59
+ target: DemoTarget;
60
+ at?: Fraction;
61
+ double?: boolean;
62
+ right?: boolean;
63
+ };
64
+ export type HoverAction = ActionBase & {
65
+ do: 'hover';
66
+ target: DemoTarget;
67
+ at?: Fraction;
68
+ };
69
+ /** Typed a letter at a time; replaces what the field held. */
70
+ export type TypeAction = ActionBase & {
71
+ do: 'type';
72
+ target: DemoTarget;
73
+ text: string;
74
+ };
75
+ /** A key, or a chord: 'Escape', 'Enter', 'Control+K'. To what has focus, or to `target`. */
76
+ export type KeyAction = ActionBase & {
77
+ do: 'key';
78
+ key: string;
79
+ target?: DemoTarget;
80
+ };
81
+ /** A native `<select>`'s option, by its text or value. */
82
+ export type SelectAction = ActionBase & {
83
+ do: 'select';
84
+ target: DemoTarget;
85
+ option: string;
86
+ };
87
+ /** Pressed at `target` (`at`), moved to `to` - another target, or a point of the same one - and let go. */
88
+ export type DragAction = ActionBase & Modifiers & {
89
+ do: 'drag';
90
+ target: DemoTarget;
91
+ at?: Fraction;
92
+ to: {
93
+ target?: DemoTarget;
94
+ at?: Fraction;
95
+ };
96
+ };
97
+ /** Into view (`target`), or the page or `target` scrolled by pixels. */
98
+ export type ScrollAction = ActionBase & {
99
+ do: 'scroll';
100
+ target?: DemoTarget;
101
+ by?: [x: number, y: number];
102
+ };
103
+ /** Until `target` shows (or, `gone`, no longer does): what loads takes its time. */
104
+ export type WaitForAction = ActionBase & {
105
+ do: 'waitFor';
106
+ target: DemoTarget;
107
+ gone?: boolean;
108
+ timeout?: number;
109
+ };
110
+ /** How long a presentation effect stays: ms, else to the end of its step. */
111
+ export type Lasting = {
112
+ for?: number;
113
+ };
114
+ /** Dims everything but the target. */
115
+ export type SpotlightAction = ActionBase & Lasting & {
116
+ do: 'spotlight';
117
+ target: DemoTarget;
118
+ text?: string;
119
+ padding?: number;
120
+ };
121
+ /** A ring around the target; `shape` 'circle' for round things. */
122
+ export type RingAction = ActionBase & Lasting & {
123
+ do: 'ring';
124
+ target: DemoTarget;
125
+ text?: string;
126
+ color?: string;
127
+ shape?: 'box' | 'circle';
128
+ padding?: number;
129
+ };
130
+ /** An arrow pointing at the target, from a side, with an optional label. */
131
+ export type ArrowAction = ActionBase & Lasting & {
132
+ do: 'arrow';
133
+ target: DemoTarget;
134
+ text?: string;
135
+ from?: Side;
136
+ color?: string;
137
+ };
138
+ /** A note: at the target, or in a corner of the screen. */
139
+ export type CalloutAction = ActionBase & Lasting & {
140
+ do: 'callout';
141
+ text: string;
142
+ target?: DemoTarget;
143
+ side?: Side;
144
+ corner?: Corner;
145
+ };
146
+ /** Blurs the target: names, addresses, anything not to show. */
147
+ export type BlurAction = ActionBase & Lasting & {
148
+ do: 'blur';
149
+ target: DemoTarget;
150
+ };
151
+ /** A full-screen card: a title to open, a chapter, an end. */
152
+ export type CardAction = ActionBase & Lasting & {
153
+ do: 'card';
154
+ title: string;
155
+ text?: string;
156
+ };
157
+ /** Magnifies the page around the target. */
158
+ export type ZoomAction = ActionBase & Lasting & {
159
+ do: 'zoom';
160
+ target: DemoTarget;
161
+ scale?: number;
162
+ };
163
+ /** Takes down what shows: highlights, notes, cards, the zoom. */
164
+ export type ClearAction = ActionBase & {
165
+ do: 'clear';
166
+ };
167
+ export type Side = 'top' | 'right' | 'bottom' | 'left';
168
+ export type Corner = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';
169
+ export type InteractAction = ClickAction | HoverAction | TypeAction | KeyAction | SelectAction | DragAction | ScrollAction | WaitForAction;
170
+ export type PresentAction = SpotlightAction | RingAction | ArrowAction | CalloutAction | BlurAction | CardAction | ZoomAction | ClearAction;
171
+ export type BuiltInAction = InteractAction | PresentAction;
172
+ /** An action a plugin plays (`DemoPlugin.actions`): `do` is its name, the rest its own. */
173
+ export type PluginAction = ActionBase & {
174
+ do: string;
175
+ [detail: string]: unknown;
176
+ };
177
+ export type DemoAction = BuiltInAction | PluginAction;
178
+ export declare const INTERACT_KINDS: readonly ["click", "hover", "type", "key", "select", "drag", "scroll", "waitFor"];
179
+ export declare const PRESENT_KINDS: readonly ["spotlight", "ring", "arrow", "callout", "blur", "card", "zoom", "clear"];
180
+ export declare const BUILT_IN_KINDS: readonly string[];
181
+ export declare function isBuiltIn(action: DemoAction): action is BuiltInAction;
182
+ export declare function isPresent(action: DemoAction): action is PresentAction;
183
+ /** Default ms before an action. */
184
+ export declare const DEFAULT_WAIT = 800;
185
+ /** The actions that take a target, and their targets; `drag` may have a second. */
186
+ export declare function targetsOf(action: DemoAction): DemoTarget[];
187
+ export declare function isTarget(value: unknown): value is DemoTarget;
188
+ /** A step's narration in `language`, else in the first language it has. */
189
+ export declare function sayOf(step: DemoStep, language: Language): string;
190
+ /** The languages a demo is narrated in, most used first. */
191
+ export declare function languagesOf(demo: Demo): Language[];
192
+ /** One sentence each, as they are spoken and subtitled. Ended by a stop and a space: "Ing.Plus" is one word. */
193
+ export declare function sentences(text: string): string[];
194
+ /** A scenario, for people: title, description, each step's narration. */
195
+ export declare function scenarioOf(demo: Demo, language: Language): string;
196
+ /** A new, empty demo. */
197
+ export declare function newDemo(title?: string, start?: Record<string, string>): Demo;
198
+ /** A file-name-safe id from a title, unique enough to keep next to others. */
199
+ export declare function idFrom(title: string): string;
200
+ /** A deep copy, through JSON: demos are plain data. */
201
+ export declare function copyOf<T>(value: T): T;
package/model/Demo.js ADDED
@@ -0,0 +1 @@
1
+ export const INTERACT_KINDS=["click","hover","type","key","select","drag","scroll","waitFor"];export const PRESENT_KINDS=["spotlight","ring","arrow","callout","blur","card","zoom","clear"];export const BUILT_IN_KINDS=[...INTERACT_KINDS,...PRESENT_KINDS];export function isBuiltIn(t){return BUILT_IN_KINDS.includes(t.do)}export function isPresent(t){return PRESENT_KINDS.includes(t.do)}export const DEFAULT_WAIT=800;export function targetsOf(t){const e=[],r=t.target;isTarget(r)&&e.push(r);const o=t.to?.target;return isTarget(o)&&e.push(o),e}export function isTarget(t){return"object"==typeof t&&null!==t&&"string"==typeof t.css}export function sayOf(t,e){return t.say[e]??Object.values(t.say).find(t=>t)??""}export function languagesOf(t){const e=new Map;return t.steps.forEach(t=>Object.entries(t.say).forEach(([t,r])=>{r&&e.set(t,(e.get(t)??0)+1)})),[...e.entries()].sort((t,e)=>e[1]-t[1]).map(([t])=>t)}export function sentences(t){return t.split(/(?<=[.!?…]["')\]]*)\s+/).map(t=>t.trim()).filter(Boolean)}export function scenarioOf(t,e){return[`# ${t.title}`,"",...t.description?[t.description,""]:[],...t.steps.map((t,r)=>`${r+1}. ${t.title?`**${t.title}.** `:""}${sayOf(t,e)||"…"}`),""].join("\n")}export function newDemo(t="New demo",e){return{id:idFrom(t),title:t,description:"",...e?{start:e}:{},steps:[{say:{},actions:[]}]}}export function idFrom(t){return`${t.toLowerCase().normalize("NFKD").replace(/[^\w\s-]/g,"").trim().replace(/[\s_]+/g,"-").slice(0,40)||"demo"}-${Math.random().toString(36).slice(2,6)}`}export function copyOf(t){return JSON.parse(JSON.stringify(t))}
@@ -0,0 +1,12 @@
1
+ /** A subtitle: ms from the start, and its text. */
2
+ export type Subtitle = {
3
+ start: number;
4
+ end: number;
5
+ text: string;
6
+ };
7
+ /** WebVTT: for players, browsers and editors. */
8
+ export declare function toVtt(cues: Subtitle[]): string;
9
+ /** SubRip: for video editors and players that read no WebVTT. */
10
+ export declare function toSrt(cues: Subtitle[]): string;
11
+ /** Subtitles back from WebVTT or SubRip. */
12
+ export declare function parseSubtitles(text: string): Subtitle[];
@@ -0,0 +1 @@
1
+ function t(t,n){const e=Math.max(0,Math.round(t)),r=Math.floor(e/36e5),o=Math.floor(e/6e4)%60,i=Math.floor(e/1e3)%60,s=(t,n=2)=>String(t).padStart(n,"0");return`${s(r)}:${s(o)}:${s(i)}${n}${s(e%1e3,3)}`}export function toVtt(n){return["WEBVTT","",...n.map(n=>`${t(n.start,".")} --\x3e ${t(n.end,".")}\n${n.text}\n`)].join("\n")}export function toSrt(n){return n.map((n,e)=>`${e+1}\n${t(n.start,",")} --\x3e ${t(n.end,",")}\n${n.text}\n`).join("\n")}export function parseSubtitles(t){const n=t=>{const[n,e,r]=3===t.trim().replace(",",".").split(":").length?t.trim().replace(",",".").split(":"):["0",...t.trim().replace(",",".").split(":")];return Math.round(1e3*(3600*Number(n)+60*Number(e)+Number(r)))},e=[];for(const r of t.replace(/\r/g,"").split(/\n\n+/)){const t=r.split("\n"),o=t.findIndex(t=>t.includes("--\x3e"));if(o<0)continue;const[i,s]=t[o].split("--\x3e");e.push({start:n(i),end:n(s.trim().split(/\s/)[0]),text:t.slice(o+1).join("\n").trim()})}return e}
@@ -0,0 +1,45 @@
1
+ import { Demo, DemoAction, Language } from './Demo';
2
+ /**
3
+ * When what happens in a demo, ms from its start: estimated before it plays (`estimate`), measured
4
+ * as it plays (`PlayResult.timing`). The editor's timeline draws it; the subtitles are its cues.
5
+ */
6
+ export type Timing = {
7
+ duration: number;
8
+ steps: {
9
+ step: number;
10
+ start: number;
11
+ end: number;
12
+ }[];
13
+ /** Sentences: subtitles. */
14
+ cues: Cue[];
15
+ /** Interactions and presentation effects, as they start and end; an effect lasts (`Lasting`). */
16
+ actions: {
17
+ step: number;
18
+ index: number;
19
+ start: number;
20
+ end: number;
21
+ error?: string;
22
+ }[];
23
+ };
24
+ export type Cue = {
25
+ step: number;
26
+ start: number;
27
+ end: number;
28
+ text: string;
29
+ };
30
+ /** ms to read a sentence aloud, without a voice: also how long its subtitle shows. */
31
+ export declare function readingTime(text: string): number;
32
+ /** ms an action takes once started, about. `own`: a plugin's estimate for its actions. */
33
+ export declare function actionTime(action: DemoAction, own?: (action: DemoAction) => number | undefined): number;
34
+ export type EstimateOptions = {
35
+ language: Language;
36
+ /** ms a sentence takes to say: its voice's, once made; else `readingTime`. */
37
+ sayTime?: (text: string) => number | undefined;
38
+ actionTime?: (action: DemoAction) => number | undefined;
39
+ };
40
+ /** The timing a demo plays with, about: as the player schedules it. */
41
+ export declare function estimate(demo: Demo, options: EstimateOptions): Timing;
42
+ /** The step playing at `time`, or the last. */
43
+ export declare function stepAt(timing: Timing, time: number): number;
44
+ /** As `m:ss`, or `m:ss.s` with tenths. */
45
+ export declare function clock(ms: number, tenths?: boolean): string;
@@ -0,0 +1 @@
1
+ import{DEFAULT_WAIT as t,isPresent as e,sayOf as s,sentences as r}from"./Demo.js";export function readingTime(t){return 500+55*t.length}export function actionTime(t,s){switch(t.do){case"click":case"hover":case"select":case"scroll":return 600;case"type":return 600+60*String(t.text??"").length;case"key":return 150;case"drag":return 1400;case"waitFor":return 300;case"zoom":return 700;default:return e(t)?0:s?.(t)??1e3}}export function estimate(a,n){const o={duration:0,steps:[],cues:[],actions:[]};let c=0;return a.steps.forEach((a,i)=>{const u=c;let p=u;const d=[];r(s(a,n.language)).forEach(t=>{d.push(p);const e=p+(n.sayTime?.(t)??readingTime(t));o.cues.push({step:i,start:p,end:e,text:t}),p=e});let h=u;const f=[];a.actions.forEach((s,r)=>{void 0!==s.cue&&(h=Math.max(h,d[s.cue]??p));const a=h+(s.wait??t);h=a+actionTime(s,n.actionTime),e(s)&&"clear"!==s.do?f.push({index:r,start:a,for:s.for}):o.actions.push({step:i,index:r,start:a,end:h}),"clear"===s.do&&f.splice(0).forEach(t=>o.actions.push({step:i,index:t.index,start:t.start,end:a}))});const l=Math.max(p,h)+(a.hold??0);f.forEach(t=>o.actions.push({step:i,index:t.index,start:t.start,end:void 0===t.for?l:Math.min(l,t.start+t.for)})),o.steps.push({step:i,start:u,end:l}),c=l}),o.actions.sort((t,e)=>t.start-e.start),o.duration=c,o}export function stepAt(t,e){const s=t.steps.find(t=>e<t.end);return s?.step??Math.max(0,t.steps.length-1)}export function clock(t,e=!1){const s=Math.max(0,t)/1e3,r=Math.floor(s/60),a=s-60*r;return`${r}:${e?a.toFixed(1).padStart(4,"0"):String(Math.floor(a)).padStart(2,"0")}`}
@@ -0,0 +1,16 @@
1
+ import { Demo } from './Demo';
2
+ /** A problem with a demo, where it is: `steps[2].actions[0].target`. */
3
+ export type Problem = {
4
+ path: string;
5
+ message: string;
6
+ };
7
+ /**
8
+ * What is wrong with it as a demo, none if nothing: its shape, not whether its targets are on the
9
+ * page (`DemoEngine.check` plays it for that). `kinds`: the actions plugins add.
10
+ */
11
+ export declare function validate(value: unknown, kinds?: readonly string[]): Problem[];
12
+ /** The demo in `text`, or why not. */
13
+ export declare function parseDemo(text: string, kinds?: readonly string[]): {
14
+ demo?: Demo;
15
+ problems: Problem[];
16
+ };
@@ -0,0 +1 @@
1
+ import{BUILT_IN_KINDS as t,isTarget as e}from"./Demo.js";const o={click:["target"],hover:["target"],type:["target","text"],key:["key"],select:["target","option"],drag:["target","to"],scroll:[],waitFor:["target"],spotlight:["target"],ring:["target"],arrow:["target"],callout:["text"],blur:["target"],card:["title"],zoom:["target"],clear:[]},r=new Set(["target"]),n=["top","right","bottom","left"],a=["top-left","top-right","bottom-left","bottom-right"];export function validate(i,c=[]){const d=[],f=(t,e)=>d.push({path:t,message:e});if("object"!=typeof i||null===i)return[{path:"",message:"not an object"}];const g=i;if("string"==typeof g.id&&g.id||f("id","needs a string"),"string"==typeof g.title&&g.title||f("title","needs a string"),void 0!==g.description&&"string"!=typeof g.description&&f("description","is a string"),void 0===g.start||"object"==typeof g.start&&!Object.values(g.start).some(t=>"string"!=typeof t)||f("start","is an object of strings"),!Array.isArray(g.steps))return f("steps","needs an array"),d;const l=[...t,...c];return g.steps.forEach((t,e)=>{const o=`steps[${e}]`;return"object"!=typeof t||null===t?f(o,"not an object"):("object"!=typeof t.say||null===t.say||Array.isArray(t.say)?f(`${o}.say`,"needs an object: language → narration, {} for none"):Object.entries(t.say).forEach(([t,e])=>{"string"!=typeof e&&f(`${o}.say.${t}`,"is a string")}),Array.isArray(t.actions)?void t.actions.forEach((t,e)=>p(t,`${o}.actions[${e}]`)):f(`${o}.actions`,"needs an array, [] for none"))}),void 0!==g.cleanup&&(Array.isArray(g.cleanup)?g.cleanup.forEach((t,e)=>p(t,`cleanup[${e}]`)):f("cleanup","needs an array of actions")),d;function p(t,i){if("object"!=typeof t||null===t)return f(i,"not an object");if(!l.includes(t.do))return f(`${i}.do`,`unknown action "${t.do}": one of ${l.join(", ")}`);for(const n of o[t.do]??[]){const o=t[n];void 0===o||""===o&&"text"!==n?f(`${i}.${n}`,"is required"):r.has(n)&&!e(o)&&f(`${i}.${n}`,"needs { css, text?, key?, index? }")}void 0!==t.wait&&("number"!=typeof t.wait||t.wait<0)&&f(`${i}.wait`,"is ms, 0 or more"),void 0!==t.cue&&(!Number.isInteger(t.cue)||t.cue<0)&&f(`${i}.cue`,"is a sentence's index, 0 or more");const c=t;if(void 0===c.at||s(c.at)||f(`${i}.at`,"is [x, y], fractions of the box"),void 0===c.from||n.includes(c.from)||f(`${i}.from`,`one of ${n.join(", ")}`),void 0===c.side||n.includes(c.side)||f(`${i}.side`,`one of ${n.join(", ")}`),void 0===c.corner||a.includes(c.corner)||f(`${i}.corner`,`one of ${a.join(", ")}`),"drag"===t.do){const t=c.to;t&&void 0!==t.target&&!e(t.target)&&f(`${i}.to.target`,"needs { css, text?, key?, index? }"),t&&void 0!==t.at&&!s(t.at)&&f(`${i}.to.at`,"is [x, y], fractions of the box"),t&&void 0===t.target&&void 0===t.at&&f(`${i}.to`,"needs a target, an at, or both")}}}function s(t){return Array.isArray(t)&&2===t.length&&t.every(t=>"number"==typeof t&&Number.isFinite(t))}export function parseDemo(t,e=[]){let o;try{o=JSON.parse(t)}catch(t){return{problems:[{path:"",message:t.message}]}}const r=validate(o,e);return r.length?{problems:r}:{demo:o,problems:r}}
package/package.json CHANGED
@@ -1,6 +1,67 @@
1
1
  {
2
2
  "name": "@protomaze/demo-engine",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Protomaze Demo Engine: record, edit, narrate, play and film demos of a web app, in the browser",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/protomaze/demo-engine.git"
8
+ },
9
+ "homepage": "https://github.com/protomaze/demo-engine#readme",
10
+ "main": "index.js",
11
+ "types": "index.d.ts",
12
+ "files": [
13
+ "**/*.js",
14
+ "**/*.d.ts",
15
+ "AGENTS.md"
16
+ ],
17
+ "scripts": {
18
+ "dev": "webpack serve --mode development",
19
+ "check": "tsc -p tsconfig.json --noEmit",
20
+ "test": "rimraf .test-build && tsc -p tsconfig.test.json && node --test .test-build/test/",
21
+ "compile": "node dev/guide.js && tsc -p tsconfig.build.json && node dev/fix_extensions.js && node dev/copy_files.js && node dev/minify_files.js",
22
+ "deploy": "rimraf build && npm run compile && cd build && npm publish --access public",
23
+ "build": "webpack --mode production && npm run deploy",
24
+ "release": "npm version patch --no-git-tag-version && npm run build",
25
+ "release:minor": "npm version minor --no-git-tag-version && npm run build",
26
+ "release:major": "npm version major --no-git-tag-version && npm run build"
27
+ },
28
+ "keywords": [
29
+ "demo",
30
+ "walkthrough",
31
+ "screen recording",
32
+ "text to speech",
33
+ "subtitles",
34
+ "typescript"
35
+ ],
36
+ "author": "Tom Crauwels",
37
+ "dependencies": {
38
+ "@protomaze/time": "^1.16.1"
39
+ },
40
+ "peerDependencies": {
41
+ "react": "^18.2.0",
42
+ "react-dom": "^18.2.0"
43
+ },
44
+ "devDependencies": {
45
+ "@types/node": "^20.17.0",
46
+ "@types/react": "18.0.34",
47
+ "@types/react-dom": "18.0.11",
48
+ "@types/three": "0.178.0",
49
+ "copy-webpack-plugin": "^14.0.0",
50
+ "css-loader": "^6.2.0",
51
+ "html-webpack-plugin": "^5.3.2",
52
+ "react": "18.2.0",
53
+ "react-dom": "18.2.0",
54
+ "rimraf": "^6.1.3",
55
+ "style-loader": "^3.2.1",
56
+ "terser": "^5.43.1",
57
+ "ts-loader": "^9.6.2",
58
+ "typescript": "^6.0.3",
59
+ "webpack": "^5.64.4",
60
+ "webpack-cli": "^6.0.1",
61
+ "webpack-dev-server": "^5.2.2"
62
+ },
63
+ "overrides": {
64
+ "@types/scheduler": "< 0.23.0"
65
+ },
66
+ "type": "module"
67
+ }
@@ -0,0 +1,67 @@
1
+ import type { Fraction, Modifiers } from '../model/Demo';
2
+ /** The stand-in pointer the viewer sees: the overlay's. */
3
+ export type Cursor = {
4
+ move(x: number, y: number): void;
5
+ press(down: boolean): void;
6
+ position(): {
7
+ x: number;
8
+ y: number;
9
+ } | undefined;
10
+ };
11
+ /** The next frame; in a background tab, where frames stop, a moment later. */
12
+ export declare function nextFrame(): Promise<void>;
13
+ type Point = {
14
+ x: number;
15
+ y: number;
16
+ };
17
+ /**
18
+ * Acts on the page as a person would, with events the app hears as its own: the pointer moves
19
+ * there, over what it passes, presses, types a letter at a time. `speed` divides every delay: a
20
+ * check runs fast.
21
+ */
22
+ export declare class Hand {
23
+ private cursor;
24
+ private speed;
25
+ private hovered;
26
+ constructor(cursor: Cursor, speed?: () => number);
27
+ private wait;
28
+ /** The stand-in pointer, moved there along an eased path; longer ways take longer. */
29
+ moveTo(x: number, y: number): Promise<void>;
30
+ /** What a real pointer there would hit: the deepest element there, if it is `within`'s. */
31
+ hit(x: number, y: number, within?: Element): Element;
32
+ /** Over it, and off what it was over: React's enter and leave follow over and out. */
33
+ over(element: Element, x: number, y: number): void;
34
+ /** Off what it is over. */
35
+ leave(next?: Element): void;
36
+ /** Pointed at: moved there and over it. */
37
+ point(element: Element, at: Point): Promise<void>;
38
+ click(element: Element, at: Point, { double, right, ...modifiers }?: Modifiers & {
39
+ double?: boolean;
40
+ right?: boolean;
41
+ }): Promise<void>;
42
+ /** Pressed at `from` in `element`, moved to `to`, let go: sliders, maps, what moves with a pointer. */
43
+ drag(element: Element, from: Point, to: Point, modifiers?: Modifiers): Promise<void>;
44
+ /** A native range input: its value follows the pointer, as the browser would set it. */
45
+ private slide;
46
+ /** Typed a letter at a time, as React and the page hear it; replaces what was there. */
47
+ type(element: Element, text: string): Promise<void>;
48
+ /** A key or chord - 'Escape', 'Control+K' - to `element`, else to what has focus. Enter in a form's field submits it. */
49
+ key(chord: string, element?: Element): void;
50
+ /** A native select's option, by its text or value: the pointer goes there, the option is chosen. */
51
+ select(select: HTMLSelectElement, option: string, at: Point): Promise<void>;
52
+ /** Into view, or by pixels: smooth, as a wheel would. */
53
+ scroll(element: Element | undefined, by?: [number, number]): Promise<void>;
54
+ /** Off everything, as it was before playing. */
55
+ reset(): void;
56
+ }
57
+ /** A point of an element: `at` fractions of its box. */
58
+ export declare function at(element: Element, fraction?: Fraction): Point;
59
+ /** 'Control+Shift+P' as its key and the keys held. */
60
+ export declare function parseChord(chord: string): {
61
+ key: string;
62
+ ctrlKey: boolean;
63
+ shiftKey: boolean;
64
+ altKey: boolean;
65
+ metaKey: boolean;
66
+ };
67
+ export {};
package/page/Input.js ADDED
@@ -0,0 +1 @@
1
+ export function nextFrame(){return new Promise(t=>{const e=()=>{cancelAnimationFrame(n),clearTimeout(o),t()},n=requestAnimationFrame(e),o=setTimeout(e,40)})}export class Hand{constructor(t,e=()=>1){this.cursor=t,this.speed=e}wait(t){return(t=>new Promise(e=>setTimeout(e,t)))(t/this.speed())}async moveTo(t,e){const n=this.cursor.position()??{x:innerWidth/2,y:innerHeight/2},o=Math.hypot(t-n.x,e-n.y),s=Math.min(900,250+.6*o)/this.speed(),i=performance.now();for(;;){const o=Math.min(1,(performance.now()-i)/(s||1)),r=o<.5?4*o*o*o:1-Math.pow(-2*o+2,3)/2;if(this.cursor.move(n.x+(t-n.x)*r,n.y+(e-n.y)*r),o>=1)break;await nextFrame()}}hit(t,e,n){const o=document.elementFromPoint(t,e);return n?o&&n.contains(o)?o:n:o??document.body}over(t,n,o){if(this.hovered!==t){const s=this.hovered;this.leave(t),e(t,"pointerover",n,o,{relatedTarget:s??null}),e(t,"mouseover",n,o,{relatedTarget:s??null});const i=[];for(let e=t;e&&(!s||!e.contains(s));e=e.parentElement)i.unshift(e);i.forEach(t=>{e(t,"pointerenter",n,o,{bubbles:!1,relatedTarget:s??null}),e(t,"mouseenter",n,o,{bubbles:!1,relatedTarget:s??null})}),this.hovered=t}e(t,"pointermove",n,o),e(t,"mousemove",n,o)}leave(t){const n=this.hovered;if(n){e(n,"pointerout",0,0,{relatedTarget:t??null}),e(n,"mouseout",0,0,{relatedTarget:t??null});for(let o=n;o&&!o.contains(t??null);o=o.parentElement)e(o,"pointerleave",0,0,{bubbles:!1,relatedTarget:t??null}),e(o,"mouseleave",0,0,{bubbles:!1,relatedTarget:t??null});this.hovered=void 0}}async point(t,e){await this.moveTo(e.x,e.y),this.over(this.hit(e.x,e.y,t),e.x,e.y)}async click(o,s,{double:i=!1,right:r=!1,...a}={}){await this.point(o,s);const c=this.hit(s.x,s.y,o),l=t(a),u=r?2:0;for(let t=0;t<(i?2:1);t++)this.cursor.press(!0),e(c,"pointerdown",s.x,s.y,{button:u,buttons:r?2:1,...l}),e(c,"mousedown",s.x,s.y,{button:u,buttons:r?2:1,...l,detail:t+1}),n(c),await this.wait(60),e(c,"pointerup",s.x,s.y,{button:u,buttons:0,...l}),e(c,"mouseup",s.x,s.y,{button:u,buttons:0,...l,detail:t+1}),r?e(c,"contextmenu",s.x,s.y,{button:u,buttons:0,...l}):e(c,"click",s.x,s.y,{button:u,buttons:0,...l,detail:t+1}),setTimeout(()=>this.cursor.press(!1),160/this.speed()),i&&await this.wait(80);i&&e(c,"dblclick",s.x,s.y,{button:u,buttons:0,...l,detail:2})}async drag(o,s,i,r={}){if(o instanceof HTMLInputElement&&"range"===o.type)return this.slide(o,s,i);await this.point(o,s);const a=t(r),c=this.hit(s.x,s.y,o);this.cursor.press(!0),e(c,"pointerdown",s.x,s.y,{button:0,buttons:1,...a}),e(c,"mousedown",s.x,s.y,{button:0,buttons:1,...a}),n(c);const l=Math.max(8,Math.round(Math.hypot(i.x-s.x,i.y-s.y)/12));for(let t=1;t<=l;t++){const n=t/l,o=s.x+(i.x-s.x)*n,r=s.y+(i.y-s.y)*n;this.cursor.move(o,r);const u=document.elementFromPoint(o,r)??c;e(u,"pointermove",o,r,{buttons:1,...a}),e(u,"mousemove",o,r,{buttons:1,...a}),await this.wait(16)}const u=document.elementFromPoint(i.x,i.y)??c;e(u,"pointerup",i.x,i.y,{button:0,buttons:0,...a}),e(u,"mouseup",i.x,i.y,{button:0,buttons:0,...a}),(u===c||c.contains(u))&&e(u,"click",i.x,i.y,{button:0,buttons:0,...a}),this.cursor.press(!1),this.over(u,i.x,i.y)}async slide(t,e,n){await this.point(t,e),this.cursor.press(!0);const s=t.getBoundingClientRect(),[i,r]=[Number(t.min||0),Number(t.max||100)],a="any"===t.step?0:Number(t.step||1);for(let c=1;c<=12;c++){const l=e.x+(n.x-e.x)*(c/12);this.cursor.move(l,e.y+(n.y-e.y)*(c/12));let u=i+Math.min(1,Math.max(0,(l-s.left)/(s.width||1)))*(r-i);a&&(u=Math.round((u-i)/a)*a+i),o(t,String(u)),t.dispatchEvent(new Event("input",{bubbles:!0})),await this.wait(25)}t.dispatchEvent(new Event("change",{bubbles:!0})),this.cursor.press(!1)}async type(t,n){const s=t;s.focus?.({preventScroll:!0});const i=t.isContentEditable;for(let r=0===n.length?0:1;r<=n.length;r++){const a=n.slice(0,r),c=n[r-1];c&&e(t,"keydown",0,0,{key:c}),i?t.textContent=a:o(s,a),t.dispatchEvent(new InputEvent("input",{bubbles:!0,data:c??null,inputType:c?"insertText":"deleteContentBackward"})),c&&e(t,"keyup",0,0,{key:c}),await this.wait(55)}t.dispatchEvent(new Event("change",{bubbles:!0}))}key(t,e){const n=e??document.activeElement??document.body,{key:o,...s}=parseChord(t),r={key:o,code:i(o),bubbles:!0,cancelable:!0,composed:!0,...s},a=new KeyboardEvent("keydown",r),c=!n.dispatchEvent(a);n.dispatchEvent(new KeyboardEvent("keyup",r));const l=n.form;!c&&"Enter"===o&&l&&n instanceof HTMLInputElement&&l.requestSubmit()}async select(t,e,n){await this.point(t,n),this.cursor.press(!0);const s=e.trim().toLowerCase(),i=Array.from(t.options).find(t=>t.value===e||t.text.trim().toLowerCase()===s);if(!i)throw new Error(`No option "${e}"`);await this.wait(250),o(t,i.value),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),this.cursor.press(!1)}async scroll(t,e){e?(t??window).scrollBy({left:e[0],top:e[1],behavior:this.speed()>1?"auto":"smooth"}):t?.scrollIntoView({block:"center",inline:"nearest",behavior:this.speed()>1?"auto":"smooth"}),await this.wait(500)}reset(){this.leave()}}export function at(t,e=[.5,.5]){const n=t.getBoundingClientRect();return{x:n.left+e[0]*n.width,y:n.top+e[1]*n.height}}function t(t){return{shiftKey:Boolean(t.shift),ctrlKey:Boolean(t.ctrl),altKey:Boolean(t.alt),metaKey:Boolean(t.meta)}}function e(t,e,n,o,s={}){const i={bubbles:!0,cancelable:!0,composed:!0,clientX:n,clientY:o,screenX:n,screenY:o,view:window,pointerId:1,pointerType:"mouse",isPrimary:!0,...s};let r;r=e.startsWith("key")?new KeyboardEvent(e,{bubbles:!0,cancelable:!0,composed:!0,...s}):e.startsWith("pointer")?new PointerEvent(e,i):new MouseEvent(e,i),t.dispatchEvent(r)}function n(t){const e=t.closest('button, a[href], input, textarea, select, summary, [tabindex], [contenteditable=""], [contenteditable="true"]');e?.focus({preventScroll:!0})}function o(t,e){const n=Object.getPrototypeOf(t),o=Object.getOwnPropertyDescriptor(n,"value")?.set;o?o.call(t,e):t.value=e}const s={control:"ctrl",ctrl:"ctrl",shift:"shift",alt:"alt",option:"alt",meta:"meta",cmd:"meta",command:"meta"};export function parseChord(t){const e=t.length>1&&t.endsWith("++"),n=(e?t.slice(0,-2):t).split("+").map(t=>t.trim()).filter(Boolean),o=e?"+":n.pop()??"",i=new Set(n.map(t=>s[t.toLowerCase()]).filter(Boolean));return{key:1===o.length&&i.size?o.toLowerCase():o,ctrlKey:i.has("ctrl"),shiftKey:i.has("shift"),altKey:i.has("alt"),metaKey:i.has("meta")}}function i(t){return/^[a-z]$/i.test(t)?`Key${t.toUpperCase()}`:/^\d$/.test(t)?`Digit${t}`:" "===t?"Space":t}