@protomaze/demo-engine 0.1.5 → 0.1.7

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.
package/AGENTS.md CHANGED
@@ -22,7 +22,8 @@ what they show, not where they are.
22
22
  4. Write the demo (format below). Narration first, then the actions that show it.
23
23
  5. `demoEngine.validate(demo)` - its shape. Then `await demoEngine.check(demo)` - from the demo's
24
24
  start, fast and silent, going past what fails, its cleanup after; fix every failure and check
25
- again until `ok` twice in a row (the second run proves the cleanup).
25
+ again until `ok` twice in a row (the second run proves the cleanup). The page's CSS transitions
26
+ and animations are off while it runs, so it works in a background tab too.
26
27
  6. `await demoEngine.save(demo)`, then `demoEngine.open(demo.id)` - the person sees it in the
27
28
  studio, can play, tune, film and share it. `demoEngine.play(id)` plays it with sound once the
28
29
  person clicks. `demoEngine.estimate(demo)` gives its length.
@@ -111,7 +112,8 @@ Step options: `title` (for the editor), `hold` (ms after), `pause: true` (waits
111
112
 
112
113
  `cleanup`: actions done after the demo - when it ends or is stopped - quickly and unseen, so the app
113
114
  is as it found it and the demo plays again: clear filters and searches, close what was opened, go
114
- back to the first tab. What the app cannot undo through its UI, its start resets.
115
+ back to the first tab. What the app cannot undo through its UI, its start resets. A cleanup target
116
+ not there within half a second is skipped, so list every reset that might be needed.
115
117
 
116
118
  ## Good demos
117
119
 
@@ -127,6 +129,6 @@ back to the first tab. What the app cannot undo through its UI, its start resets
127
129
 
128
130
  help() · languages() · start() · page({ within?, query?, limit? }) · find(target) ·
129
131
  describe(css | [x, y]) · try(action) · preview(presentationAction, ms?) · demos() · get(id) ·
130
- validate(demo) · estimate(demoOrId) · check(demoOrId, { from?, to? }) · save(demo) · remove(id) ·
132
+ validate(demo) · estimate(demoOrId) · check(demoOrId, { from?, to?, animations? }) · save(demo) · remove(id) ·
131
133
  open(demoOrId) · play(demoOrId, { from? }) · guide(demoOrId, { from? }) · loop([demoOrId]) ·
132
134
  stopLoop() · stop() · state() · link(demoOrId)
package/agent/Agent.d.ts CHANGED
@@ -98,6 +98,7 @@ export declare function agentTools(engine: DemoEngine): {
98
98
  check: (demo: DemoOrId, options?: {
99
99
  from?: number;
100
100
  to?: number;
101
+ animations?: boolean;
101
102
  }) => Promise<CheckReport>;
102
103
  /** Kept in this browser; shows in the library. Over an app's demo of the same id, until removed. */
103
104
  save: (demo: Demo) => Promise<{
package/agent/Guide.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  /** How an AI makes a demo with `window.demoEngine`: `demoEngine.help()` returns it; AGENTS.md is made from it. */
2
- export declare const GUIDE = "# Making a demo with demoEngine\n\nYou see the app in a browser and run JavaScript in it. `window.demoEngine` has the tools; every\nresult is plain data. A demo is steps; each step's narration is spoken (and subtitled) a sentence at\na time while its actions play one after the other. Actions point at elements as a person would: by\nwhat they show, not where they are.\n\n## Workflow\n\n1. `demoEngine.languages()` - which languages to write narration in.\n `demoEngine.start()` - where the app is; a demo starts there. `demoEngine.demos()` - what exists.\n2. Explore. `demoEngine.page()` lists what can be acted on, each with a ready `target`, its label,\n state and box; `page({ query: 'save' })` or `page({ within: '[data-demo=\"filters\"]' })` narrows it.\n Look with screenshots too. `demoEngine.try({ do: 'click', target })` does one action now and says\n what appeared and went: walk the app this way to learn the path the demo will take.\n3. Plan the story before the actions: what should the viewer understand at the end? One idea per step.\n4. Write the demo (format below). Narration first, then the actions that show it.\n5. `demoEngine.validate(demo)` - its shape. Then `await demoEngine.check(demo)` - from the demo's\n start, fast and silent, going past what fails, its cleanup after; fix every failure and check\n again until `ok` twice in a row (the second run proves the cleanup).\n6. `await demoEngine.save(demo)`, then `demoEngine.open(demo.id)` - the person sees it in the\n studio, can play, tune, film and share it. `demoEngine.play(id)` plays it with sound once the\n person clicks. `demoEngine.estimate(demo)` gives its length.\n\n## Length\n\n- Short (a teaser, one feature): 4-7 steps, 30-60 s, one or two sentences a step.\n- Normal (a tour): 8-12 steps, 1-3 min.\n- Detailed (a deep dive): 12-25 steps, 3-6 min; still one idea per step.\n\n## What it is for\n\n- Marketing video: short, benefit first, a `card` to open and close, zooms on what impresses; no\n setup steps on screen. The person films it (film button); music can play under it.\n- Sales pitch: one step per point the presenter makes; `pause: true` on steps where they talk\n freely. They advance with a clicker (PageDown) and repeat with PageUp.\n- Expo booth: 30-90 s, readable without sound (subtitles carry it), ends where it started so it can\n loop. `demoEngine.loop([ids])` plays them unattended; a visitor's touch hands the app over.\n- Tutorial or training: `demoEngine.guide(id)` lets the viewer do each click and entry themselves,\n ringed with what to do. Narrate why, not only what; small steps; one new thing each.\n\n## Narration\n\n- For the viewer, about what matters to them: \"Which pipes need work first?\" before \"Click Risk\".\n- Present tense, plain words, at most ~20 words a sentence; a step ~1-3 sentences.\n- Say what to look at as it happens; name things as the app names them.\n- Every language of `languages().write`: `say: { en: '\u2026', de: '\u2026' }`. Same meaning, natural in each.\n- No \"In this demo\u2026\" filler; open with the question or the benefit, close with what was shown.\n\n## Format\n\n```json\n{\n \"id\": \"orders-tour\",\n \"title\": \"Orders, from list to invoice\",\n \"description\": \"One sentence: who it is for and what it shows.\",\n \"start\": { \"\u2026\": \"as demoEngine.start() gives it, or leave out\" },\n \"steps\": [\n {\n \"title\": \"Find an order\",\n \"say\": { \"en\": \"Every order lands here, newest first. Let's find one from Berlin.\" },\n \"actions\": [\n { \"do\": \"spotlight\", \"target\": { \"css\": \"table\", \"text\": \"orders\" }, \"for\": 2500 },\n { \"do\": \"type\", \"target\": { \"css\": \"input[type=\\\"search\\\"]\" }, \"text\": \"Berlin\", \"cue\": 1 },\n { \"do\": \"click\", \"target\": { \"css\": \"tr\", \"text\": \"berlin #\" }, \"wait\": 1200 }\n ]\n }\n ]\n}\n```\n\nA target: `{ css, text?, key?, index? }` - the `index`th (0-based) element matching `css` whose label\nis `text` (or the app's locale `key`'s text: works in every language). Labels compare without case,\nspacing, and with every number as \"#\": a row \"Berlin 42\" is \"berlin #\". Use the targets `page()` and\n`describe()` give: they prefer locale keys and named regions. Avoid `index` where a scope does it:\n`{ css: '[data-demo=\"filters\"] button', text: 'apply' }`.\n\nEvery action has `wait` (ms before it, default 800) and `cue` (start with the step's sentence of that\nindex, 0-based: syncs a click with the words about it, in every language and voice).\n\nInteractions:\n- `click` { target, at?: [x, y] fractions of the box, double?, right?, shift?, ctrl?, alt?, meta? }\n- `hover` { target, at? } - shows tooltips and hover cards (not CSS :hover looks)\n- `type` { target, text } - replaces the field's text, a letter at a time\n- `key` { key, target? } - 'Escape', 'Enter', 'ArrowDown', 'Control+K'; shown as keycaps\n- `select` { target, option } - a native <select>'s option by text or value\n- `drag` { target, at?, to: { target?, at? } } - sliders, drag and drop, panning\n- `scroll` { target?, by?: [x, y] } - into view, or by pixels\n- `waitFor` { target, gone?, timeout? } - until it shows (or goes): after what loads\n\nPresentation (shown until the step ends, or `for` ms; `clear` takes all down):\n- `spotlight` { target, text?, padding? } - dims everything else: the one thing to look at\n- `ring` { target, text?, color?, shape?: 'box' | 'circle' } - a pulsing outline\n- `arrow` { target, text?, from?: 'top' | 'right' | 'bottom' | 'left' } - points at it\n- `callout` { text, target?, side?, corner? } - a note by the target, or in a corner\n- `blur` { target } - hides names, addresses, anything private\n- `card` { title, text? } - full screen: an opening title, a chapter, the end\n- `zoom` { target, scale? } - magnifies the page around it (1.8 by default)\n- `clear`\n\nThe app may add its own actions (a map's `view`, `mapClick`): `validate` lists every kind it knows\nwhen one is wrong; read the app's demos (`demoEngine.get(id)`) for examples.\n\nStep options: `title` (for the editor), `hold` (ms after), `pause: true` (waits for the presenter),\n`notes` (on the presenter's screen only: what to add live, figures to mention, questions to expect).\n\n`cleanup`: actions done after the demo - when it ends or is stopped - quickly and unseen, so the app\nis as it found it and the demo plays again: clear filters and searches, close what was opened, go\nback to the first tab. What the app cannot undo through its UI, its start resets.\n\n## Good demos\n\n- Open with a `card` (title, one line of promise), close with one (what was shown, what next).\n- Direct the eye: a spotlight or ring on what the sentence is about, an arrow for small things.\n- Let the viewer see results: a `wait` of 1500-3000 ms after what changes a lot; `waitFor` what loads.\n- Keep the pointer purposeful: no clicks that do not move the story.\n- Blur personal data.\n- Leave the app as it started: a `cleanup` list undoes what the steps changed, so demos run one\n after another and again. Check that too: `check` runs the cleanup, then `check` again.\n\n## Tools\n\nhelp() \u00B7 languages() \u00B7 start() \u00B7 page({ within?, query?, limit? }) \u00B7 find(target) \u00B7\ndescribe(css | [x, y]) \u00B7 try(action) \u00B7 preview(presentationAction, ms?) \u00B7 demos() \u00B7 get(id) \u00B7\nvalidate(demo) \u00B7 estimate(demoOrId) \u00B7 check(demoOrId, { from?, to? }) \u00B7 save(demo) \u00B7 remove(id) \u00B7\nopen(demoOrId) \u00B7 play(demoOrId, { from? }) \u00B7 guide(demoOrId, { from? }) \u00B7 loop([demoOrId]) \u00B7\nstopLoop() \u00B7 stop() \u00B7 state() \u00B7 link(demoOrId)\n";
2
+ export declare const GUIDE = "# Making a demo with demoEngine\n\nYou see the app in a browser and run JavaScript in it. `window.demoEngine` has the tools; every\nresult is plain data. A demo is steps; each step's narration is spoken (and subtitled) a sentence at\na time while its actions play one after the other. Actions point at elements as a person would: by\nwhat they show, not where they are.\n\n## Workflow\n\n1. `demoEngine.languages()` - which languages to write narration in.\n `demoEngine.start()` - where the app is; a demo starts there. `demoEngine.demos()` - what exists.\n2. Explore. `demoEngine.page()` lists what can be acted on, each with a ready `target`, its label,\n state and box; `page({ query: 'save' })` or `page({ within: '[data-demo=\"filters\"]' })` narrows it.\n Look with screenshots too. `demoEngine.try({ do: 'click', target })` does one action now and says\n what appeared and went: walk the app this way to learn the path the demo will take.\n3. Plan the story before the actions: what should the viewer understand at the end? One idea per step.\n4. Write the demo (format below). Narration first, then the actions that show it.\n5. `demoEngine.validate(demo)` - its shape. Then `await demoEngine.check(demo)` - from the demo's\n start, fast and silent, going past what fails, its cleanup after; fix every failure and check\n again until `ok` twice in a row (the second run proves the cleanup). The page's CSS transitions\n and animations are off while it runs, so it works in a background tab too.\n6. `await demoEngine.save(demo)`, then `demoEngine.open(demo.id)` - the person sees it in the\n studio, can play, tune, film and share it. `demoEngine.play(id)` plays it with sound once the\n person clicks. `demoEngine.estimate(demo)` gives its length.\n\n## Length\n\n- Short (a teaser, one feature): 4-7 steps, 30-60 s, one or two sentences a step.\n- Normal (a tour): 8-12 steps, 1-3 min.\n- Detailed (a deep dive): 12-25 steps, 3-6 min; still one idea per step.\n\n## What it is for\n\n- Marketing video: short, benefit first, a `card` to open and close, zooms on what impresses; no\n setup steps on screen. The person films it (film button); music can play under it.\n- Sales pitch: one step per point the presenter makes; `pause: true` on steps where they talk\n freely. They advance with a clicker (PageDown) and repeat with PageUp.\n- Expo booth: 30-90 s, readable without sound (subtitles carry it), ends where it started so it can\n loop. `demoEngine.loop([ids])` plays them unattended; a visitor's touch hands the app over.\n- Tutorial or training: `demoEngine.guide(id)` lets the viewer do each click and entry themselves,\n ringed with what to do. Narrate why, not only what; small steps; one new thing each.\n\n## Narration\n\n- For the viewer, about what matters to them: \"Which pipes need work first?\" before \"Click Risk\".\n- Present tense, plain words, at most ~20 words a sentence; a step ~1-3 sentences.\n- Say what to look at as it happens; name things as the app names them.\n- Every language of `languages().write`: `say: { en: '\u2026', de: '\u2026' }`. Same meaning, natural in each.\n- No \"In this demo\u2026\" filler; open with the question or the benefit, close with what was shown.\n\n## Format\n\n```json\n{\n \"id\": \"orders-tour\",\n \"title\": \"Orders, from list to invoice\",\n \"description\": \"One sentence: who it is for and what it shows.\",\n \"start\": { \"\u2026\": \"as demoEngine.start() gives it, or leave out\" },\n \"steps\": [\n {\n \"title\": \"Find an order\",\n \"say\": { \"en\": \"Every order lands here, newest first. Let's find one from Berlin.\" },\n \"actions\": [\n { \"do\": \"spotlight\", \"target\": { \"css\": \"table\", \"text\": \"orders\" }, \"for\": 2500 },\n { \"do\": \"type\", \"target\": { \"css\": \"input[type=\\\"search\\\"]\" }, \"text\": \"Berlin\", \"cue\": 1 },\n { \"do\": \"click\", \"target\": { \"css\": \"tr\", \"text\": \"berlin #\" }, \"wait\": 1200 }\n ]\n }\n ]\n}\n```\n\nA target: `{ css, text?, key?, index? }` - the `index`th (0-based) element matching `css` whose label\nis `text` (or the app's locale `key`'s text: works in every language). Labels compare without case,\nspacing, and with every number as \"#\": a row \"Berlin 42\" is \"berlin #\". Use the targets `page()` and\n`describe()` give: they prefer locale keys and named regions. Avoid `index` where a scope does it:\n`{ css: '[data-demo=\"filters\"] button', text: 'apply' }`.\n\nEvery action has `wait` (ms before it, default 800) and `cue` (start with the step's sentence of that\nindex, 0-based: syncs a click with the words about it, in every language and voice).\n\nInteractions:\n- `click` { target, at?: [x, y] fractions of the box, double?, right?, shift?, ctrl?, alt?, meta? }\n- `hover` { target, at? } - shows tooltips and hover cards (not CSS :hover looks)\n- `type` { target, text } - replaces the field's text, a letter at a time\n- `key` { key, target? } - 'Escape', 'Enter', 'ArrowDown', 'Control+K'; shown as keycaps\n- `select` { target, option } - a native <select>'s option by text or value\n- `drag` { target, at?, to: { target?, at? } } - sliders, drag and drop, panning\n- `scroll` { target?, by?: [x, y] } - into view, or by pixels\n- `waitFor` { target, gone?, timeout? } - until it shows (or goes): after what loads\n\nPresentation (shown until the step ends, or `for` ms; `clear` takes all down):\n- `spotlight` { target, text?, padding? } - dims everything else: the one thing to look at\n- `ring` { target, text?, color?, shape?: 'box' | 'circle' } - a pulsing outline\n- `arrow` { target, text?, from?: 'top' | 'right' | 'bottom' | 'left' } - points at it\n- `callout` { text, target?, side?, corner? } - a note by the target, or in a corner\n- `blur` { target } - hides names, addresses, anything private\n- `card` { title, text? } - full screen: an opening title, a chapter, the end\n- `zoom` { target, scale? } - magnifies the page around it (1.8 by default)\n- `clear`\n\nThe app may add its own actions (a map's `view`, `mapClick`): `validate` lists every kind it knows\nwhen one is wrong; read the app's demos (`demoEngine.get(id)`) for examples.\n\nStep options: `title` (for the editor), `hold` (ms after), `pause: true` (waits for the presenter),\n`notes` (on the presenter's screen only: what to add live, figures to mention, questions to expect).\n\n`cleanup`: actions done after the demo - when it ends or is stopped - quickly and unseen, so the app\nis as it found it and the demo plays again: clear filters and searches, close what was opened, go\nback to the first tab. What the app cannot undo through its UI, its start resets. A cleanup target\nnot there within half a second is skipped, so list every reset that might be needed.\n\n## Good demos\n\n- Open with a `card` (title, one line of promise), close with one (what was shown, what next).\n- Direct the eye: a spotlight or ring on what the sentence is about, an arrow for small things.\n- Let the viewer see results: a `wait` of 1500-3000 ms after what changes a lot; `waitFor` what loads.\n- Keep the pointer purposeful: no clicks that do not move the story.\n- Blur personal data.\n- Leave the app as it started: a `cleanup` list undoes what the steps changed, so demos run one\n after another and again. Check that too: `check` runs the cleanup, then `check` again.\n\n## Tools\n\nhelp() \u00B7 languages() \u00B7 start() \u00B7 page({ within?, query?, limit? }) \u00B7 find(target) \u00B7\ndescribe(css | [x, y]) \u00B7 try(action) \u00B7 preview(presentationAction, ms?) \u00B7 demos() \u00B7 get(id) \u00B7\nvalidate(demo) \u00B7 estimate(demoOrId) \u00B7 check(demoOrId, { from?, to?, animations? }) \u00B7 save(demo) \u00B7 remove(id) \u00B7\nopen(demoOrId) \u00B7 play(demoOrId, { from? }) \u00B7 guide(demoOrId, { from? }) \u00B7 loop([demoOrId]) \u00B7\nstopLoop() \u00B7 stop() \u00B7 state() \u00B7 link(demoOrId)\n";
package/agent/Guide.js CHANGED
@@ -1 +1 @@
1
- export const GUIDE='# Making a demo with demoEngine\n\nYou see the app in a browser and run JavaScript in it. `window.demoEngine` has the tools; every\nresult is plain data. A demo is steps; each step\'s narration is spoken (and subtitled) a sentence at\na time while its actions play one after the other. Actions point at elements as a person would: by\nwhat they show, not where they are.\n\n## Workflow\n\n1. `demoEngine.languages()` - which languages to write narration in.\n `demoEngine.start()` - where the app is; a demo starts there. `demoEngine.demos()` - what exists.\n2. Explore. `demoEngine.page()` lists what can be acted on, each with a ready `target`, its label,\n state and box; `page({ query: \'save\' })` or `page({ within: \'[data-demo="filters"]\' })` narrows it.\n Look with screenshots too. `demoEngine.try({ do: \'click\', target })` does one action now and says\n what appeared and went: walk the app this way to learn the path the demo will take.\n3. Plan the story before the actions: what should the viewer understand at the end? One idea per step.\n4. Write the demo (format below). Narration first, then the actions that show it.\n5. `demoEngine.validate(demo)` - its shape. Then `await demoEngine.check(demo)` - from the demo\'s\n start, fast and silent, going past what fails, its cleanup after; fix every failure and check\n again until `ok` twice in a row (the second run proves the cleanup).\n6. `await demoEngine.save(demo)`, then `demoEngine.open(demo.id)` - the person sees it in the\n studio, can play, tune, film and share it. `demoEngine.play(id)` plays it with sound once the\n person clicks. `demoEngine.estimate(demo)` gives its length.\n\n## Length\n\n- Short (a teaser, one feature): 4-7 steps, 30-60 s, one or two sentences a step.\n- Normal (a tour): 8-12 steps, 1-3 min.\n- Detailed (a deep dive): 12-25 steps, 3-6 min; still one idea per step.\n\n## What it is for\n\n- Marketing video: short, benefit first, a `card` to open and close, zooms on what impresses; no\n setup steps on screen. The person films it (film button); music can play under it.\n- Sales pitch: one step per point the presenter makes; `pause: true` on steps where they talk\n freely. They advance with a clicker (PageDown) and repeat with PageUp.\n- Expo booth: 30-90 s, readable without sound (subtitles carry it), ends where it started so it can\n loop. `demoEngine.loop([ids])` plays them unattended; a visitor\'s touch hands the app over.\n- Tutorial or training: `demoEngine.guide(id)` lets the viewer do each click and entry themselves,\n ringed with what to do. Narrate why, not only what; small steps; one new thing each.\n\n## Narration\n\n- For the viewer, about what matters to them: "Which pipes need work first?" before "Click Risk".\n- Present tense, plain words, at most ~20 words a sentence; a step ~1-3 sentences.\n- Say what to look at as it happens; name things as the app names them.\n- Every language of `languages().write`: `say: { en: \'…\', de: \'…\' }`. Same meaning, natural in each.\n- No "In this demo…" filler; open with the question or the benefit, close with what was shown.\n\n## Format\n\n```json\n{\n "id": "orders-tour",\n "title": "Orders, from list to invoice",\n "description": "One sentence: who it is for and what it shows.",\n "start": { "…": "as demoEngine.start() gives it, or leave out" },\n "steps": [\n {\n "title": "Find an order",\n "say": { "en": "Every order lands here, newest first. Let\'s find one from Berlin." },\n "actions": [\n { "do": "spotlight", "target": { "css": "table", "text": "orders" }, "for": 2500 },\n { "do": "type", "target": { "css": "input[type=\\"search\\"]" }, "text": "Berlin", "cue": 1 },\n { "do": "click", "target": { "css": "tr", "text": "berlin #" }, "wait": 1200 }\n ]\n }\n ]\n}\n```\n\nA target: `{ css, text?, key?, index? }` - the `index`th (0-based) element matching `css` whose label\nis `text` (or the app\'s locale `key`\'s text: works in every language). Labels compare without case,\nspacing, and with every number as "#": a row "Berlin 42" is "berlin #". Use the targets `page()` and\n`describe()` give: they prefer locale keys and named regions. Avoid `index` where a scope does it:\n`{ css: \'[data-demo="filters"] button\', text: \'apply\' }`.\n\nEvery action has `wait` (ms before it, default 800) and `cue` (start with the step\'s sentence of that\nindex, 0-based: syncs a click with the words about it, in every language and voice).\n\nInteractions:\n- `click` { target, at?: [x, y] fractions of the box, double?, right?, shift?, ctrl?, alt?, meta? }\n- `hover` { target, at? } - shows tooltips and hover cards (not CSS :hover looks)\n- `type` { target, text } - replaces the field\'s text, a letter at a time\n- `key` { key, target? } - \'Escape\', \'Enter\', \'ArrowDown\', \'Control+K\'; shown as keycaps\n- `select` { target, option } - a native <select>\'s option by text or value\n- `drag` { target, at?, to: { target?, at? } } - sliders, drag and drop, panning\n- `scroll` { target?, by?: [x, y] } - into view, or by pixels\n- `waitFor` { target, gone?, timeout? } - until it shows (or goes): after what loads\n\nPresentation (shown until the step ends, or `for` ms; `clear` takes all down):\n- `spotlight` { target, text?, padding? } - dims everything else: the one thing to look at\n- `ring` { target, text?, color?, shape?: \'box\' | \'circle\' } - a pulsing outline\n- `arrow` { target, text?, from?: \'top\' | \'right\' | \'bottom\' | \'left\' } - points at it\n- `callout` { text, target?, side?, corner? } - a note by the target, or in a corner\n- `blur` { target } - hides names, addresses, anything private\n- `card` { title, text? } - full screen: an opening title, a chapter, the end\n- `zoom` { target, scale? } - magnifies the page around it (1.8 by default)\n- `clear`\n\nThe app may add its own actions (a map\'s `view`, `mapClick`): `validate` lists every kind it knows\nwhen one is wrong; read the app\'s demos (`demoEngine.get(id)`) for examples.\n\nStep options: `title` (for the editor), `hold` (ms after), `pause: true` (waits for the presenter),\n`notes` (on the presenter\'s screen only: what to add live, figures to mention, questions to expect).\n\n`cleanup`: actions done after the demo - when it ends or is stopped - quickly and unseen, so the app\nis as it found it and the demo plays again: clear filters and searches, close what was opened, go\nback to the first tab. What the app cannot undo through its UI, its start resets.\n\n## Good demos\n\n- Open with a `card` (title, one line of promise), close with one (what was shown, what next).\n- Direct the eye: a spotlight or ring on what the sentence is about, an arrow for small things.\n- Let the viewer see results: a `wait` of 1500-3000 ms after what changes a lot; `waitFor` what loads.\n- Keep the pointer purposeful: no clicks that do not move the story.\n- Blur personal data.\n- Leave the app as it started: a `cleanup` list undoes what the steps changed, so demos run one\n after another and again. Check that too: `check` runs the cleanup, then `check` again.\n\n## Tools\n\nhelp() · languages() · start() · page({ within?, query?, limit? }) · find(target) ·\ndescribe(css | [x, y]) · try(action) · preview(presentationAction, ms?) · demos() · get(id) ·\nvalidate(demo) · estimate(demoOrId) · check(demoOrId, { from?, to? }) · save(demo) · remove(id) ·\nopen(demoOrId) · play(demoOrId, { from? }) · guide(demoOrId, { from? }) · loop([demoOrId]) ·\nstopLoop() · stop() · state() · link(demoOrId)\n';
1
+ export const GUIDE='# Making a demo with demoEngine\n\nYou see the app in a browser and run JavaScript in it. `window.demoEngine` has the tools; every\nresult is plain data. A demo is steps; each step\'s narration is spoken (and subtitled) a sentence at\na time while its actions play one after the other. Actions point at elements as a person would: by\nwhat they show, not where they are.\n\n## Workflow\n\n1. `demoEngine.languages()` - which languages to write narration in.\n `demoEngine.start()` - where the app is; a demo starts there. `demoEngine.demos()` - what exists.\n2. Explore. `demoEngine.page()` lists what can be acted on, each with a ready `target`, its label,\n state and box; `page({ query: \'save\' })` or `page({ within: \'[data-demo="filters"]\' })` narrows it.\n Look with screenshots too. `demoEngine.try({ do: \'click\', target })` does one action now and says\n what appeared and went: walk the app this way to learn the path the demo will take.\n3. Plan the story before the actions: what should the viewer understand at the end? One idea per step.\n4. Write the demo (format below). Narration first, then the actions that show it.\n5. `demoEngine.validate(demo)` - its shape. Then `await demoEngine.check(demo)` - from the demo\'s\n start, fast and silent, going past what fails, its cleanup after; fix every failure and check\n again until `ok` twice in a row (the second run proves the cleanup). The page\'s CSS transitions\n and animations are off while it runs, so it works in a background tab too.\n6. `await demoEngine.save(demo)`, then `demoEngine.open(demo.id)` - the person sees it in the\n studio, can play, tune, film and share it. `demoEngine.play(id)` plays it with sound once the\n person clicks. `demoEngine.estimate(demo)` gives its length.\n\n## Length\n\n- Short (a teaser, one feature): 4-7 steps, 30-60 s, one or two sentences a step.\n- Normal (a tour): 8-12 steps, 1-3 min.\n- Detailed (a deep dive): 12-25 steps, 3-6 min; still one idea per step.\n\n## What it is for\n\n- Marketing video: short, benefit first, a `card` to open and close, zooms on what impresses; no\n setup steps on screen. The person films it (film button); music can play under it.\n- Sales pitch: one step per point the presenter makes; `pause: true` on steps where they talk\n freely. They advance with a clicker (PageDown) and repeat with PageUp.\n- Expo booth: 30-90 s, readable without sound (subtitles carry it), ends where it started so it can\n loop. `demoEngine.loop([ids])` plays them unattended; a visitor\'s touch hands the app over.\n- Tutorial or training: `demoEngine.guide(id)` lets the viewer do each click and entry themselves,\n ringed with what to do. Narrate why, not only what; small steps; one new thing each.\n\n## Narration\n\n- For the viewer, about what matters to them: "Which pipes need work first?" before "Click Risk".\n- Present tense, plain words, at most ~20 words a sentence; a step ~1-3 sentences.\n- Say what to look at as it happens; name things as the app names them.\n- Every language of `languages().write`: `say: { en: \'…\', de: \'…\' }`. Same meaning, natural in each.\n- No "In this demo…" filler; open with the question or the benefit, close with what was shown.\n\n## Format\n\n```json\n{\n "id": "orders-tour",\n "title": "Orders, from list to invoice",\n "description": "One sentence: who it is for and what it shows.",\n "start": { "…": "as demoEngine.start() gives it, or leave out" },\n "steps": [\n {\n "title": "Find an order",\n "say": { "en": "Every order lands here, newest first. Let\'s find one from Berlin." },\n "actions": [\n { "do": "spotlight", "target": { "css": "table", "text": "orders" }, "for": 2500 },\n { "do": "type", "target": { "css": "input[type=\\"search\\"]" }, "text": "Berlin", "cue": 1 },\n { "do": "click", "target": { "css": "tr", "text": "berlin #" }, "wait": 1200 }\n ]\n }\n ]\n}\n```\n\nA target: `{ css, text?, key?, index? }` - the `index`th (0-based) element matching `css` whose label\nis `text` (or the app\'s locale `key`\'s text: works in every language). Labels compare without case,\nspacing, and with every number as "#": a row "Berlin 42" is "berlin #". Use the targets `page()` and\n`describe()` give: they prefer locale keys and named regions. Avoid `index` where a scope does it:\n`{ css: \'[data-demo="filters"] button\', text: \'apply\' }`.\n\nEvery action has `wait` (ms before it, default 800) and `cue` (start with the step\'s sentence of that\nindex, 0-based: syncs a click with the words about it, in every language and voice).\n\nInteractions:\n- `click` { target, at?: [x, y] fractions of the box, double?, right?, shift?, ctrl?, alt?, meta? }\n- `hover` { target, at? } - shows tooltips and hover cards (not CSS :hover looks)\n- `type` { target, text } - replaces the field\'s text, a letter at a time\n- `key` { key, target? } - \'Escape\', \'Enter\', \'ArrowDown\', \'Control+K\'; shown as keycaps\n- `select` { target, option } - a native <select>\'s option by text or value\n- `drag` { target, at?, to: { target?, at? } } - sliders, drag and drop, panning\n- `scroll` { target?, by?: [x, y] } - into view, or by pixels\n- `waitFor` { target, gone?, timeout? } - until it shows (or goes): after what loads\n\nPresentation (shown until the step ends, or `for` ms; `clear` takes all down):\n- `spotlight` { target, text?, padding? } - dims everything else: the one thing to look at\n- `ring` { target, text?, color?, shape?: \'box\' | \'circle\' } - a pulsing outline\n- `arrow` { target, text?, from?: \'top\' | \'right\' | \'bottom\' | \'left\' } - points at it\n- `callout` { text, target?, side?, corner? } - a note by the target, or in a corner\n- `blur` { target } - hides names, addresses, anything private\n- `card` { title, text? } - full screen: an opening title, a chapter, the end\n- `zoom` { target, scale? } - magnifies the page around it (1.8 by default)\n- `clear`\n\nThe app may add its own actions (a map\'s `view`, `mapClick`): `validate` lists every kind it knows\nwhen one is wrong; read the app\'s demos (`demoEngine.get(id)`) for examples.\n\nStep options: `title` (for the editor), `hold` (ms after), `pause: true` (waits for the presenter),\n`notes` (on the presenter\'s screen only: what to add live, figures to mention, questions to expect).\n\n`cleanup`: actions done after the demo - when it ends or is stopped - quickly and unseen, so the app\nis as it found it and the demo plays again: clear filters and searches, close what was opened, go\nback to the first tab. What the app cannot undo through its UI, its start resets. A cleanup target\nnot there within half a second is skipped, so list every reset that might be needed.\n\n## Good demos\n\n- Open with a `card` (title, one line of promise), close with one (what was shown, what next).\n- Direct the eye: a spotlight or ring on what the sentence is about, an arrow for small things.\n- Let the viewer see results: a `wait` of 1500-3000 ms after what changes a lot; `waitFor` what loads.\n- Keep the pointer purposeful: no clicks that do not move the story.\n- Blur personal data.\n- Leave the app as it started: a `cleanup` list undoes what the steps changed, so demos run one\n after another and again. Check that too: `check` runs the cleanup, then `check` again.\n\n## Tools\n\nhelp() · languages() · start() · page({ within?, query?, limit? }) · find(target) ·\ndescribe(css | [x, y]) · try(action) · preview(presentationAction, ms?) · demos() · get(id) ·\nvalidate(demo) · estimate(demoOrId) · check(demoOrId, { from?, to?, animations? }) · save(demo) · remove(id) ·\nopen(demoOrId) · play(demoOrId, { from? }) · guide(demoOrId, { from? }) · loop([demoOrId]) ·\nstopLoop() · stop() · state() · link(demoOrId)\n';
@@ -363,12 +363,15 @@ export declare class DemoEngine {
363
363
  /**
364
364
  * Plays it quickly and silently, going past what fails: whether every target is found and every
365
365
  * action plays. From its start (`fromStart: false`: from where the app is); no click needed.
366
+ * The page's CSS transitions and animations are off while it runs, so it works in a hidden tab
367
+ * too (`animations: true` leaves them on).
366
368
  */
367
369
  check(demo: Demo, options?: {
368
370
  from?: number;
369
371
  to?: number;
370
372
  speed?: number;
371
373
  fromStart?: boolean;
374
+ animations?: boolean;
372
375
  }): Promise<CheckReport>;
373
376
  /** When what happens in it, about: as last played if it has not changed since, else estimated. */
374
377
  timing(demo: Demo, language?: string): Timing;
@@ -1 +1 @@
1
- import{copyOf as e,languagesOf as t,newDemo as s,sayOf as i,scenarioOf as o,sentences as n}from"../model/Demo.js";import{parseSubtitles as a,toSrt as r,toVtt as h}from"../model/Subtitles.js";import{actionTime as p,estimate as l}from"../model/Timing.js";import{parseDemo as d,validate as c}from"../model/Validate.js";import{Hand as m}from"../page/Input.js";import{Overlay as g}from"../page/Overlay.js";import{Targets as u}from"../page/Targets.js";import{Speech as y}from"../speech/Speech.js";import{narrationFor as f,transcribe as w}from"../speech/Transcribe.js";import{Store as v}from"../store/Store.js";import{demoFromLink as k,download as S,fileName as b,linkTo as P,shareFiles as T}from"../store/Share.js";import{extensionOf as x,recordMicrophone as E,startFilming as R,videoSize as j}from"../video/Film.js";import{renderMusic as $}from"../speech/Music.js";import{readPack as M,writePack as L}from"../speech/Pack.js";import{Player as K}from"./Player.js";import{Recorder as N}from"./Recorder.js";import{readAction as B}from"./Read.js";import{mountUI as D}from"../ui/EngineUI.js";import{agentTools as I}from"../agent/Agent.js";import{openPresenter as O}from"../ui/Presenter.js";import{DEFAULT_RELAY as A,qrSvg as F,RemoteLink as C}from"../remote/Remote.js";import{DEFAULT_SETTINGS as J,loadSettings as U,saveSettings as z}from"./Settings.js";const V=["pointerdown","pointerup","pointermove","pointerover","pointerout","mousedown","mouseup","mousemove","mouseover","mouseout","click","dblclick","contextmenu","wheel","touchstart","touchmove","touchend","keydown","keyup","keypress"];export class DemoEngine{constructor(e){this.options=e,this.listeners=new Set,this.packs=new Map,this.remoteSent="",this.remoteTimer=0,this.getState=()=>this.state,this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e)),this.hintTimer=0,this.targets=new 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:U(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()),this.toRemote()}set(e){this.state={...this.state,...e},this.listeners.forEach(e=>e()),this.toRemote()}setSession(e){this.set({session:e})}updateSession(e,t){this.state.session.mode===e&&this.setSession({...this.state.session,...t})}say(e,t=!1){this.set({message:e?{text:e,error:t}:void 0})}changeSettings(e){const t={...this.state.settings,...e};z(this.settingsKey,t),this.set({settings:t}),e.music?.on&&this.loadMusic().catch(()=>{})}language(){const e=this.state.settings.language;return"page"!==e?e:this.options.language?.()??this.options.languages?.[0]??(navigator.language.split("-")[0]||"en")}languages(){return this.options.languages??[this.language()]}pluginKinds(){return this.plugins.flatMap(e=>Object.keys(e.actions??{}))}pluginAction(e){return this.plugins.map(t=>t.actions?.[e]).find(Boolean)}read(e,t){return B(e,this.options.labels,this.plugins,t)}async mount(){if(this.unmount)return;this.overlay.mount();const e=D(this),t=e=>this.key(e);window.addEventListener("keydown",t,!0);const s=e=>this.gate(e);V.forEach(e=>window.addEventListener(e,s,{capture:!0,passive:!1})),this.state.settings.music.on&&this.loadMusic().catch(()=>{});const i=!1===this.options.agent?void 0:this.options.agent??"demoEngine";i&&(window[i]=I(this)),this.unmount=()=>{e(),window.removeEventListener("keydown",t,!0),V.forEach(e=>window.removeEventListener(e,s,{capture:!0})),i&&delete window[i],this.overlay.unmount()},await this.arrived()}destroy(){this.closeRemote(),this.stopLoop(),this.stop(),this.unmount?.(),this.unmount=void 0}async arrived(){const e=sessionStorage.getItem(this.pendingKey());if(sessionStorage.removeItem(this.pendingKey()),e){const{demo:t,verb:s,from:i,loop:o}=JSON.parse(e);return"loop"===s&&o?void this.loop(o.demos,{gap:o.gap,idle:o.idle,reset:o.reload?"reload":void 0},o.index):this.whenClicked(t.title,"film"===s?"Film":"Play",()=>"film"===s?this.film(t):this.play(t,{from:i}),!0)}const t=await k();if(t){const e=c(t,this.pluginKinds());return e.length?this.say(`The link's demo: ${e[0].path} ${e[0].message}`,!0):(await this.save(t),this.say(`"${t.title}" came with the link: it is kept here.`),this.openStudio(t))}const s=new URL(window.location.href),i=s.searchParams.get("demo");if(i){s.searchParams.delete("demo"),window.history.replaceState(window.history.state,"",s.toString());const e=(await this.entries()).find(e=>e.demo.id===i);e&&this.whenClicked(e.demo.title,"Play",()=>this.play(e.demo),!0)}}gate(e){const t=this.state.session;if(!e.isTrusted||"playing"!==t.mode||t.paused||t.looping)return;const s=e.composedPath();if(s.includes(this.overlay.host))return;if(t.guided&&t.instruction){const i=t.player.viewerTarget();if(i&&(s.includes(i)||e instanceof KeyboardEvent&&i.contains(document.activeElement)))return;if(!i&&e instanceof KeyboardEvent)return}const i=e.defaultPrevented;e.cancelable&&e.preventDefault(),e.stopImmediatePropagation(),i||"pointerdown"!==e.type&&"keydown"!==e.type&&"wheel"!==e.type||this.hint(t.guided?'Only the ringed part now: or "Do it for me"':"Playing: Space pauses, and the app is yours then. Esc stops.")}hint(e){window.clearTimeout(this.hintTimer),this.set({hint:e}),this.hintTimer=window.setTimeout(()=>this.set({hint:void 0}),3e3)}pendingKey(){return`protomaze-demo-engine:${this.options.app}:pending`}key(e){if(!e.isTrusted)return;const t=e.composedPath(),s=t.some(e=>e instanceof HTMLElement&&(e.isContentEditable||e.matches("input, textarea, select"))),i=t.includes(this.overlay.host),o=this.state.session,n=()=>{e.preventDefault(),e.stopPropagation()};if("ready"!==o.mode)if("recording"!==o.mode){if("l"===e.key.toLowerCase()&&e.ctrlKey&&e.shiftKey&&this.looping)return n(),this.stopLoop();if(!("playing"!==o.mode||o.looping||o.checking||s&&(i||o.guided&&o.instruction))){if("Escape"===e.key)this.stop();else if(" "===e.key||"b"===e.key||"."===e.key)this.togglePause();else if("ArrowRight"===e.key||"Enter"===e.key||"PageDown"===e.key)o.player.next();else if("ArrowLeft"===e.key||"PageUp"===e.key)o.player.back();else if("Home"===e.key)o.player.goTo(0);else if("End"===e.key)o.player.goTo(o.steps-1);else{if(!/^[1-9]$/.test(e.key)||e.ctrlKey||e.metaKey||e.altKey)return;o.player.goTo(Number(e.key)-1)}n()}}else"Escape"!==e.key||s||(n(),this.stopRecording?.());else"Escape"===e.key&&(n(),o.cancel())}async entries(){return await this.store.ready(),this.entriesNow()}entriesNow(){const{demos:e,videos:t}=this.store.get(),s=new Map(e.map(e=>[e.id,e])),i=this.language(),n=(this.options.demos??[]).map(e=>"demo"in e?e:{demo:e,scenario:void 0});return[...n.map(({demo:e,scenario:n})=>{const a=s.get(e.id);return a?{demo:a,scenario:a.scenario??n??o(a,i),origin:"edited",video:t.get(e.id)}:{demo:e,scenario:n??o(e,i),origin:"app",video:t.get(e.id)}}),...e.filter(e=>!n.some(t=>t.demo.id===e.id)).map(e=>({demo:e,scenario:e.scenario??o(e,i),origin:"here",video:t.get(e.id)}))]}async save(t){const s=c(t,this.pluginKinds());if(s.length)throw new Error(`Not a demo: ${s.map(e=>`${e.path} ${e.message}`).join("; ")}`);await this.store.saveDemo(e(t))}async remove(e){await this.store.deleteDemo(e),this.state.studio?.demo.id===e&&this.closeStudio()}parse(e){return d(e,this.pluginKinds())}create(e){return s(e,this.options.start?.current())}openStudio(t){this.set({studio:{demo:e(t),opened:Date.now()}})}closeStudio(){this.set({studio:void 0})}activated(){const e=navigator.userActivation;return!e||e.isActive}whenClicked(e,t,s,i=!1){const o=()=>{this.setSession({mode:"idle"}),this.speech.wake(),s().catch(e=>this.say(e.message,!0))};if(!i&&this.activated())return o();this.setSession({mode:"ready",title:e,verb:t,go:o,cancel:()=>this.setSession({mode:"idle"})})}async goToStart(e,t,s,i){if(!e.start||!this.options.start)return!0;sessionStorage.setItem(this.pendingKey(),JSON.stringify({demo:e,verb:t,from:s,loop:i}));return"reload"!==await this.options.start.go(e.start)&&(sessionStorage.removeItem(this.pendingKey()),!0)}busy(){return"idle"!==this.state.session.mode&&"ready"!==this.state.session.mode}play(e,t={}){return new Promise(s=>this.whenClicked(e.title,"Play",async()=>{if(this.busy())return s(void 0);if(this.say(void 0),!await this.goToStart(e,"play",t.from))return s(void 0);const i=await this.run(e,t);s(i)}))}async run(e,t={}){const{settings:s}=this.state,i=t.language??this.language(),o=s.music.on&&!t.checking&&!t.guided&&await Promise.race([this.loadMusic(),new Promise(e=>setTimeout(()=>e(!1),t.filming?6e4:1500))]);this.speech.setPack(s.usePacks?await this.pack(e):void 0);const n=new K(e,{language:i,subtitles:s.subtitles,waitForPresenter:s.waitForPresenter&&!t.looping,catchUp:s.catchUp,music:Boolean(o),...t},{hand:this.hand,targets:this.targets,overlay:this.overlay,speech:this.speech,plugins:this.plugins,ready:this.options.ready,read:(e,t)=>this.read(e,t),reset:async()=>!e.start||!this.options.start||"reload"!==await this.options.start.go(e.start),update:e=>this.updateSession("playing",e)});this.setSession({mode:"playing",title:e.title,demo:e,steps:e.steps.length,filming:Boolean(t.filming),checking:Boolean(t.checking),guided:Boolean(t.guided),looping:Boolean(t.looping),presenting:Boolean(t.presenting),player:n,step:t.from??0,caption:"",paused:!1,waiting:!1,catchingUp:!1}),this.player=n;const a=await n.play().finally(()=>this.player=void 0);return this.setSession({mode:"idle"}),t.checking||a.navigated||(this.set({lastRun:{json:JSON.stringify(e),language:i,timing:a.timing}}),a.error&&"Stopped."!==a.error&&this.say(a.error,!0)),a}stop(){const e=this.state.session;"playing"===e.mode&&e.player.stop(),"recording"===e.mode&&this.stopRecording?.(),"ready"!==e.mode&&"preparing"!==e.mode||this.setSession({mode:"idle"})}togglePause(){const e=this.state.session;"playing"===e.mode&&(e.paused?e.player.resume():e.player.pause())}resume(){const e=this.state.session;"playing"===e.mode&&e.player.resume()}next(){const e=this.state.session;"playing"===e.mode&&e.player.next()}back(){const e=this.state.session;"playing"===e.mode&&e.player.back()}openPresenter(e={}){return O(this,e)}presenterKey(e){this.key(e)}present(e,t={}){this.openDialog({kind:"present",demo:e,from:t.from})}openDialog(e){this.set({dialog:e,...this.state.library&&this.options.launcher?{library:void 0}:{}})}closeDialog(){this.set({dialog:void 0})}openSettings(){this.set({library:"settings"})}showLibrary(e){this.set({library:e})}goTo(e){const t=this.state.session;return"playing"===t.mode&&t.player.goTo(e)}guide(e,t={}){return this.play(e,{...t,guided:!0})}doItForMe(){const e=this.state.session;"playing"===e.mode&&e.player.doItForMe()}async openRemote(){if(!1===this.options.remote)throw new Error("No phone remote in this app");if(this.state.remote)return this.state.remote;const e=this.options.remote?.relay??A;this.remoteLink=await C.open(e,{command:e=>this.fromRemote(e),hello:()=>this.remoteSent="",peers:e=>this.state.remote&&this.set({remote:{...this.state.remote,peers:e}})});const t={url:this.remoteLink.url,svg:F(this.remoteLink.url),peers:0};return this.set({remote:t}),this.remoteTimer=window.setInterval(()=>this.toRemote(!0),1e3),t}closeRemote(){window.clearInterval(this.remoteTimer),this.remoteLink?.close(),this.remoteLink=void 0,this.remoteSent="",this.set({remote:void 0})}fromRemote(e){const t=this.state.session;"playing"===t.mode&&("next"===e.do?t.player.next():"back"===e.do?t.player.back():"goto"===e.do&&void 0!==e.step?t.player.goTo(e.step):"stop"===e.do?this.stop():"toggle"===e.do&&(t.waiting?t.player.next():this.togglePause()))}toRemote(e=!1){if(!this.remoteLink)return;const t=this.remoteState(),{at:s,elapsed:i,stepElapsed:o,...n}=t,a=JSON.stringify(n);(a!==this.remoteSent||e&&t.playing)&&(this.remoteSent=a,this.remoteLink.send(t))}remoteState(){const e=this.state.session,t=Date.now();if("playing"!==e.mode||e.checking)return{playing:!1,title:"",steps:[],step:0,caption:"",paused:!1,waiting:!1,filming:!1,elapsed:0,stepElapsed:0,planned:0,at:t};const s=this.language(),o=this.timing(e.demo,s),a=o.steps.find(t=>t.step===e.step),r=e.player.elapsed();return{playing:!0,title:e.demo.title,steps:e.demo.steps.map((e,t)=>({title:e.title??`Step ${t+1}`,script:n(i(e,s)),...e.notes?{notes:e.notes}:{}})),step:e.step,caption:e.caption,paused:e.paused,waiting:e.waiting,filming:e.filming,elapsed:r,stepElapsed:r-e.player.stepStartedAt,planned:o.duration,...a?{plannedStep:a.end-a.start}:{},at:t}}pack(e){let t=this.packs.get(e.id);return t||(t=(async()=>{const t=await this.store.asset(`narration:${e.id}`);if(t)return M(await t.arrayBuffer());const s=this.options.narration?.(e);if(!s)return;const i=await fetch(s);return i.ok?M(await i.arrayBuffer()):void 0})().catch(()=>{}),this.packs.set(e.id,t)),t}async makePack(e,s=()=>{}){const i=await this.pack(e);this.speech.setPack(i);const o=t(e).flatMap(t=>e.steps.flatMap(e=>n(e.say[t]??"").map(e=>({language:t,text:e})))),a=o.filter((e,t)=>o.findIndex(t=>t.language===e.language&&t.text===e.text)===t),r=[];for(const e of a)s(r.length,a.length),r.push({...await this.speech.packable(e.text,e.language),...e});s(r.length,a.length);const h=L(e.id,r);return await this.store.saveAsset(`narration:${e.id}`,h),this.packs.delete(e.id),h}async downloadPack(e){try{const t=await this.makePack(e,(e,t)=>this.say(`Making the narration pack: ${e} / ${t}`));S(t,`${e.id}.narration.zip`),this.say(`Narration pack: ${Math.round(t.size/1e5)/10} MB, kept here too. Check it in beside ${e.id}.demo.json, for every viewer.`)}catch(e){this.say(`Narration pack: ${e.message}`,!0)}}async dropPack(e){await this.store.saveAsset(`narration:${e.id}`,void 0),this.packs.delete(e.id)}async setMusic(e){await this.store.saveAsset("music",e),this.musicLoaded=void 0;const{music:t}=this.state.settings;this.changeSettings({music:e?{...t,on:!0,track:"file",name:e.name??"music"}:{...t,track:"calm",name:void 0}})}async loadMusic(){const{music:e}=this.state.settings,t="file"===e.track?`file:${e.name}`:e.track;if(this.musicLoaded!==t){if("file"===e.track){const t=await this.store.asset("music");if(!t)return!1;await this.speech.setMusic(t,e.volume).catch(()=>{})}else this.speech.setMusicBuffer(await $(e.track),e.volume);this.musicLoaded=t}return this.speech.setMusicVolume(e.volume),this.speech.hasMusic}async listenToMusic(e=20){if(this.speech.wake(),!await this.loadMusic())return()=>{};this.speech.startMusic();const t=setTimeout(()=>this.speech.stopMusic(),1e3*e);return()=>{clearTimeout(t),this.speech.stopMusic(.6)}}async loop(e,t={},s=0){if(0===e.length)return;this.stopLoop();let i=!1,o=0,n=s;const a=t.idle??this.state.settings.loopIdle,r=t.gap??1500,h=e.map(e=>e.title),p=e=>{if(!e.isTrusted||e.composedPath().includes(this.overlay.host))return;o=performance.now();const t=this.state.session;"playing"===t.mode&&t.looping&&t.player.stop(!0)},l=["pointerdown","keydown","wheel","touchstart"];l.forEach(e=>window.addEventListener(e,p,{capture:!0,passive:!0}));this.looping={demos:e,options:t,stop:()=>{i=!0,l.forEach(e=>window.removeEventListener(e,p,{capture:!0}));const e=this.state.session;"playing"===e.mode&&e.looping&&e.player.stop(),this.set({loop:void 0})}};const d=e=>new Promise(t=>setTimeout(t,e));for(;!i;){const s=e[n%e.length];this.set({loop:{titles:h,index:n%e.length,visitor:!1}});if(!await this.goToStart(s,"loop",void 0,{demos:e,index:n%e.length,gap:t.gap,idle:t.idle,reload:"reload"===t.reset})||i)return;const p=await this.run(s,{looping:!0,catchUp:!1});if(i)break;if(p.error&&performance.now()-o<1e3){for(;!i&&performance.now()-o<a;)this.set({loop:{titles:h,index:n%e.length,visitor:!0,resumesAt:Date.now()+a-(performance.now()-o)}}),await d(1e3);if(i)break;if("reload"===t.reset)return sessionStorage.setItem(this.pendingKey(),JSON.stringify({demo:s,verb:"loop",loop:{demos:e,index:n%e.length,gap:t.gap,idle:t.idle,reload:!0}})),window.location.reload();await(t.reset?.())}else n++,await d(r)}}stopLoop(){this.looping?.stop(),this.looping=void 0}elapsed(){const e=this.state.session;return"playing"===e.mode?e.player.elapsed():void 0}async check(e,t={}){const s=c(e,this.pluginKinds());if(s.length)return{ok:!1,problems:s,failures:[],duration:0,error:"Not a valid demo"};if(this.busy())return{ok:!1,problems:s,failures:[],duration:0,error:`Busy: ${this.state.session.mode}`};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:l(e,{language:t,sayTime:e=>this.speech.duration(e,t),actionTime:e=>{const t=this.pluginAction(e.do);return t?.duration?.(e)??p(e)}})}film(e,t={}){return new Promise(s=>this.whenClicked(e.title,"Film",async()=>this.busy()?s(void 0):(this.say(void 0),await this.goToStart(e,"film")?void s(await this.filmNow(e,t)):s(void 0))))}async filmNow(e,t){const s=t.language??this.language();let o=!1;const a=await R({soundtrack:this.speech.soundtrack(),microphone:t.microphone,crop:this.options.filmElement?.(),...this.filmQuality(),onEnded:()=>{o=!0,this.stop()}});let r;try{const t=e.steps.flatMap(e=>n(i(e,s)));this.setSession({mode:"preparing",title:e.title,text:"Preparing the narration"}),await this.speech.prepare(t,s,(e,t)=>this.updateSession("preparing",{text:`Preparing the narration: ${e} / ${t}`})),o||"preparing"!==this.state.session.mode||(r=await this.run(e,{language:s,filming:a}))}finally{"preparing"===this.state.session.mode&&this.setSession({mode:"idle"})}const{video:p,voice:l}=await a.stop();if(!r||r.error)return void this.say("Stopped."!==r?.error&&r?`Filming failed: ${r.error}`:"Filming stopped: nothing kept.",Boolean(r?.error&&"Stopped."!==r.error));let d=r.timing.cues;l&&"off"===this.state.settings.speech.voice&&(this.setSession({mode:"preparing",title:e.title,text:"Transcribing what was said"}),d=await this.transcribe(l,s).catch(()=>d),this.setSession({mode:"idle"}));const c={id:e.id,blob:p,at:Date.now(),json:JSON.stringify(e),vtt:h(d),timing:r.timing,language:s,look:this.look(s),...l?{voice:l}:{}};return await this.store.saveVideo(c),this.say(`Filmed "${e.title}": ${Math.round(p.size/1e6)} MB, kept here.`),c}filmQuality(){const{frameRate:e,bitrate:t,lines:s,aspect:i,fit:o}=this.state.settings.film;return{frameRate:e,bitrate:t,fit:o,...s?{size:j(s,i)}:{}}}look(e){const{settings:t}=this.state,s=this.options.appTheme?.(),i=this.options.language?.();return{...s?{theme:s}:{},...i?{locale:i}:{},voice:t.speech.voice,language:e,subtitles:t.subtitles}}async transcribe(e,t=this.language()){const{settings:s}=this.state;return 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 R({soundtrack:this.speech.soundtrack(),microphone:o.microphone,crop:this.options.filmElement?.(),...this.filmQuality(),onEnded:()=>{this.stopRecording?.()}}):o.microphone&&(r=await E())}catch(e){return this.say(`Could not start: ${e.message}`,!0),i()}const p=this.options.start?.current(),l=new N(this.targets,this.plugins,n,e=>this.updateSession("recording",e));a?.resume();const d=performance.now();this.setSession({mode:"recording",filming:Boolean(a),microphone:Boolean(r||a&&o.microphone),step:0,caption:"",actions:0}),this.nextStepRecording=()=>l.nextStep(),this.sayRecording=e=>l.say(e),this.stopRecording=async()=>{this.stopRecording=this.nextStepRecording=this.sayRecording=void 0;const c=Boolean(r||a&&o.microphone),m=l.stop(c),g=performance.now()-d;this.setSession({mode:"preparing",title:"Recording",text:"Keeping what was recorded"});try{const[i,o]=await Promise.all([r?.stop(),a?.stop()]),l=i??o?.voice;let d=[];if(l){this.updateSession("preparing",{text:"Transcribing what was said"});try{d=await this.transcribe(l,n);const e=f(m.stepStarts,d);m.steps.forEach((t,s)=>{!t.say[n]&&e[s]&&(t.say[n]=e[s])})}catch(e){this.say(`Transcribing failed: ${e.message}`,!0)}}const c=m.steps.filter(e=>e.actions.length>0||Object.values(e.say).some(Boolean)),u=t.into?e(t.into):{...s("Recorded demo",p),steps:[]},y=t.after??u.steps.length-1,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(d),language:n,look:{...this.look(n),voice:"off",subtitles:!1},timing:{duration:g,steps:m.stepStarts.map((e,t)=>({step:t,start:e,end:m.stepStarts[t+1]??g})),cues:d.map(e=>({...e,step:0})),actions:[]},...o.voice?{voice:o.voice}:{}}),this.setSession({mode:"idle"}),this.say(`Recorded ${c.length} step${1===c.length?"":"s"}${o?", and filmed":""}.`),t.into&&this.state.studio?.demo.id===t.into.id?this.set({studio:{...this.state.studio,recorded:{steps:w.steps,at:Date.now()}}}):this.openStudio(w)}catch(e){this.setSession({mode:"idle"}),this.say(e.message,!0)}i()}}nextStep(){this.nextStepRecording?.()}narrate(e){this.sayRecording?.(e)}async finishRecording(){await(this.stopRecording?.())}link(e){return P(e)}downloadDemo(e,t="json"){if("md"===t)return S(e.scenario??o(e,this.language()),b(e.id,"md"),"text/markdown");const{scenario:s,savedAt:i,...n}=e;S(JSON.stringify(n,null,2)+"\n",b(e.id,"demo.json"),"application/json")}downloadVideo(e,t,s=!1){return"vtt"===s?S(e.vtt,b(t,"vtt"),"text/vtt"):"srt"===s?S(r(a(e.vtt)),b(t,"srt"),"application/x-subrip"):void S(e.blob,b(t,x(e.blob)))}shareVideo(e,t){return T([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{J as DEFAULT_SETTINGS};
1
+ import{copyOf as e,languagesOf as t,newDemo as s,sayOf as i,scenarioOf as o,sentences as n}from"../model/Demo.js";import{parseSubtitles as a,toSrt as r,toVtt as h}from"../model/Subtitles.js";import{actionTime as p,estimate as l}from"../model/Timing.js";import{parseDemo as d,validate as c}from"../model/Validate.js";import{Hand as m}from"../page/Input.js";import{Overlay as g}from"../page/Overlay.js";import{stillPage as u}from"../page/Still.js";import{Targets as y}from"../page/Targets.js";import{Speech as f}from"../speech/Speech.js";import{narrationFor as w,transcribe as v}from"../speech/Transcribe.js";import{Store as k}from"../store/Store.js";import{demoFromLink as S,download as b,fileName as P,linkTo as T,shareFiles as x}from"../store/Share.js";import{extensionOf as E,recordMicrophone as R,startFilming as j,videoSize as $}from"../video/Film.js";import{renderMusic as M}from"../speech/Music.js";import{readPack as L,writePack as K}from"../speech/Pack.js";import{Player as N}from"./Player.js";import{Recorder as B}from"./Recorder.js";import{readAction as D}from"./Read.js";import{mountUI as I}from"../ui/EngineUI.js";import{agentTools as O}from"../agent/Agent.js";import{openPresenter as A}from"../ui/Presenter.js";import{DEFAULT_RELAY as F,qrSvg as C,RemoteLink as J}from"../remote/Remote.js";import{DEFAULT_SETTINGS as U,loadSettings as z,saveSettings as V}from"./Settings.js";const Q=["pointerdown","pointerup","pointermove","pointerover","pointerout","mousedown","mouseup","mousemove","mouseover","mouseout","click","dblclick","contextmenu","wheel","touchstart","touchmove","touchend","keydown","keyup","keypress"];export class DemoEngine{constructor(e){this.options=e,this.listeners=new Set,this.packs=new Map,this.remoteSent="",this.remoteTimer=0,this.getState=()=>this.state,this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e)),this.hintTimer=0,this.targets=new y({...e.targets,labels:e.labels}),this.overlay=new g(e.overlay),this.hand=new m(this.overlay.cursor,()=>this.player?.speedNow??1),this.settingsKey=`protomaze-demo-engine:${e.app}:settings`,this.state={session:{mode:"idle"},settings:z(this.settingsKey),speech:{}},this.speech=new f(()=>this.state.settings.speech,()=>this.set({speech:{...this.speech.state}})),this.store=new k(`protomaze-demo-engine:${e.app}`),this.store.subscribe(()=>this.emit()),this.plugins=e.plugins??[]}emit(){this.state={...this.state},this.listeners.forEach(e=>e()),this.toRemote()}set(e){this.state={...this.state,...e},this.listeners.forEach(e=>e()),this.toRemote()}setSession(e){this.set({session:e})}updateSession(e,t){this.state.session.mode===e&&this.setSession({...this.state.session,...t})}say(e,t=!1){this.set({message:e?{text:e,error:t}:void 0})}changeSettings(e){const t={...this.state.settings,...e};V(this.settingsKey,t),this.set({settings:t}),e.music?.on&&this.loadMusic().catch(()=>{})}language(){const e=this.state.settings.language;return"page"!==e?e:this.options.language?.()??this.options.languages?.[0]??(navigator.language.split("-")[0]||"en")}languages(){return this.options.languages??[this.language()]}pluginKinds(){return this.plugins.flatMap(e=>Object.keys(e.actions??{}))}pluginAction(e){return this.plugins.map(t=>t.actions?.[e]).find(Boolean)}read(e,t){return D(e,this.options.labels,this.plugins,t)}async mount(){if(this.unmount)return;this.overlay.mount();const e=I(this),t=e=>this.key(e);window.addEventListener("keydown",t,!0);const s=e=>this.gate(e);Q.forEach(e=>window.addEventListener(e,s,{capture:!0,passive:!1})),this.state.settings.music.on&&this.loadMusic().catch(()=>{});const i=!1===this.options.agent?void 0:this.options.agent??"demoEngine";i&&(window[i]=O(this)),this.unmount=()=>{e(),window.removeEventListener("keydown",t,!0),Q.forEach(e=>window.removeEventListener(e,s,{capture:!0})),i&&delete window[i],this.overlay.unmount()},await this.arrived()}destroy(){this.closeRemote(),this.stopLoop(),this.stop(),this.unmount?.(),this.unmount=void 0}async arrived(){const e=sessionStorage.getItem(this.pendingKey());if(sessionStorage.removeItem(this.pendingKey()),e){const{demo:t,verb:s,from:i,loop:o}=JSON.parse(e);return"loop"===s&&o?void this.loop(o.demos,{gap:o.gap,idle:o.idle,reset:o.reload?"reload":void 0},o.index):this.whenClicked(t.title,"film"===s?"Film":"Play",()=>"film"===s?this.film(t):this.play(t,{from:i}),!0)}const t=await S();if(t){const e=c(t,this.pluginKinds());return e.length?this.say(`The link's demo: ${e[0].path} ${e[0].message}`,!0):(await this.save(t),this.say(`"${t.title}" came with the link: it is kept here.`),this.openStudio(t))}const s=new URL(window.location.href),i=s.searchParams.get("demo");if(i){s.searchParams.delete("demo"),window.history.replaceState(window.history.state,"",s.toString());const e=(await this.entries()).find(e=>e.demo.id===i);e&&this.whenClicked(e.demo.title,"Play",()=>this.play(e.demo),!0)}}gate(e){const t=this.state.session;if(!e.isTrusted||"playing"!==t.mode||t.paused||t.looping)return;const s=e.composedPath();if(s.includes(this.overlay.host))return;if(t.guided&&t.instruction){const i=t.player.viewerTarget();if(i&&(s.includes(i)||e instanceof KeyboardEvent&&i.contains(document.activeElement)))return;if(!i&&e instanceof KeyboardEvent)return}const i=e.defaultPrevented;e.cancelable&&e.preventDefault(),e.stopImmediatePropagation(),i||"pointerdown"!==e.type&&"keydown"!==e.type&&"wheel"!==e.type||this.hint(t.guided?'Only the ringed part now: or "Do it for me"':"Playing: Space pauses, and the app is yours then. Esc stops.")}hint(e){window.clearTimeout(this.hintTimer),this.set({hint:e}),this.hintTimer=window.setTimeout(()=>this.set({hint:void 0}),3e3)}pendingKey(){return`protomaze-demo-engine:${this.options.app}:pending`}key(e){if(!e.isTrusted)return;const t=e.composedPath(),s=t.some(e=>e instanceof HTMLElement&&(e.isContentEditable||e.matches("input, textarea, select"))),i=t.includes(this.overlay.host),o=this.state.session,n=()=>{e.preventDefault(),e.stopPropagation()};if("ready"!==o.mode)if("recording"!==o.mode){if("l"===e.key.toLowerCase()&&e.ctrlKey&&e.shiftKey&&this.looping)return n(),this.stopLoop();if(!("playing"!==o.mode||o.looping||o.checking||s&&(i||o.guided&&o.instruction))){if("Escape"===e.key)this.stop();else if(" "===e.key||"b"===e.key||"."===e.key)this.togglePause();else if("ArrowRight"===e.key||"Enter"===e.key||"PageDown"===e.key)o.player.next();else if("ArrowLeft"===e.key||"PageUp"===e.key)o.player.back();else if("Home"===e.key)o.player.goTo(0);else if("End"===e.key)o.player.goTo(o.steps-1);else{if(!/^[1-9]$/.test(e.key)||e.ctrlKey||e.metaKey||e.altKey)return;o.player.goTo(Number(e.key)-1)}n()}}else"Escape"!==e.key||s||(n(),this.stopRecording?.());else"Escape"===e.key&&(n(),o.cancel())}async entries(){return await this.store.ready(),this.entriesNow()}entriesNow(){const{demos:e,videos:t}=this.store.get(),s=new Map(e.map(e=>[e.id,e])),i=this.language(),n=(this.options.demos??[]).map(e=>"demo"in e?e:{demo:e,scenario:void 0});return[...n.map(({demo:e,scenario:n})=>{const a=s.get(e.id);return a?{demo:a,scenario:a.scenario??n??o(a,i),origin:"edited",video:t.get(e.id)}:{demo:e,scenario:n??o(e,i),origin:"app",video:t.get(e.id)}}),...e.filter(e=>!n.some(t=>t.demo.id===e.id)).map(e=>({demo:e,scenario:e.scenario??o(e,i),origin:"here",video:t.get(e.id)}))]}async save(t){const s=c(t,this.pluginKinds());if(s.length)throw new Error(`Not a demo: ${s.map(e=>`${e.path} ${e.message}`).join("; ")}`);await this.store.saveDemo(e(t))}async remove(e){await this.store.deleteDemo(e),this.state.studio?.demo.id===e&&this.closeStudio()}parse(e){return d(e,this.pluginKinds())}create(e){return s(e,this.options.start?.current())}openStudio(t){this.set({studio:{demo:e(t),opened:Date.now()}})}closeStudio(){this.set({studio:void 0})}activated(){const e=navigator.userActivation;return!e||e.isActive}whenClicked(e,t,s,i=!1){const o=()=>{this.setSession({mode:"idle"}),this.speech.wake(),s().catch(e=>this.say(e.message,!0))};if(!i&&this.activated())return o();this.setSession({mode:"ready",title:e,verb:t,go:o,cancel:()=>this.setSession({mode:"idle"})})}async goToStart(e,t,s,i){if(!e.start||!this.options.start)return!0;sessionStorage.setItem(this.pendingKey(),JSON.stringify({demo:e,verb:t,from:s,loop:i}));return"reload"!==await this.options.start.go(e.start)&&(sessionStorage.removeItem(this.pendingKey()),!0)}busy(){return"idle"!==this.state.session.mode&&"ready"!==this.state.session.mode}play(e,t={}){return new Promise(s=>this.whenClicked(e.title,"Play",async()=>{if(this.busy())return s(void 0);if(this.say(void 0),!await this.goToStart(e,"play",t.from))return s(void 0);const i=await this.run(e,t);s(i)}))}async run(e,t={}){const{settings:s}=this.state,i=t.language??this.language(),o=s.music.on&&!t.checking&&!t.guided&&await Promise.race([this.loadMusic(),new Promise(e=>setTimeout(()=>e(!1),t.filming?6e4:1500))]);this.speech.setPack(s.usePacks?await this.pack(e):void 0);const n=new N(e,{language:i,subtitles:s.subtitles,waitForPresenter:s.waitForPresenter&&!t.looping,catchUp:s.catchUp,music:Boolean(o),...t},{hand:this.hand,targets:this.targets,overlay:this.overlay,speech:this.speech,plugins:this.plugins,ready:this.options.ready,read:(e,t)=>this.read(e,t),reset:async()=>!e.start||!this.options.start||"reload"!==await this.options.start.go(e.start),update:e=>this.updateSession("playing",e)});this.setSession({mode:"playing",title:e.title,demo:e,steps:e.steps.length,filming:Boolean(t.filming),checking:Boolean(t.checking),guided:Boolean(t.guided),looping:Boolean(t.looping),presenting:Boolean(t.presenting),player:n,step:t.from??0,caption:"",paused:!1,waiting:!1,catchingUp:!1}),this.player=n;const a=await n.play().finally(()=>this.player=void 0);return this.setSession({mode:"idle"}),t.checking||a.navigated||(this.set({lastRun:{json:JSON.stringify(e),language:i,timing:a.timing}}),a.error&&"Stopped."!==a.error&&this.say(a.error,!0)),a}stop(){const e=this.state.session;"playing"===e.mode&&e.player.stop(),"recording"===e.mode&&this.stopRecording?.(),"ready"!==e.mode&&"preparing"!==e.mode||this.setSession({mode:"idle"})}togglePause(){const e=this.state.session;"playing"===e.mode&&(e.paused?e.player.resume():e.player.pause())}resume(){const e=this.state.session;"playing"===e.mode&&e.player.resume()}next(){const e=this.state.session;"playing"===e.mode&&e.player.next()}back(){const e=this.state.session;"playing"===e.mode&&e.player.back()}openPresenter(e={}){return A(this,e)}presenterKey(e){this.key(e)}present(e,t={}){this.openDialog({kind:"present",demo:e,from:t.from})}openDialog(e){this.set({dialog:e,...this.state.library&&this.options.launcher?{library:void 0}:{}})}closeDialog(){this.set({dialog:void 0})}openSettings(){this.set({library:"settings"})}showLibrary(e){this.set({library:e})}goTo(e){const t=this.state.session;return"playing"===t.mode&&t.player.goTo(e)}guide(e,t={}){return this.play(e,{...t,guided:!0})}doItForMe(){const e=this.state.session;"playing"===e.mode&&e.player.doItForMe()}async openRemote(){if(!1===this.options.remote)throw new Error("No phone remote in this app");if(this.state.remote)return this.state.remote;const e=this.options.remote?.relay??F;this.remoteLink=await J.open(e,{command:e=>this.fromRemote(e),hello:()=>this.remoteSent="",peers:e=>this.state.remote&&this.set({remote:{...this.state.remote,peers:e}})});const t={url:this.remoteLink.url,svg:C(this.remoteLink.url),peers:0};return this.set({remote:t}),this.remoteTimer=window.setInterval(()=>this.toRemote(!0),1e3),t}closeRemote(){window.clearInterval(this.remoteTimer),this.remoteLink?.close(),this.remoteLink=void 0,this.remoteSent="",this.set({remote:void 0})}fromRemote(e){const t=this.state.session;"playing"===t.mode&&("next"===e.do?t.player.next():"back"===e.do?t.player.back():"goto"===e.do&&void 0!==e.step?t.player.goTo(e.step):"stop"===e.do?this.stop():"toggle"===e.do&&(t.waiting?t.player.next():this.togglePause()))}toRemote(e=!1){if(!this.remoteLink)return;const t=this.remoteState(),{at:s,elapsed:i,stepElapsed:o,...n}=t,a=JSON.stringify(n);(a!==this.remoteSent||e&&t.playing)&&(this.remoteSent=a,this.remoteLink.send(t))}remoteState(){const e=this.state.session,t=Date.now();if("playing"!==e.mode||e.checking)return{playing:!1,title:"",steps:[],step:0,caption:"",paused:!1,waiting:!1,filming:!1,elapsed:0,stepElapsed:0,planned:0,at:t};const s=this.language(),o=this.timing(e.demo,s),a=o.steps.find(t=>t.step===e.step),r=e.player.elapsed();return{playing:!0,title:e.demo.title,steps:e.demo.steps.map((e,t)=>({title:e.title??`Step ${t+1}`,script:n(i(e,s)),...e.notes?{notes:e.notes}:{}})),step:e.step,caption:e.caption,paused:e.paused,waiting:e.waiting,filming:e.filming,elapsed:r,stepElapsed:r-e.player.stepStartedAt,planned:o.duration,...a?{plannedStep:a.end-a.start}:{},at:t}}pack(e){let t=this.packs.get(e.id);return t||(t=(async()=>{const t=await this.store.asset(`narration:${e.id}`);if(t)return L(await t.arrayBuffer());const s=this.options.narration?.(e);if(!s)return;const i=await fetch(s);return i.ok?L(await i.arrayBuffer()):void 0})().catch(()=>{}),this.packs.set(e.id,t)),t}async makePack(e,s=()=>{}){const i=await this.pack(e);this.speech.setPack(i);const o=t(e).flatMap(t=>e.steps.flatMap(e=>n(e.say[t]??"").map(e=>({language:t,text:e})))),a=o.filter((e,t)=>o.findIndex(t=>t.language===e.language&&t.text===e.text)===t),r=[];for(const e of a)s(r.length,a.length),r.push({...await this.speech.packable(e.text,e.language),...e});s(r.length,a.length);const h=K(e.id,r);return await this.store.saveAsset(`narration:${e.id}`,h),this.packs.delete(e.id),h}async downloadPack(e){try{const t=await this.makePack(e,(e,t)=>this.say(`Making the narration pack: ${e} / ${t}`));b(t,`${e.id}.narration.zip`),this.say(`Narration pack: ${Math.round(t.size/1e5)/10} MB, kept here too. Check it in beside ${e.id}.demo.json, for every viewer.`)}catch(e){this.say(`Narration pack: ${e.message}`,!0)}}async dropPack(e){await this.store.saveAsset(`narration:${e.id}`,void 0),this.packs.delete(e.id)}async setMusic(e){await this.store.saveAsset("music",e),this.musicLoaded=void 0;const{music:t}=this.state.settings;this.changeSettings({music:e?{...t,on:!0,track:"file",name:e.name??"music"}:{...t,track:"calm",name:void 0}})}async loadMusic(){const{music:e}=this.state.settings,t="file"===e.track?`file:${e.name}`:e.track;if(this.musicLoaded!==t){if("file"===e.track){const t=await this.store.asset("music");if(!t)return!1;await this.speech.setMusic(t,e.volume).catch(()=>{})}else this.speech.setMusicBuffer(await M(e.track),e.volume);this.musicLoaded=t}return this.speech.setMusicVolume(e.volume),this.speech.hasMusic}async listenToMusic(e=20){if(this.speech.wake(),!await this.loadMusic())return()=>{};this.speech.startMusic();const t=setTimeout(()=>this.speech.stopMusic(),1e3*e);return()=>{clearTimeout(t),this.speech.stopMusic(.6)}}async loop(e,t={},s=0){if(0===e.length)return;this.stopLoop();let i=!1,o=0,n=s;const a=t.idle??this.state.settings.loopIdle,r=t.gap??1500,h=e.map(e=>e.title),p=e=>{if(!e.isTrusted||e.composedPath().includes(this.overlay.host))return;o=performance.now();const t=this.state.session;"playing"===t.mode&&t.looping&&t.player.stop(!0)},l=["pointerdown","keydown","wheel","touchstart"];l.forEach(e=>window.addEventListener(e,p,{capture:!0,passive:!0}));this.looping={demos:e,options:t,stop:()=>{i=!0,l.forEach(e=>window.removeEventListener(e,p,{capture:!0}));const e=this.state.session;"playing"===e.mode&&e.looping&&e.player.stop(),this.set({loop:void 0})}};const d=e=>new Promise(t=>setTimeout(t,e));for(;!i;){const s=e[n%e.length];this.set({loop:{titles:h,index:n%e.length,visitor:!1}});if(!await this.goToStart(s,"loop",void 0,{demos:e,index:n%e.length,gap:t.gap,idle:t.idle,reload:"reload"===t.reset})||i)return;const p=await this.run(s,{looping:!0,catchUp:!1});if(i)break;if(p.error&&performance.now()-o<1e3){for(;!i&&performance.now()-o<a;)this.set({loop:{titles:h,index:n%e.length,visitor:!0,resumesAt:Date.now()+a-(performance.now()-o)}}),await d(1e3);if(i)break;if("reload"===t.reset)return sessionStorage.setItem(this.pendingKey(),JSON.stringify({demo:s,verb:"loop",loop:{demos:e,index:n%e.length,gap:t.gap,idle:t.idle,reload:!0}})),window.location.reload();await(t.reset?.())}else n++,await d(r)}}stopLoop(){this.looping?.stop(),this.looping=void 0}elapsed(){const e=this.state.session;return"playing"===e.mode?e.player.elapsed():void 0}async check(e,t={}){const s=c(e,this.pluginKinds());if(s.length)return{ok:!1,problems:s,failures:[],duration:0,error:"Not a valid demo"};if(this.busy())return{ok:!1,problems:s,failures:[],duration:0,error:`Busy: ${this.state.session.mode}`};const{animations:i,fromStart:o,...n}=t,a=i?()=>{}:u();try{if(!1!==o&&e.start&&this.options.start){if("reload"===await this.options.start.go(e.start))return{ok:!1,problems:s,failures:[],duration:0,error:"Its start reloads the page: check again once it is back"}}const t=await this.run(e,{...n,speed:n.speed??8,keepGoing:!0,checking:!0,catchUp:!0,subtitles:!1}),i=t.failures.map(t=>({...t,action:e.steps[t.step].actions[t.index]}));return{ok:!t.error&&0===i.length,error:t.error,failures:i,problems:s,duration:t.timing.duration}}finally{a()}}timing(e,t=this.language()){const s=this.state.lastRun;return s&&s.language===t&&s.json===JSON.stringify(e)&&s.timing.steps.length===e.steps.length?s.timing:l(e,{language:t,sayTime:e=>this.speech.duration(e,t),actionTime:e=>{const t=this.pluginAction(e.do);return t?.duration?.(e)??p(e)}})}film(e,t={}){return new Promise(s=>this.whenClicked(e.title,"Film",async()=>this.busy()?s(void 0):(this.say(void 0),await this.goToStart(e,"film")?void s(await this.filmNow(e,t)):s(void 0))))}async filmNow(e,t){const s=t.language??this.language();let o=!1;const a=await j({soundtrack:this.speech.soundtrack(),microphone:t.microphone,crop:this.options.filmElement?.(),...this.filmQuality(),onEnded:()=>{o=!0,this.stop()}});let r;try{const t=e.steps.flatMap(e=>n(i(e,s)));this.setSession({mode:"preparing",title:e.title,text:"Preparing the narration"}),await this.speech.prepare(t,s,(e,t)=>this.updateSession("preparing",{text:`Preparing the narration: ${e} / ${t}`})),o||"preparing"!==this.state.session.mode||(r=await this.run(e,{language:s,filming:a}))}finally{"preparing"===this.state.session.mode&&this.setSession({mode:"idle"})}const{video:p,voice:l}=await a.stop();if(!r||r.error)return void this.say("Stopped."!==r?.error&&r?`Filming failed: ${r.error}`:"Filming stopped: nothing kept.",Boolean(r?.error&&"Stopped."!==r.error));let d=r.timing.cues;l&&"off"===this.state.settings.speech.voice&&(this.setSession({mode:"preparing",title:e.title,text:"Transcribing what was said"}),d=await this.transcribe(l,s).catch(()=>d),this.setSession({mode:"idle"}));const c={id:e.id,blob:p,at:Date.now(),json:JSON.stringify(e),vtt:h(d),timing:r.timing,language:s,look:this.look(s),...l?{voice:l}:{}};return await this.store.saveVideo(c),this.say(`Filmed "${e.title}": ${Math.round(p.size/1e6)} MB, kept here.`),c}filmQuality(){const{frameRate:e,bitrate:t,lines:s,aspect:i,fit:o}=this.state.settings.film;return{frameRate:e,bitrate:t,fit:o,...s?{size:$(s,i)}:{}}}look(e){const{settings:t}=this.state,s=this.options.appTheme?.(),i=this.options.language?.();return{...s?{theme:s}:{},...i?{locale:i}:{},voice:t.speech.voice,language:e,subtitles:t.subtitles}}async transcribe(e,t=this.language()){const{settings:s}=this.state;return v(e,{language:t,with:s.transcriber,model:s.whisperModel,elevenLabsKey:s.speech.elevenlabs.key,progress:e=>this.set({speech:e<1?{loading:e}:{}})})}record(e={}){return new Promise(t=>this.whenClicked(e.into?.title??"New demo","Record",async()=>{if(this.busy())return t();this.say(void 0),await this.recordNow(e,t)}))}async recordNow(t,i){const{settings:o}=this.state,n=this.language();let a,r;try{o.filmRecording?a=await j({soundtrack:this.speech.soundtrack(),microphone:o.microphone,crop:this.options.filmElement?.(),...this.filmQuality(),onEnded:()=>{this.stopRecording?.()}}):o.microphone&&(r=await R())}catch(e){return this.say(`Could not start: ${e.message}`,!0),i()}const p=this.options.start?.current(),l=new B(this.targets,this.plugins,n,e=>this.updateSession("recording",e));a?.resume();const d=performance.now();this.setSession({mode:"recording",filming:Boolean(a),microphone:Boolean(r||a&&o.microphone),step:0,caption:"",actions:0}),this.nextStepRecording=()=>l.nextStep(),this.sayRecording=e=>l.say(e),this.stopRecording=async()=>{this.stopRecording=this.nextStepRecording=this.sayRecording=void 0;const c=Boolean(r||a&&o.microphone),m=l.stop(c),g=performance.now()-d;this.setSession({mode:"preparing",title:"Recording",text:"Keeping what was recorded"});try{const[i,o]=await Promise.all([r?.stop(),a?.stop()]),l=i??o?.voice;let d=[];if(l){this.updateSession("preparing",{text:"Transcribing what was said"});try{d=await this.transcribe(l,n);const e=w(m.stepStarts,d);m.steps.forEach((t,s)=>{!t.say[n]&&e[s]&&(t.say[n]=e[s])})}catch(e){this.say(`Transcribing failed: ${e.message}`,!0)}}const c=m.steps.filter(e=>e.actions.length>0||Object.values(e.say).some(Boolean)),u=t.into?e(t.into):{...s("Recorded demo",p),steps:[]},y=t.after??u.steps.length-1,f={...u,steps:[...u.steps.slice(0,y+1),...c,...u.steps.slice(y+1)]};0===f.steps.length&&f.steps.push({say:{},actions:[]}),o&&await this.store.saveVideo({id:f.id,blob:o.video,at:Date.now(),json:JSON.stringify(f),vtt:h(d),language:n,look:{...this.look(n),voice:"off",subtitles:!1},timing:{duration:g,steps:m.stepStarts.map((e,t)=>({step:t,start:e,end:m.stepStarts[t+1]??g})),cues:d.map(e=>({...e,step:0})),actions:[]},...o.voice?{voice:o.voice}:{}}),this.setSession({mode:"idle"}),this.say(`Recorded ${c.length} step${1===c.length?"":"s"}${o?", and filmed":""}.`),t.into&&this.state.studio?.demo.id===t.into.id?this.set({studio:{...this.state.studio,recorded:{steps:f.steps,at:Date.now()}}}):this.openStudio(f)}catch(e){this.setSession({mode:"idle"}),this.say(e.message,!0)}i()}}nextStep(){this.nextStepRecording?.()}narrate(e){this.sayRecording?.(e)}async finishRecording(){await(this.stopRecording?.())}link(e){return T(e)}downloadDemo(e,t="json"){if("md"===t)return b(e.scenario??o(e,this.language()),P(e.id,"md"),"text/markdown");const{scenario:s,savedAt:i,...n}=e;b(JSON.stringify(n,null,2)+"\n",P(e.id,"demo.json"),"application/json")}downloadVideo(e,t,s=!1){return"vtt"===s?b(e.vtt,P(t,"vtt"),"text/vtt"):"srt"===s?b(r(a(e.vtt)),P(t,"srt"),"application/x-subrip"):void b(e.blob,P(t,E(e.blob)))}shareVideo(e,t){return x([new File([e.blob],P(t,E(e.blob)),{type:e.blob.type}),new File([e.vtt],P(t,"vtt"),{type:"text/vtt"})],t)}languagesOf(e){return t(e)}}export{U as DEFAULT_SETTINGS};
@@ -80,6 +80,8 @@ export declare class Player {
80
80
  private t0;
81
81
  private silence;
82
82
  private speed;
83
+ /** How long a target may take to show: shorter in the cleanup, where what is absent is skipped. */
84
+ private findTimeout;
83
85
  /** On to the next step: what is left of this one quickly, silently. */
84
86
  private hurrying;
85
87
  /** A step to go to, asked for by the presenter. */
@@ -144,7 +146,10 @@ export declare class Player {
144
146
  * ("Do it for me", next), and the demo does it.
145
147
  */
146
148
  private viewerDoes;
147
- /** The demo's cleanup, quick and unseen, whatever fails: the app as the demo found it. */
149
+ /**
150
+ * The demo's cleanup, quick and unseen, whatever fails: the app as the demo found it. A target not
151
+ * there within half a second is skipped, so a cleanup can list every reset that might be needed.
152
+ */
148
153
  private cleanup;
149
154
  /** Under a card naming the step: what the audience need not see happen. */
150
155
  private covered;
package/engine/Player.js CHANGED
@@ -1 +1 @@
1
- import{DEFAULT_WAIT as t,isBuiltIn as e,isPresent as s,sayOf as i,sentences as a}from"../model/Demo.js";import{readingTime as o}from"../model/Timing.js";import{at as n}from"../page/Input.js";import{pointIn as r}from"../page/Targets.js";import{isGuided as h,waitForViewer as p}from"./Guided.js";const c=t=>new Promise(e=>setTimeout(e,t));export class Player{constructor(t,e,s){this.demo=t,this.options=e,this.context=s,this.stopped=!1,this.held=0,this.t0=performance.now(),this.silence=()=>{},this.hurrying=!1,this.dropping=!1,this.navigated=!1,this.stepNow=0,this.stepStart=0,this.last=0,this.skipViewer=()=>{},this.viewerDid=!1,this.keepApp=!1,this.waitingNow=!1,this.sleep=async t=>{let e=t/this.speed;for(;e>0&&!this.stopped&&!this.hurrying&&!this.dropping;){if(void 0!==this.pausedAt){await c(50);continue}const t=Math.min(e,50),s=performance.now();await c(t),e-=performance.now()-s}},this.speed=e.speed??1}elapsed(){return(this.pausedAt??performance.now())-this.t0-this.held}get paused(){return void 0!==this.pausedAt}pause(t=!1){void 0===this.pausedAt&&(this.pausedAt=performance.now(),this.waitingNow=t,this.context.speech.pause(),this.options.filming?.pause(),this.context.update({paused:!0,waiting:t}))}resume(){void 0!==this.pausedAt&&(this.held+=performance.now()-this.pausedAt,this.pausedAt=void 0,this.context.speech.resume(),this.options.filming?.resume(),this.context.update({paused:!1,waiting:!1}))}stop(t=!1){this.stopped=!0,this.keepApp=t,this.silence(),this.skipViewer(),this.resume()}viewerTarget(){return this.target?.()}get speedNow(){return this.hurrying?20:this.speed}next(){if(this.waiting)return this.resume();this.goTo(this.stepNow+1)}back(){const t=!this.waiting&&this.elapsed()-this.stepStart<3e3;this.goTo(t?this.stepNow-1:this.stepNow)}goTo(t){if(this.options.filming||this.stopped)return!1;const e=Math.max(0,Math.min(t,this.last));return!(e>this.stepNow&&this.stepNow===this.last)&&(this.jump=e,this.navigated=!0,e>this.stepNow?this.hurrying=!0:this.dropping=!0,this.silence(),this.skipViewer(),this.resume(),!0)}get step(){return this.stepNow}get stepStartedAt(){return this.stepStart}get waiting(){return void 0!==this.pausedAt&&this.waitingNow}doItForMe(){this.skipViewer()}async whilePaused(){for(;void 0!==this.pausedAt&&!this.stopped;)await c(50)}async find(t){const e=await this.context.targets.find(t,1e4,()=>this.stopped);if(!e)throw new Error(this.stopped?"Stopped.":`Not found: ${describeTarget(t)}`);return e}follow(t,e){let s=e;return()=>(s?.isConnected||(s=this.context.targets.matches(t)[t.index??0]),s)}async play(){const{demo:e,options:n,context:r}=this,p=n.language,d=Math.max(0,Math.min(n.from??0,e.steps.length-1)),l=Math.min(n.to??e.steps.length-1,e.steps.length-1),u=this.speed>1,w={duration:0,steps:[],cues:[],actions:[]},g=[];let f;const m=new Set;try{this.last=l,d>0&&!1!==n.catchUp&&await this.catchUp(0,d);const f=e.steps.map(t=>u?[]:a(i(t,p))),y=[...f.slice(d),...f.slice(0,d)].flat();y.forEach(t=>r.speech.make(t,p)?.catch(()=>{}));const v=y.map(t=>r.speech.make(t,p))[0]?.catch(()=>{});v&&await Promise.race([v,c(n.filming?6e5:3e3)]),await(r.ready?.()),this.t0=performance.now(),this.held=0,n.filming?.resume(),n.music&&!u&&r.speech.startMusic();let x=d;for(;x<=l&&!this.stopped;){const i=e.steps[x];this.stepNow=x,r.update({step:x,caption:""}),r.overlay.raise();const a=this.elapsed();this.stepStart=a;const c=[],y=f[x].map((t,e)=>new Promise(t=>c[e]=t));let v=!1,k=()=>{};const b=new Promise(t=>k=t),$=async()=>{for(const[t,e]of f[x].entries()){if(await this.whilePaused(),this.stopped||this.hurrying||this.dropping)break;const s=await r.speech.say(e,p,n.filming?1/0:0===t&&x===d?0:1500);await this.whilePaused();const i=this.elapsed();c[t](),!1!==n.subtitles&&r.overlay.subtitle(e),r.update({caption:e}),s?(this.silence=s.stop,this.hurrying&&s.stop(),await s.done):await this.sleep(o(e)),w.cues.push({step:x,start:i,end:this.elapsed(),text:e})}v=!0,c.forEach(t=>t()),k(),r.overlay.subtitle(void 0),r.update({caption:""})},N=async()=>{for(const[e,a]of i.actions.entries()){if(this.stopped||this.dropping)break;if(void 0===a.cue||v||u||await(y[a.cue]??b),await this.sleep(a.wait??t),await this.whilePaused(),this.stopped||this.dropping)break;if(this.hurrying&&s(a))continue;const i=this.elapsed(),o={step:x,index:e,start:i,end:i};w.actions.push(o);try{const t=n.guided&&h(a)&&!this.hurrying;t&&await this.viewerDoes(a);const e=t&&this.viewerDid?void 0:await this.perform(a,p);if(o.end=this.elapsed(),e){const t=()=>{m.delete(t)&&(e(),o.end=this.elapsed())};m.add(t);const s=a.for;void 0!==s&&this.sleep(s).then(t)}"clear"===a.do&&[...m].forEach(t=>t())}catch(t){const s=t.message;if(o.end=this.elapsed(),o.error=s,this.stopped)break;if(!n.keepGoing)throw new Error(`Step ${x+1}, action ${e+1} (${a.do}): ${s}`);g.push({step:x,index:e,error:s})}}};if(await Promise.all([$(),N()]),i.hold&&await this.sleep(i.hold),[...m].forEach(t=>t()),w.steps.push({step:x,start:a,end:this.elapsed()}),this.hurrying=!1,void 0===this.jump&&(i.pause||n.waitForPresenter)&&x<l&&!this.stopped&&!u&&(this.pause(!0),await this.whilePaused()),this.stopped)break;if(void 0!==this.jump){const t=this.jump;this.jump=void 0,this.dropping=!1,t<=x?await this.rewind(t):t>x+1&&await this.covered(t,()=>this.catchUp(x+1,t)),x=t;continue}x++}this.stopped||await this.sleep(u?0:1e3)}catch(t){f=t.message}finally{[...m].forEach(t=>t()),r.speech.stopMusic(),this.keepApp||await this.cleanup(),r.update({instruction:void 0}),r.overlay.clear(),r.overlay.subtitle(void 0),r.overlay.hideCursor(),r.hand.reset(),this.stopped&&(f??(f="Stopped."))}return w.duration=this.elapsed(),{timing:w,error:f,failures:g,...this.navigated?{navigated:!0}:{}}}async viewerDoes(t){this.viewerDid=!1;const e=t.target,s=e?await this.find(e):void 0;s?.scrollIntoView({block:"nearest",inline:"nearest"});const i=this.context.read(t,s);this.target=s&&e?this.follow(e,s):void 0;const a=s&&e?[this.context.overlay.show({kind:"ring",element:this.follow(e,s)}),this.context.overlay.show({kind:"callout",text:i,element:this.follow(e,s)})]:[this.context.overlay.show({kind:"callout",text:i,corner:"top-right"})];this.context.update({instruction:i});const o=p(t,this.context.targets);let n=!1;this.skipViewer=()=>{n=!0,o.cancel()},await o.done,this.target=void 0,this.skipViewer=()=>{},a.forEach(t=>t()),this.context.update({instruction:void 0}),this.viewerDid=!n}async cleanup(){const e=this.demo.cleanup??[];if(0===e.length)return;const[i,a]=[this.stopped,this.speed];this.stopped=!1,this.hurrying=!1,this.speed=Math.max(a,12),this.context.update({caption:""}),this.context.overlay.quiet=!0;try{for(const i of e)s(i)||(await this.sleep(Math.min(i.wait??t,1e3)),await this.perform(i,this.options.language).catch(()=>{}))}finally{this.context.overlay.quiet=!1,[this.stopped,this.speed]=[i,a]}}async covered(t,e){const s=this.demo.steps[t]?.title,i=this.context.overlay.show({kind:"card",title:`${t+1}${s?` · ${s}`:""}`,text:`${t+1} / ${this.last+1}`});this.context.overlay.quiet=!0,this.context.overlay.subtitle(void 0);try{await e()}finally{this.context.overlay.quiet=!1,this.context.overlay.hideCursor(),await c(250),i()}}async rewind(t){await this.covered(t,async()=>{this.context.overlay.clear(),await this.cleanup(),await(this.context.reset?.()),await this.catchUp(0,t)})}async catchUp(e,i){const a=this.speed;this.speed=Math.max(a,12),this.context.update({catchingUp:!0});try{for(let a=e;a<i&&!this.stopped;a++){this.context.update({step:a});for(const e of this.demo.steps[a].actions){if(this.stopped)return;if(!s(e)){await this.sleep(Math.min(e.wait??t,1500));try{await this.perform(e,this.options.language)}catch(t){throw new Error(`Catching up, step ${a+1}: ${t.message}`)}}}}await this.sleep(1500)}finally{this.speed=a,this.context.update({catchingUp:!1})}}async perform(t,s){const{hand:i,overlay:a}=this.context;if(!e(t)){const e=this.context.plugins.map(e=>e.actions?.[t.do]).find(Boolean);if(!e)throw new Error(`No plugin plays "${t.do}"`);const o={hand:i,overlay:a,targets:this.context.targets,language:s,speed:this.speed,find:t=>this.find(t),sleep:this.sleep,stopped:()=>this.stopped};return void await e.play(t,o)}const o=t=>a.show(t);switch(t.do){case"click":{const e=await this.find(t.target);return e.scrollIntoView({block:"nearest",inline:"nearest"}),i.click(e,n(e,t.at),t)}case"hover":{const e=await this.find(t.target);return e.scrollIntoView({block:"nearest",inline:"nearest"}),i.point(e,n(e,t.at))}case"type":{const e=await this.find(t.target);return e.scrollIntoView({block:"nearest",inline:"nearest"}),await i.point(e,n(e)),i.type(e,t.text)}case"key":{const e=t.target?await this.find(t.target):void 0;return this.speed<=1&&a.keys(t.key),i.key(t.key,e)}case"select":{const e=await this.find(t.target);if(!(e instanceof HTMLSelectElement))throw new Error("Not a <select>: click its options instead");return e.scrollIntoView({block:"nearest",inline:"nearest"}),i.select(e,t.option,n(e))}case"drag":{const e=await this.find(t.target);e.scrollIntoView({block:"nearest",inline:"nearest"});const s=n(e,t.at),a=t.to.target?await this.find(t.to.target):e;return i.drag(e,s,r(a,t.to.at),t)}case"scroll":{const e=t.target?await this.find(t.target):void 0;return i.scroll(e,t.by)}case"waitFor":{const e=performance.now()+(t.timeout??1e4);for(;!this.stopped;){if(this.context.targets.matches(t.target).some(t=>t.getClientRects().length>0)!==Boolean(t.gone))return;if(performance.now()>e)throw new Error(`${t.gone?"Still there":"Not found"}: ${describeTarget(t.target)}`);await c(100)}return}case"clear":return void a.clear();case"card":return o({kind:"card",title:t.title,text:t.text});case"callout":{const e=t.target?await this.find(t.target):void 0;return o({kind:"callout",text:t.text,side:t.side,corner:t.corner,element:e&&this.follow(t.target,e)})}default:{const e=await this.find(t.target);e.scrollIntoView({block:"nearest",inline:"nearest"});const s=this.follow(t.target,e);switch(t.do){case"spotlight":return o({kind:"spotlight",element:s,text:t.text,padding:t.padding});case"ring":return o({kind:"ring",element:s,text:t.text,color:t.color,shape:t.shape,padding:t.padding});case"arrow":return o({kind:"arrow",element:s,text:t.text,from:t.from,color:t.color});case"blur":return o({kind:"blur",element:s});case"zoom":{const e=o({kind:"zoom",element:s,scale:t.scale});return await this.sleep(700),e}}}}}}export function describeTarget(t){const e=t.key??t.text;return`${e?`"${e}" `:""}${t.css}${t.index?` #${t.index+1}`:""}`}
1
+ import{DEFAULT_WAIT as t,isBuiltIn as e,isPresent as s,sayOf as i,sentences as o}from"../model/Demo.js";import{readingTime as a}from"../model/Timing.js";import{at as n}from"../page/Input.js";import{pointIn as r}from"../page/Targets.js";import{isGuided as h,waitForViewer as p}from"./Guided.js";const c=t=>new Promise(e=>setTimeout(e,t));export class Player{constructor(t,e,s){this.demo=t,this.options=e,this.context=s,this.stopped=!1,this.held=0,this.t0=performance.now(),this.silence=()=>{},this.findTimeout=1e4,this.hurrying=!1,this.dropping=!1,this.navigated=!1,this.stepNow=0,this.stepStart=0,this.last=0,this.skipViewer=()=>{},this.viewerDid=!1,this.keepApp=!1,this.waitingNow=!1,this.sleep=async t=>{let e=t/this.speed;for(;e>0&&!this.stopped&&!this.hurrying&&!this.dropping;){if(void 0!==this.pausedAt){await c(50);continue}const t=Math.min(e,50),s=performance.now();await c(t),e-=performance.now()-s}},this.speed=e.speed??1}elapsed(){return(this.pausedAt??performance.now())-this.t0-this.held}get paused(){return void 0!==this.pausedAt}pause(t=!1){void 0===this.pausedAt&&(this.pausedAt=performance.now(),this.waitingNow=t,this.context.speech.pause(),this.options.filming?.pause(),this.context.update({paused:!0,waiting:t}))}resume(){void 0!==this.pausedAt&&(this.held+=performance.now()-this.pausedAt,this.pausedAt=void 0,this.context.speech.resume(),this.options.filming?.resume(),this.context.update({paused:!1,waiting:!1}))}stop(t=!1){this.stopped=!0,this.keepApp=t,this.silence(),this.skipViewer(),this.resume()}viewerTarget(){return this.target?.()}get speedNow(){return this.hurrying?20:this.speed}next(){if(this.waiting)return this.resume();this.goTo(this.stepNow+1)}back(){const t=!this.waiting&&this.elapsed()-this.stepStart<3e3;this.goTo(t?this.stepNow-1:this.stepNow)}goTo(t){if(this.options.filming||this.stopped)return!1;const e=Math.max(0,Math.min(t,this.last));return!(e>this.stepNow&&this.stepNow===this.last)&&(this.jump=e,this.navigated=!0,e>this.stepNow?this.hurrying=!0:this.dropping=!0,this.silence(),this.skipViewer(),this.resume(),!0)}get step(){return this.stepNow}get stepStartedAt(){return this.stepStart}get waiting(){return void 0!==this.pausedAt&&this.waitingNow}doItForMe(){this.skipViewer()}async whilePaused(){for(;void 0!==this.pausedAt&&!this.stopped;)await c(50)}async find(t){const e=await this.context.targets.find(t,this.findTimeout,()=>this.stopped);if(!e)throw new Error(this.stopped?"Stopped.":`Not found: ${describeTarget(t)}`);return e}follow(t,e){let s=e;return()=>(s?.isConnected||(s=this.context.targets.matches(t)[t.index??0]),s)}async play(){const{demo:e,options:n,context:r}=this,p=n.language,d=Math.max(0,Math.min(n.from??0,e.steps.length-1)),l=Math.min(n.to??e.steps.length-1,e.steps.length-1),u=this.speed>1,w={duration:0,steps:[],cues:[],actions:[]},g=[];let f;const m=new Set;try{this.last=l,d>0&&!1!==n.catchUp&&await this.catchUp(0,d);const f=e.steps.map(t=>u?[]:o(i(t,p))),y=[...f.slice(d),...f.slice(0,d)].flat();y.forEach(t=>r.speech.make(t,p)?.catch(()=>{}));const v=y.map(t=>r.speech.make(t,p))[0]?.catch(()=>{});v&&await Promise.race([v,c(n.filming?6e5:3e3)]),await(r.ready?.()),this.t0=performance.now(),this.held=0,n.filming?.resume(),n.music&&!u&&r.speech.startMusic();let x=d;for(;x<=l&&!this.stopped;){const i=e.steps[x];this.stepNow=x,r.update({step:x,caption:""}),r.overlay.raise();const o=this.elapsed();this.stepStart=o;const c=[],y=f[x].map((t,e)=>new Promise(t=>c[e]=t));let v=!1,k=()=>{};const b=new Promise(t=>k=t),$=async()=>{for(const[t,e]of f[x].entries()){if(await this.whilePaused(),this.stopped||this.hurrying||this.dropping)break;const s=await r.speech.say(e,p,n.filming?1/0:0===t&&x===d?0:1500);await this.whilePaused();const i=this.elapsed();c[t](),!1!==n.subtitles&&r.overlay.subtitle(e),r.update({caption:e}),s?(this.silence=s.stop,this.hurrying&&s.stop(),await s.done):await this.sleep(a(e)),w.cues.push({step:x,start:i,end:this.elapsed(),text:e})}v=!0,c.forEach(t=>t()),k(),r.overlay.subtitle(void 0),r.update({caption:""})},N=async()=>{for(const[e,o]of i.actions.entries()){if(this.stopped||this.dropping)break;if(void 0===o.cue||v||u||await(y[o.cue]??b),await this.sleep(o.wait??t),await this.whilePaused(),this.stopped||this.dropping)break;if(this.hurrying&&s(o))continue;const i=this.elapsed(),a={step:x,index:e,start:i,end:i};w.actions.push(a);try{const t=n.guided&&h(o)&&!this.hurrying;t&&await this.viewerDoes(o);const e=t&&this.viewerDid?void 0:await this.perform(o,p);if(a.end=this.elapsed(),e){const t=()=>{m.delete(t)&&(e(),a.end=this.elapsed())};m.add(t);const s=o.for;void 0!==s&&this.sleep(s).then(t)}"clear"===o.do&&[...m].forEach(t=>t())}catch(t){const s=t.message;if(a.end=this.elapsed(),a.error=s,this.stopped)break;if(!n.keepGoing)throw new Error(`Step ${x+1}, action ${e+1} (${o.do}): ${s}`);g.push({step:x,index:e,error:s})}}};if(await Promise.all([$(),N()]),i.hold&&await this.sleep(i.hold),[...m].forEach(t=>t()),w.steps.push({step:x,start:o,end:this.elapsed()}),this.hurrying=!1,void 0===this.jump&&(i.pause||n.waitForPresenter)&&x<l&&!this.stopped&&!u&&(this.pause(!0),await this.whilePaused()),this.stopped)break;if(void 0!==this.jump){const t=this.jump;this.jump=void 0,this.dropping=!1,t<=x?await this.rewind(t):t>x+1&&await this.covered(t,()=>this.catchUp(x+1,t)),x=t;continue}x++}this.stopped||await this.sleep(u?0:1e3)}catch(t){f=t.message}finally{[...m].forEach(t=>t()),r.speech.stopMusic(),this.keepApp||await this.cleanup(),r.update({instruction:void 0}),r.overlay.clear(),r.overlay.subtitle(void 0),r.overlay.hideCursor(),r.hand.reset(),this.stopped&&(f??(f="Stopped."))}return w.duration=this.elapsed(),{timing:w,error:f,failures:g,...this.navigated?{navigated:!0}:{}}}async viewerDoes(t){this.viewerDid=!1;const e=t.target,s=e?await this.find(e):void 0;s?.scrollIntoView({block:"nearest",inline:"nearest"});const i=this.context.read(t,s);this.target=s&&e?this.follow(e,s):void 0;const o=s&&e?[this.context.overlay.show({kind:"ring",element:this.follow(e,s)}),this.context.overlay.show({kind:"callout",text:i,element:this.follow(e,s)})]:[this.context.overlay.show({kind:"callout",text:i,corner:"top-right"})];this.context.update({instruction:i});const a=p(t,this.context.targets);let n=!1;this.skipViewer=()=>{n=!0,a.cancel()},await a.done,this.target=void 0,this.skipViewer=()=>{},o.forEach(t=>t()),this.context.update({instruction:void 0}),this.viewerDid=!n}async cleanup(){const e=this.demo.cleanup??[];if(0===e.length)return;const[i,o]=[this.stopped,this.speed];this.stopped=!1,this.hurrying=!1,this.speed=Math.max(o,12),this.findTimeout=500,this.context.update({caption:""}),this.context.overlay.quiet=!0;try{for(const i of e)s(i)||(await this.sleep(Math.min(i.wait??t,1e3)),await this.perform(i,this.options.language).catch(()=>{}))}finally{this.context.overlay.quiet=!1,this.findTimeout=1e4,[this.stopped,this.speed]=[i,o]}}async covered(t,e){const s=this.demo.steps[t]?.title,i=this.context.overlay.show({kind:"card",title:`${t+1}${s?` · ${s}`:""}`,text:`${t+1} / ${this.last+1}`});this.context.overlay.quiet=!0,this.context.overlay.subtitle(void 0);try{await e()}finally{this.context.overlay.quiet=!1,this.context.overlay.hideCursor(),await c(250),i()}}async rewind(t){await this.covered(t,async()=>{this.context.overlay.clear(),await this.cleanup(),await(this.context.reset?.()),await this.catchUp(0,t)})}async catchUp(e,i){const o=this.speed;this.speed=Math.max(o,12),this.context.update({catchingUp:!0});try{for(let o=e;o<i&&!this.stopped;o++){this.context.update({step:o});for(const e of this.demo.steps[o].actions){if(this.stopped)return;if(!s(e)){await this.sleep(Math.min(e.wait??t,1500));try{await this.perform(e,this.options.language)}catch(t){throw new Error(`Catching up, step ${o+1}: ${t.message}`)}}}}await this.sleep(1500)}finally{this.speed=o,this.context.update({catchingUp:!1})}}async perform(t,s){const{hand:i,overlay:o}=this.context;if(!e(t)){const e=this.context.plugins.map(e=>e.actions?.[t.do]).find(Boolean);if(!e)throw new Error(`No plugin plays "${t.do}"`);const a={hand:i,overlay:o,targets:this.context.targets,language:s,speed:this.speed,find:t=>this.find(t),sleep:this.sleep,stopped:()=>this.stopped};return void await e.play(t,a)}const a=t=>o.show(t);switch(t.do){case"click":{const e=await this.find(t.target);return e.scrollIntoView({block:"nearest",inline:"nearest"}),i.click(e,n(e,t.at),t)}case"hover":{const e=await this.find(t.target);return e.scrollIntoView({block:"nearest",inline:"nearest"}),i.point(e,n(e,t.at))}case"type":{const e=await this.find(t.target);return e.scrollIntoView({block:"nearest",inline:"nearest"}),await i.point(e,n(e)),i.type(e,t.text)}case"key":{const e=t.target?await this.find(t.target):void 0;return this.speed<=1&&o.keys(t.key),i.key(t.key,e)}case"select":{const e=await this.find(t.target);if(!(e instanceof HTMLSelectElement))throw new Error("Not a <select>: click its options instead");return e.scrollIntoView({block:"nearest",inline:"nearest"}),i.select(e,t.option,n(e))}case"drag":{const e=await this.find(t.target);e.scrollIntoView({block:"nearest",inline:"nearest"});const s=n(e,t.at),o=t.to.target?await this.find(t.to.target):e;return i.drag(e,s,r(o,t.to.at),t)}case"scroll":{const e=t.target?await this.find(t.target):void 0;return i.scroll(e,t.by)}case"waitFor":{const e=performance.now()+(t.timeout??this.findTimeout);for(;!this.stopped;){if(this.context.targets.matches(t.target).some(t=>t.getClientRects().length>0)!==Boolean(t.gone))return;if(performance.now()>e)throw new Error(`${t.gone?"Still there":"Not found"}: ${describeTarget(t.target)}`);await c(100)}return}case"clear":return void o.clear();case"card":return a({kind:"card",title:t.title,text:t.text});case"callout":{const e=t.target?await this.find(t.target):void 0;return a({kind:"callout",text:t.text,side:t.side,corner:t.corner,element:e&&this.follow(t.target,e)})}default:{const e=await this.find(t.target);e.scrollIntoView({block:"nearest",inline:"nearest"});const s=this.follow(t.target,e);switch(t.do){case"spotlight":return a({kind:"spotlight",element:s,text:t.text,padding:t.padding});case"ring":return a({kind:"ring",element:s,text:t.text,color:t.color,shape:t.shape,padding:t.padding});case"arrow":return a({kind:"arrow",element:s,text:t.text,from:t.from,color:t.color});case"blur":return a({kind:"blur",element:s});case"zoom":{const e=a({kind:"zoom",element:s,scale:t.scale});return await this.sleep(700),e}}}}}}export function describeTarget(t){const e=t.key??t.text;return`${e?`"${e}" `:""}${t.css}${t.index?` #${t.index+1}`:""}`}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protomaze/demo-engine",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
4
4
  "description": "Protomaze Demo Engine: record, edit, narrate, play and film demos of a web app, in the browser",
5
5
  "repository": {
6
6
  "type": "git",
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Turns the page's CSS transitions and animations off until the returned function is called. A page
3
+ * in a hidden tab never finishes them: what fades in would stay at opacity 0, and not be found.
4
+ * The engine's own overlay is in a shadow root, which this does not reach.
5
+ */
6
+ export declare function stillPage(document?: Document): () => void;
package/page/Still.js ADDED
@@ -0,0 +1 @@
1
+ export function stillPage(t=window.document){const e=t.createElement("style");return e.setAttribute("data-demo-ignore",""),e.textContent="*, *::before, *::after { transition: none !important; animation: none !important; }",t.head.append(e),()=>e.remove()}
package/page/Targets.js CHANGED
@@ -1 +1 @@
1
- export const IGNORED="[data-demo-ignore]";const t=["button","a[href]","input","textarea","select","summary","canvas","video",'[contenteditable=""]','[contenteditable="true"]','[role="button"]','[role="link"]','[role="tab"]','[role="option"]','[role="menuitem"]','[role="menuitemcheckbox"]','[role="menuitemradio"]','[role="switch"]','[role="checkbox"]','[role="radio"]','[role="slider"]','[role="combobox"]','[role="treeitem"]','[role="gridcell"]','[role="row"]',"li[role]","[data-demo]"];export function normal(t){return t.replace(/\s+/g," ").replace(/\d[\d.,]*/g,"#").trim().toLowerCase().slice(0,80)}export function dictionaryLabels(t,e){let n;const r=()=>{const e=t();if(n?.from===e)return n;const r=new Map,i=new Map,o=(t,e)=>Object.entries(t).forEach(([t,n])=>{const s=e+t;if("object"==typeof n&&n)o(n,s+".");else if("string"==typeof n&&!n.includes("{{")){const t=normal(n);r.set(t,r.has(t)?null:s),i.set(s,n)}});return o(e,""),n={from:e,keys:r,texts:i}};return{keyOf:t=>r().keys.get(normal(t))??void 0,textOf:t=>e?.(t)??r().texts.get(t)}}export class Targets{constructor(e={}){this.options=e,this.interactive=[...t,...e.interactive??[]].join(","),this.attributes=["aria-label","title",...e.labelAttributes??[]]}labelOf(t){const e=t,n=t.getAttribute("aria-labelledby")?.split(/\s+/).map(e=>t.ownerDocument.getElementById(e)?.textContent??"").join(" "),r=t.matches("input, select, textarea"),i=r?t.closest("label"):null,o=t.getAttribute("data-demo")||(t instanceof HTMLInputElement&&["button","submit","reset"].includes(t.type)?t.value:"")||(r?"":e.innerText?.trim())||n?.trim()||this.attributes.map(e=>t.getAttribute(e)).find(Boolean)||t.placeholder||t.alt||t.id&&t.ownerDocument.querySelector(`label[for="${CSS.escape(t.id)}"]`)?.textContent||i&&Array.from(i.childNodes).filter(t=>t.nodeType===Node.TEXT_NODE).map(t=>t.textContent).join(" ").trim()||t.name||"";if(o.trim())return normal(o);const s=t.querySelector("svg[data-testid], [data-icon]"),a=s?.getAttribute("data-testid")??s?.getAttribute("data-icon");if(a)return normal(a);let l=t.parentElement;for(let t=0;l&&t<4;t++,l=l.parentElement){const t=l.innerText??"";if(t.trim())return normal(t)}return""}cssOf(t){const e=t.tagName.toLowerCase(),n=t.getAttribute("role"),r="input"===e?t.getAttribute("type"):null,i=this.options.stableClass&&Array.from(t.classList).find(t=>this.options.stableClass.test(t));return e+(i?`.${CSS.escape(i)}`:"")+(n?`[role="${n}"]`:"")+(r?`[type="${r}"]`:"")}labelIn(t){if(t.key){const e=this.options.labels?.textOf(t.key);if(void 0!==e)return normal(e)}return void 0===t.text?void 0:normal(t.text)}targetElement(t){return!t||t.closest(IGNORED)?null:t.closest(this.interactive)??t}matches(t){const e=this.labelIn(t);let n;try{n=Array.from(document.querySelectorAll(t.css))}catch{return[]}return n.filter(t=>!t.closest(IGNORED)&&(void 0===e||this.labelOf(t)===e))}describe(t){const r=this.cssOf(t),i=this.labelOf(t),o=i&&!t.getAttribute("data-demo")?this.options.labels?.keyOf(i):void 0,s=t=>({css:t,...o?{key:o}:i?{text:i}:{}}),a=s(r);if(this.matches(a).length<=1)return a;for(let i=t.parentElement;i&&i!==document.body;i=i.parentElement){const o=n(i);if(!o)continue;const a=s(`${o} ${r}`),l=this.matches(a);if(1===l.length)return a;if(l.length>1)return{...a,...e(l,t)}}return{...a,...e(this.matches(a),t)}}async find(t,e=1e4,n=()=>!1){const r=performance.now()+e;do{const e=this.matches(t)[t.index??0];if(e&&shown(e))return e;await new Promise(t=>setTimeout(t,100))}while(performance.now()<r&&!n())}list({within:t,query:e,limit:n=400}={}){const i=t?Array.from(document.querySelectorAll(t)):[document.body],o=new Set,s=[],a=e?normal(e):void 0;for(const t of i)for(const e of Array.from(t.querySelectorAll(this.interactive))){if(s.length>=n)break;if(o.has(e)||e.closest(IGNORED)||!shown(e))continue;const i=e.parentElement?.closest(this.interactive);if(i&&!i.closest(IGNORED)&&t.contains(i)&&this.labelOf(i)===this.labelOf(e)&&!e.matches("input, select, textarea, canvas"))continue;o.add(e);const l=this.labelOf(e);if(a&&!l.includes(a))continue;const c=e.getBoundingClientRect();s.push({target:this.describe(e),label:l,tag:e.tagName.toLowerCase(),...e.getAttribute("role")?{role:e.getAttribute("role")}:{},...r(e),box:{x:Math.round(c.x),y:Math.round(c.y),width:Math.round(c.width),height:Math.round(c.height)}})}return s}}function e(t,e){const n=t.indexOf(e);return n>0?{index:n}:{}}function n(t){const e=t.getAttribute("data-demo");if(e)return`[data-demo="${e.replace(/"/g,'\\"')}"]`;const n=t.id;return n&&/^[a-z][\w-]*$/i.test(n)&&!/\d{3,}|[:]|^(mui|radix|react|headlessui|rc)-?/i.test(n)?`#${CSS.escape(n)}`:void 0}export function shown(t){const e=t.checkVisibility;if(e){if(!e.call(t,{checkVisibilityCSS:!0}))return!1;if(!e.call(t,{checkOpacity:!0,checkVisibilityCSS:!0})){const e=t.parentElement;if(!t.matches("input, select, textarea")||!e||!shown(e))return!1}}return t.getClientRects().length>0}function r(t){const e=[],n=t;t.matches("input[type=checkbox], input[type=radio]")?e.push(n.checked?"checked":"unchecked"):t.matches("input, textarea")?e.push(`value "${n.value.slice(0,60)}"`):t instanceof HTMLSelectElement&&e.push(`value "${t.selectedOptions[0]?.text??""}"`);for(const n of["aria-checked","aria-selected","aria-expanded","aria-pressed","aria-current"]){const r=t.getAttribute(n);r&&"false"!==r&&e.push(`${n.slice(5)}${"true"===r?"":`=${r}`}`)}return(t.disabled||"true"===t.getAttribute("aria-disabled"))&&e.push("disabled"),e.length?{state:e.join(", ")}:{}}export function fractionIn(t,e,n){const r=t.getBoundingClientRect(),i=t=>Math.round(1e3*t)/1e3;return[i((e-r.left)/(r.width||1)),i((n-r.top)/(r.height||1))]}export function pointIn(t,e=[.5,.5]){const n=t.getBoundingClientRect();return{x:n.left+e[0]*n.width,y:n.top+e[1]*n.height}}
1
+ export const IGNORED="[data-demo-ignore]";const t=["button","a[href]","input","textarea","select","summary","canvas","video",'[contenteditable=""]','[contenteditable="true"]','[role="button"]','[role="link"]','[role="tab"]','[role="option"]','[role="menuitem"]','[role="menuitemcheckbox"]','[role="menuitemradio"]','[role="switch"]','[role="checkbox"]','[role="radio"]','[role="slider"]','[role="combobox"]','[role="treeitem"]','[role="gridcell"]','[role="row"]',"li[role]","[data-demo]"];export function normal(t){return t.replace(/\s+/g," ").replace(/\d[\d.,]*/g,"#").trim().toLowerCase().slice(0,80)}export function dictionaryLabels(t,e){let n;const r=()=>{const e=t();if(n?.from===e)return n;const r=new Map,i=new Map,o=(t,e)=>Object.entries(t).forEach(([t,n])=>{const s=e+t;if("object"==typeof n&&n)o(n,s+".");else if("string"==typeof n&&!n.includes("{{")){const t=normal(n);r.set(t,r.has(t)?null:s),i.set(s,n)}});return o(e,""),n={from:e,keys:r,texts:i}};return{keyOf:t=>r().keys.get(normal(t))??void 0,textOf:t=>e?.(t)??r().texts.get(t)}}export class Targets{constructor(e={}){this.options=e,this.interactive=[...t,...e.interactive??[]].join(","),this.attributes=["aria-label","title",...e.labelAttributes??[]]}labelOf(t){const e=t,n=t.getAttribute("aria-labelledby")?.split(/\s+/).map(e=>t.ownerDocument.getElementById(e)?.textContent??"").join(" "),r=t.matches("input, select, textarea"),i=r?t.closest("label"):null,o=r?"":e.innerText?.trim()??"",s=t.getAttribute("data-demo")||(t instanceof HTMLInputElement&&["button","submit","reset"].includes(t.type)?t.value:"")||(/[\p{L}\p{N}]/u.test(o)?o:"")||n?.trim()||this.attributes.map(e=>t.getAttribute(e)).find(Boolean)||t.placeholder||t.alt||t.id&&t.ownerDocument.querySelector(`label[for="${CSS.escape(t.id)}"]`)?.textContent||i&&Array.from(i.childNodes).filter(t=>t.nodeType===Node.TEXT_NODE).map(t=>t.textContent).join(" ").trim()||t.name||o;if(s.trim())return normal(s);const a=t.querySelector("svg[data-testid], [data-icon]"),l=a?.getAttribute("data-testid")??a?.getAttribute("data-icon");if(l)return normal(l);let c=t.parentElement;for(let t=0;c&&t<4;t++,c=c.parentElement){const t=c.innerText??"";if(t.trim())return normal(t)}return""}cssOf(t){const e=t.tagName.toLowerCase(),n=t.getAttribute("role"),r="input"===e?t.getAttribute("type"):null,i=this.options.stableClass&&Array.from(t.classList).find(t=>this.options.stableClass.test(t));return e+(i?`.${CSS.escape(i)}`:"")+(n?`[role="${n}"]`:"")+(r?`[type="${r}"]`:"")}labelIn(t){if(t.key){const e=this.options.labels?.textOf(t.key);if(void 0!==e)return normal(e)}return void 0===t.text?void 0:normal(t.text)}targetElement(t){return!t||t.closest(IGNORED)?null:t.closest(this.interactive)??t}matches(t){const e=this.labelIn(t);let n;try{n=Array.from(document.querySelectorAll(t.css))}catch{return[]}return n.filter(t=>!t.closest(IGNORED)&&(void 0===e||this.labelOf(t)===e))}describe(t){const r=this.cssOf(t),i=this.labelOf(t),o=i&&!t.getAttribute("data-demo")?this.options.labels?.keyOf(i):void 0,s=t=>({css:t,...o?{key:o}:i?{text:i}:{}}),a=s(r);if(this.matches(a).length<=1)return a;for(let i=t.parentElement;i&&i!==document.body;i=i.parentElement){const o=n(i);if(!o)continue;const a=s(`${o} ${r}`),l=this.matches(a);if(1===l.length)return a;if(l.length>1)return{...a,...e(l,t)}}return{...a,...e(this.matches(a),t)}}async find(t,e=1e4,n=()=>!1){const r=performance.now()+e;do{const e=this.matches(t)[t.index??0];if(e&&shown(e))return e;await new Promise(t=>setTimeout(t,100))}while(performance.now()<r&&!n())}list({within:t,query:e,limit:n=400}={}){const i=t?Array.from(document.querySelectorAll(t)):[document.body],o=new Set,s=[],a=e?normal(e):void 0;for(const t of i)for(const e of Array.from(t.querySelectorAll(this.interactive))){if(s.length>=n)break;if(o.has(e)||e.closest(IGNORED)||!shown(e))continue;const i=e.parentElement?.closest(this.interactive);if(i&&!i.closest(IGNORED)&&t.contains(i)&&this.labelOf(i)===this.labelOf(e)&&!e.matches("input, select, textarea, canvas"))continue;o.add(e);const l=this.labelOf(e);if(a&&!l.includes(a))continue;const c=e.getBoundingClientRect();s.push({target:this.describe(e),label:l,tag:e.tagName.toLowerCase(),...e.getAttribute("role")?{role:e.getAttribute("role")}:{},...r(e),box:{x:Math.round(c.x),y:Math.round(c.y),width:Math.round(c.width),height:Math.round(c.height)}})}return s}}function e(t,e){const n=t.indexOf(e);return n>0?{index:n}:{}}function n(t){const e=t.getAttribute("data-demo");if(e)return`[data-demo="${e.replace(/"/g,'\\"')}"]`;const n=t.id;return n&&/^[a-z][\w-]*$/i.test(n)&&!/\d{3,}|[:]|^(mui|radix|react|headlessui|rc)-?/i.test(n)?`#${CSS.escape(n)}`:void 0}export function shown(t){const e=t.checkVisibility;if(e){if(!e.call(t,{checkVisibilityCSS:!0}))return!1;if(!e.call(t,{checkOpacity:!0,checkVisibilityCSS:!0})){const e=t.parentElement;if(!t.matches("input, select, textarea")||!e||!shown(e))return!1}}return t.getClientRects().length>0}function r(t){const e=[],n=t;t.matches("input[type=checkbox], input[type=radio]")?e.push(n.checked?"checked":"unchecked"):t.matches("input, textarea")?e.push(`value "${n.value.slice(0,60)}"`):t instanceof HTMLSelectElement&&e.push(`value "${t.selectedOptions[0]?.text??""}"`);for(const n of["aria-checked","aria-selected","aria-expanded","aria-pressed","aria-current"]){const r=t.getAttribute(n);r&&"false"!==r&&e.push(`${n.slice(5)}${"true"===r?"":`=${r}`}`)}return(t.disabled||"true"===t.getAttribute("aria-disabled"))&&e.push("disabled"),e.length?{state:e.join(", ")}:{}}export function fractionIn(t,e,n){const r=t.getBoundingClientRect(),i=t=>Math.round(1e3*t)/1e3;return[i((e-r.left)/(r.width||1)),i((n-r.top)/(r.height||1))]}export function pointIn(t,e=[.5,.5]){const n=t.getBoundingClientRect();return{x:n.left+e[0]*n.width,y:n.top+e[1]*n.height}}