@protomaze/demo-engine 0.1.1 → 0.1.2

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
@@ -106,7 +106,8 @@ Presentation (shown until the step ends, or `for` ms; `clear` takes all down):
106
106
  The app may add its own actions (a map's `view`, `mapClick`): `validate` lists every kind it knows
107
107
  when one is wrong; read the app's demos (`demoEngine.get(id)`) for examples.
108
108
 
109
- Step options: `title` (for the editor), `hold` (ms after), `pause: true` (waits for the presenter).
109
+ Step options: `title` (for the editor), `hold` (ms after), `pause: true` (waits for the presenter),
110
+ `notes` (on the presenter's screen only: what to add live, figures to mention, questions to expect).
110
111
 
111
112
  `cleanup`: actions done after the demo - when it ends or is stopped - quickly and unseen, so the app
112
113
  is as it found it and the demo plays again: clear filters and searches, close what was opened, go
package/README.md CHANGED
@@ -9,8 +9,9 @@ Demos of a web app, made and played in the app itself, in the browser: no backen
9
9
  A **narration pack** keeps a demo's finished audio, so every viewer hears it without a key, tokens
10
10
  or a model download.
11
11
  - **Show**: a stand-in pointer, spotlights, rings, arrows, notes, blur, title cards, zoom, keycaps.
12
- - **Play**: as a video would; **present** step by step with a clicker; **guide** a viewer who does
13
- each step themselves (tutorials, trainings); **loop** unattended at an expo booth.
12
+ - **Play**: as a video would; **present** step by step with a clicker and a presenter's screen
13
+ (script, notes, what comes next, the clock); **guide** a viewer who does each step themselves
14
+ (tutorials, trainings); **loop** unattended at an expo booth.
14
15
  - **Film**: an MP4 or WebM of the tab with narration, music and subtitles, made in the browser, at
15
16
  exactly 720p, 1080p, 1440p or 4K, landscape, portrait or square.
16
17
  - **Music**: four tracks the engine composes itself (calm, lo-fi, bright, piano) - free to use
@@ -152,6 +153,13 @@ part is. At a booth, a visitor's touch hands the app over.
152
153
  Going forward, the steps between are caught up under a card naming the step; going back, the app is
153
154
  reset - the demo's cleanup, its start - and caught up to the step, under the card. Not while filming.
154
155
 
156
+ **Presenting**: `engine.present(demo)` waits after each step and opens the presenter's screen in a
157
+ window of its own - beside the projected app, never in a video: the step's script with the sentence
158
+ being said, the step's `notes` (for the presenter only), what comes next, the clock against the
159
+ plan, every step to go to, big controls. `engine.openPresenter({ onTop: true })` keeps a compact one
160
+ always on top (Chrome's Document Picture-in-Picture). `mountPresenter(engine, document)` puts it in
161
+ a window or frame of the app's own. A clicker works in either window.
162
+
155
163
  A presenter's clicker sends PageDown and PageUp: "Wait for the presenter after each step" makes
156
164
  a pitch. Guided, the viewer does each click, entry and choice; "Do it for me" lets the demo. Looped,
157
165
  a visitor's touch hands the app over; after `idle` it plays on, from the app's start (or a reload).
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\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).\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";
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\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).\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';
@@ -247,6 +247,17 @@ export declare class DemoEngine {
247
247
  next(): void;
248
248
  /** The presenter's back: this step again, or - in its first seconds - the one before. */
249
249
  back(): void;
250
+ /**
251
+ * The presenter's screen, in a window of its own - or `onTop`, always on top where the browser
252
+ * can: the script, notes, what comes next, the clock, the controls. From a click.
253
+ */
254
+ openPresenter(options?: {
255
+ onTop?: boolean;
256
+ }): Promise<boolean>;
257
+ /** Keys pressed in another window of the engine's (the presenter's): a clicker's go to whichever is in front. */
258
+ presenterKey(event: KeyboardEvent): void;
259
+ /** Presents it: waiting after each step, the presenter's screen open beside it. From a click. */
260
+ present(demo: Demo, options?: Partial<PlayOptions>): Promise<PlayResult | undefined>;
250
261
  /** To a step of what plays (0-based): forward or back. False where it cannot (filmed). */
251
262
  goTo(step: number): boolean;
252
263
  /**
@@ -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 d}from"../model/Timing.js";import{parseDemo as c,validate as l}from"../model/Validate.js";import{Hand as g}from"../page/Input.js";import{Overlay as m}from"../page/Overlay.js";import{Targets as u}from"../page/Targets.js";import{Speech as y}from"../speech/Speech.js";import{narrationFor as f,transcribe as w}from"../speech/Transcribe.js";import{Store as v}from"../store/Store.js";import{demoFromLink as k,download as b,fileName as S,linkTo as P,shareFiles as x}from"../store/Share.js";import{extensionOf as T,recordMicrophone as E,startFilming as j,videoSize as $}from"../video/Film.js";import{renderMusic as M}from"../speech/Music.js";import{readPack as R,writePack as K}from"../speech/Pack.js";import{Player as N}from"./Player.js";import{Recorder as L}from"./Recorder.js";import{readAction as B}from"./Read.js";import{mountUI as D}from"../ui/EngineUI.js";import{agentTools as I}from"../agent/Agent.js";import{DEFAULT_SETTINGS as O,loadSettings as A,saveSettings as F}from"./Settings.js";const C=["pointerdown","pointerup","pointermove","pointerover","pointerout","mousedown","mouseup","mousemove","mouseover","mouseout","click","dblclick","contextmenu","wheel","touchstart","touchmove","touchend","keydown","keyup","keypress"];export class DemoEngine{constructor(e){this.options=e,this.listeners=new Set,this.packs=new Map,this.getState=()=>this.state,this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e)),this.hintTimer=0,this.targets=new u({...e.targets,labels:e.labels}),this.overlay=new m(e.overlay),this.hand=new g(this.overlay.cursor,()=>this.player?.speedNow??1),this.settingsKey=`protomaze-demo-engine:${e.app}:settings`,this.state={session:{mode:"idle"},settings:A(this.settingsKey),speech:{}},this.speech=new y(()=>this.state.settings.speech,()=>this.set({speech:{...this.speech.state}})),this.store=new v(`protomaze-demo-engine:${e.app}`),this.store.subscribe(()=>this.emit()),this.plugins=e.plugins??[]}emit(){this.state={...this.state},this.listeners.forEach(e=>e())}set(e){this.state={...this.state,...e},this.listeners.forEach(e=>e())}setSession(e){this.set({session:e})}updateSession(e,t){this.state.session.mode===e&&this.setSession({...this.state.session,...t})}say(e,t=!1){this.set({message:e?{text:e,error:t}:void 0})}changeSettings(e){const t={...this.state.settings,...e};F(this.settingsKey,t),this.set({settings:t}),e.music?.on&&this.loadMusic().catch(()=>{})}language(){const e=this.state.settings.language;return"page"!==e?e:this.options.language?.()??this.options.languages?.[0]??(navigator.language.split("-")[0]||"en")}languages(){return this.options.languages??[this.language()]}pluginKinds(){return this.plugins.flatMap(e=>Object.keys(e.actions??{}))}pluginAction(e){return this.plugins.map(t=>t.actions?.[e]).find(Boolean)}read(e,t){return B(e,this.options.labels,this.plugins,t)}async mount(){if(this.unmount)return;this.overlay.mount();const e=D(this),t=e=>this.key(e);window.addEventListener("keydown",t,!0);const s=e=>this.gate(e);C.forEach(e=>window.addEventListener(e,s,{capture:!0,passive:!1})),this.state.settings.music.on&&this.loadMusic().catch(()=>{});const i=!1===this.options.agent?void 0:this.options.agent??"demoEngine";i&&(window[i]=I(this)),this.unmount=()=>{e(),window.removeEventListener("keydown",t,!0),C.forEach(e=>window.removeEventListener(e,s,{capture:!0})),i&&delete window[i],this.overlay.unmount()},await this.arrived()}destroy(){this.stopLoop(),this.stop(),this.unmount?.(),this.unmount=void 0}async arrived(){const e=sessionStorage.getItem(this.pendingKey());if(sessionStorage.removeItem(this.pendingKey()),e){const{demo:t,verb:s,from:i,loop:o}=JSON.parse(e);return"loop"===s&&o?void this.loop(o.demos,{gap:o.gap,idle:o.idle,reset:o.reload?"reload":void 0},o.index):this.whenClicked(t.title,"film"===s?"Film":"Play",()=>"film"===s?this.film(t):this.play(t,{from:i}),!0)}const t=await k();if(t){const e=l(t,this.pluginKinds());return e.length?this.say(`The link's demo: ${e[0].path} ${e[0].message}`,!0):(await this.save(t),this.say(`"${t.title}" came with the link: it is kept here.`),this.openStudio(t))}const s=new URL(window.location.href),i=s.searchParams.get("demo");if(i){s.searchParams.delete("demo"),window.history.replaceState(window.history.state,"",s.toString());const e=(await this.entries()).find(e=>e.demo.id===i);e&&this.whenClicked(e.demo.title,"Play",()=>this.play(e.demo),!0)}}gate(e){const t=this.state.session;if(!e.isTrusted||"playing"!==t.mode||t.paused||t.looping)return;const s=e.composedPath();if(s.includes(this.overlay.host))return;if(t.guided&&t.instruction){const i=t.player.viewerTarget();if(i&&(s.includes(i)||e instanceof KeyboardEvent&&i.contains(document.activeElement)))return;if(!i&&e instanceof KeyboardEvent)return}const i=e.defaultPrevented;e.cancelable&&e.preventDefault(),e.stopImmediatePropagation(),i||"pointerdown"!==e.type&&"keydown"!==e.type&&"wheel"!==e.type||this.hint(t.guided?'Only the ringed part now: or "Do it for me"':"Playing: Space pauses, and the app is yours then. Esc stops.")}hint(e){window.clearTimeout(this.hintTimer),this.set({hint:e}),this.hintTimer=window.setTimeout(()=>this.set({hint:void 0}),3e3)}pendingKey(){return`protomaze-demo-engine:${this.options.app}:pending`}key(e){if(!e.isTrusted)return;const t=e.composedPath(),s=t.some(e=>e instanceof HTMLElement&&(e.isContentEditable||e.matches("input, textarea, select"))),i=t.includes(this.overlay.host),o=this.state.session,n=()=>{e.preventDefault(),e.stopPropagation()};if("ready"!==o.mode)if("recording"!==o.mode){if("l"===e.key.toLowerCase()&&e.ctrlKey&&e.shiftKey&&this.looping)return n(),this.stopLoop();if(!("playing"!==o.mode||o.looping||o.checking||s&&(i||o.guided&&o.instruction))){if("Escape"===e.key)this.stop();else if(" "===e.key||"b"===e.key||"."===e.key)this.togglePause();else if("ArrowRight"===e.key||"Enter"===e.key||"PageDown"===e.key)o.player.next();else if("ArrowLeft"===e.key||"PageUp"===e.key)o.player.back();else if("Home"===e.key)o.player.goTo(0);else if("End"===e.key)o.player.goTo(o.steps-1);else{if(!/^[1-9]$/.test(e.key)||e.ctrlKey||e.metaKey||e.altKey)return;o.player.goTo(Number(e.key)-1)}n()}}else"Escape"!==e.key||s||(n(),this.stopRecording?.());else"Escape"===e.key&&(n(),o.cancel())}async entries(){return await this.store.ready(),this.entriesNow()}entriesNow(){const{demos:e,videos:t}=this.store.get(),s=new Map(e.map(e=>[e.id,e])),i=this.language(),n=(this.options.demos??[]).map(e=>"demo"in e?e:{demo:e,scenario:void 0});return[...n.map(({demo:e,scenario:n})=>{const a=s.get(e.id);return a?{demo:a,scenario:a.scenario??n??o(a,i),origin:"edited",video:t.get(e.id)}:{demo:e,scenario:n??o(e,i),origin:"app",video:t.get(e.id)}}),...e.filter(e=>!n.some(t=>t.demo.id===e.id)).map(e=>({demo:e,scenario:e.scenario??o(e,i),origin:"here",video:t.get(e.id)}))]}async save(t){const s=l(t,this.pluginKinds());if(s.length)throw new Error(`Not a demo: ${s.map(e=>`${e.path} ${e.message}`).join("; ")}`);await this.store.saveDemo(e(t))}async remove(e){await this.store.deleteDemo(e),this.state.studio?.demo.id===e&&this.closeStudio()}parse(e){return c(e,this.pluginKinds())}create(e){return s(e,this.options.start?.current())}openStudio(t){this.set({studio:{demo:e(t),opened:Date.now()}})}closeStudio(){this.set({studio:void 0})}activated(){const e=navigator.userActivation;return!e||e.isActive}whenClicked(e,t,s,i=!1){const o=()=>{this.setSession({mode:"idle"}),this.speech.wake(),s().catch(e=>this.say(e.message,!0))};if(!i&&this.activated())return o();this.setSession({mode:"ready",title:e,verb:t,go:o,cancel:()=>this.setSession({mode:"idle"})})}async goToStart(e,t,s,i){if(!e.start||!this.options.start)return!0;sessionStorage.setItem(this.pendingKey(),JSON.stringify({demo:e,verb:t,from:s,loop:i}));return"reload"!==await this.options.start.go(e.start)&&(sessionStorage.removeItem(this.pendingKey()),!0)}busy(){return"idle"!==this.state.session.mode&&"ready"!==this.state.session.mode}play(e,t={}){return new Promise(s=>this.whenClicked(e.title,"Play",async()=>{if(this.busy())return s(void 0);if(this.say(void 0),!await this.goToStart(e,"play",t.from))return s(void 0);const i=await this.run(e,t);s(i)}))}async run(e,t={}){const{settings:s}=this.state,i=t.language??this.language(),o=s.music.on&&!t.checking&&!t.guided&&await Promise.race([this.loadMusic(),new Promise(e=>setTimeout(()=>e(!1),t.filming?6e4:1500))]);this.speech.setPack(s.usePacks?await this.pack(e):void 0);const n=new N(e,{language:i,subtitles:s.subtitles,waitForPresenter:s.waitForPresenter&&!t.looping,catchUp:s.catchUp,music:Boolean(o),...t},{hand:this.hand,targets:this.targets,overlay:this.overlay,speech:this.speech,plugins:this.plugins,ready:this.options.ready,read:(e,t)=>this.read(e,t),reset:async()=>!e.start||!this.options.start||"reload"!==await this.options.start.go(e.start),update:e=>this.updateSession("playing",e)});this.setSession({mode:"playing",title:e.title,demo:e,steps:e.steps.length,filming:Boolean(t.filming),checking:Boolean(t.checking),guided:Boolean(t.guided),looping:Boolean(t.looping),player:n,step:t.from??0,caption:"",paused:!1,waiting:!1,catchingUp:!1}),this.player=n;const a=await n.play().finally(()=>this.player=void 0);return this.setSession({mode:"idle"}),t.checking||a.navigated||(this.set({lastRun:{json:JSON.stringify(e),language:i,timing:a.timing}}),a.error&&"Stopped."!==a.error&&this.say(a.error,!0)),a}stop(){const e=this.state.session;"playing"===e.mode&&e.player.stop(),"recording"===e.mode&&this.stopRecording?.(),"ready"!==e.mode&&"preparing"!==e.mode||this.setSession({mode:"idle"})}togglePause(){const e=this.state.session;"playing"===e.mode&&(e.paused?e.player.resume():e.player.pause())}resume(){const e=this.state.session;"playing"===e.mode&&e.player.resume()}next(){const e=this.state.session;"playing"===e.mode&&e.player.next()}back(){const e=this.state.session;"playing"===e.mode&&e.player.back()}goTo(e){const t=this.state.session;return"playing"===t.mode&&t.player.goTo(e)}guide(e,t={}){return this.play(e,{...t,guided:!0})}doItForMe(){const e=this.state.session;"playing"===e.mode&&e.player.doItForMe()}pack(e){let t=this.packs.get(e.id);return t||(t=(async()=>{const t=await this.store.asset(`narration:${e.id}`);if(t)return R(await t.arrayBuffer());const s=this.options.narration?.(e);if(!s)return;const i=await fetch(s);return i.ok?R(await i.arrayBuffer()):void 0})().catch(()=>{}),this.packs.set(e.id,t)),t}async makePack(e,s=()=>{}){const i=await this.pack(e);this.speech.setPack(i);const o=t(e).flatMap(t=>e.steps.flatMap(e=>n(e.say[t]??"").map(e=>({language:t,text:e})))),a=o.filter((e,t)=>o.findIndex(t=>t.language===e.language&&t.text===e.text)===t),r=[];for(const e of a)s(r.length,a.length),r.push({...await this.speech.packable(e.text,e.language),...e});s(r.length,a.length);const h=K(e.id,r);return await this.store.saveAsset(`narration:${e.id}`,h),this.packs.delete(e.id),h}async downloadPack(e){try{const t=await this.makePack(e,(e,t)=>this.say(`Making the narration pack: ${e} / ${t}`));b(t,`${e.id}.narration.zip`),this.say(`Narration pack: ${Math.round(t.size/1e5)/10} MB, kept here too. Check it in beside ${e.id}.demo.json, for every viewer.`)}catch(e){this.say(`Narration pack: ${e.message}`,!0)}}async dropPack(e){await this.store.saveAsset(`narration:${e.id}`,void 0),this.packs.delete(e.id)}async setMusic(e){await this.store.saveAsset("music",e),this.musicLoaded=void 0;const{music:t}=this.state.settings;this.changeSettings({music:e?{...t,on:!0,track:"file",name:e.name??"music"}:{...t,track:"calm",name:void 0}})}async loadMusic(){const{music:e}=this.state.settings,t="file"===e.track?`file:${e.name}`:e.track;if(this.musicLoaded!==t){if("file"===e.track){const t=await this.store.asset("music");if(!t)return!1;await this.speech.setMusic(t,e.volume).catch(()=>{})}else this.speech.setMusicBuffer(await M(e.track),e.volume);this.musicLoaded=t}return this.speech.setMusicVolume(e.volume),this.speech.hasMusic}async listenToMusic(e=20){if(this.speech.wake(),!await this.loadMusic())return()=>{};this.speech.startMusic();const t=setTimeout(()=>this.speech.stopMusic(),1e3*e);return()=>{clearTimeout(t),this.speech.stopMusic(.6)}}async loop(e,t={},s=0){if(0===e.length)return;this.stopLoop();let i=!1,o=0,n=s;const a=t.idle??this.state.settings.loopIdle,r=t.gap??1500,h=e.map(e=>e.title),p=e=>{if(!e.isTrusted||e.composedPath().includes(this.overlay.host))return;o=performance.now();const t=this.state.session;"playing"===t.mode&&t.looping&&t.player.stop(!0)},d=["pointerdown","keydown","wheel","touchstart"];d.forEach(e=>window.addEventListener(e,p,{capture:!0,passive:!0}));this.looping={demos:e,options:t,stop:()=>{i=!0,d.forEach(e=>window.removeEventListener(e,p,{capture:!0}));const e=this.state.session;"playing"===e.mode&&e.looping&&e.player.stop(),this.set({loop:void 0})}};const c=e=>new Promise(t=>setTimeout(t,e));for(;!i;){const s=e[n%e.length];this.set({loop:{titles:h,index:n%e.length,visitor:!1}});if(!await this.goToStart(s,"loop",void 0,{demos:e,index:n%e.length,gap:t.gap,idle:t.idle,reload:"reload"===t.reset})||i)return;const p=await this.run(s,{looping:!0,catchUp:!1});if(i)break;if(p.error&&performance.now()-o<1e3){for(;!i&&performance.now()-o<a;)this.set({loop:{titles:h,index:n%e.length,visitor:!0,resumesAt:Date.now()+a-(performance.now()-o)}}),await c(1e3);if(i)break;if("reload"===t.reset)return sessionStorage.setItem(this.pendingKey(),JSON.stringify({demo:s,verb:"loop",loop:{demos:e,index:n%e.length,gap:t.gap,idle:t.idle,reload:!0}})),window.location.reload();await(t.reset?.())}else n++,await c(r)}}stopLoop(){this.looping?.stop(),this.looping=void 0}elapsed(){const e=this.state.session;return"playing"===e.mode?e.player.elapsed():void 0}async check(e,t={}){const s=l(e,this.pluginKinds());if(s.length)return{ok:!1,problems:s,failures:[],duration:0,error:"Not a valid demo"};if(this.busy())return{ok:!1,problems:s,failures:[],duration:0,error:`Busy: ${this.state.session.mode}`};if(!1!==t.fromStart&&e.start&&this.options.start){if("reload"===await this.options.start.go(e.start))return{ok:!1,problems:s,failures:[],duration:0,error:"Its start reloads the page: check again once it is back"}}const i=await this.run(e,{...t,speed:t.speed??8,keepGoing:!0,checking:!0,catchUp:!0,subtitles:!1}),o=i.failures.map(t=>({...t,action:e.steps[t.step].actions[t.index]}));return{ok:!i.error&&0===o.length,error:i.error,failures:o,problems:s,duration:i.timing.duration}}timing(e,t=this.language()){const s=this.state.lastRun;return s&&s.language===t&&s.json===JSON.stringify(e)&&s.timing.steps.length===e.steps.length?s.timing:d(e,{language:t,sayTime:e=>this.speech.duration(e,t),actionTime:e=>{const t=this.pluginAction(e.do);return t?.duration?.(e)??p(e)}})}film(e,t={}){return new Promise(s=>this.whenClicked(e.title,"Film",async()=>this.busy()?s(void 0):(this.say(void 0),await this.goToStart(e,"film")?void s(await this.filmNow(e,t)):s(void 0))))}async filmNow(e,t){const s=t.language??this.language();let o=!1;const a=await j({soundtrack:this.speech.soundtrack(),microphone:t.microphone,crop:this.options.filmElement?.(),...this.filmQuality(),onEnded:()=>{o=!0,this.stop()}});let r;try{const t=e.steps.flatMap(e=>n(i(e,s)));this.setSession({mode:"preparing",title:e.title,text:"Preparing the narration"}),await this.speech.prepare(t,s,(e,t)=>this.updateSession("preparing",{text:`Preparing the narration: ${e} / ${t}`})),o||"preparing"!==this.state.session.mode||(r=await this.run(e,{language:s,filming:a}))}finally{"preparing"===this.state.session.mode&&this.setSession({mode:"idle"})}const{video:p,voice:d}=await a.stop();if(!r||r.error)return void this.say("Stopped."!==r?.error&&r?`Filming failed: ${r.error}`:"Filming stopped: nothing kept.",Boolean(r?.error&&"Stopped."!==r.error));let c=r.timing.cues;d&&"off"===this.state.settings.speech.voice&&(this.setSession({mode:"preparing",title:e.title,text:"Transcribing what was said"}),c=await this.transcribe(d,s).catch(()=>c),this.setSession({mode:"idle"}));const l={id:e.id,blob:p,at:Date.now(),json:JSON.stringify(e),vtt:h(c),timing:r.timing,language:s,...d?{voice:d}:{}};return await this.store.saveVideo(l),this.say(`Filmed "${e.title}": ${Math.round(p.size/1e6)} MB, kept here.`),l}filmQuality(){const{frameRate:e,bitrate:t,lines:s,aspect:i,fit:o}=this.state.settings.film;return{frameRate:e,bitrate:t,fit:o,...s?{size:$(s,i)}:{}}}async transcribe(e,t=this.language()){const{settings:s}=this.state;return w(e,{language:t,with:s.transcriber,model:s.whisperModel,elevenLabsKey:s.speech.elevenlabs.key,progress:e=>this.set({speech:e<1?{loading:e}:{}})})}record(e={}){return new Promise(t=>this.whenClicked(e.into?.title??"New demo","Record",async()=>{if(this.busy())return t();this.say(void 0),await this.recordNow(e,t)}))}async recordNow(t,i){const{settings:o}=this.state,n=this.language();let a,r;try{o.filmRecording?a=await j({soundtrack:this.speech.soundtrack(),microphone:o.microphone,crop:this.options.filmElement?.(),...this.filmQuality(),onEnded:()=>{this.stopRecording?.()}}):o.microphone&&(r=await E())}catch(e){return this.say(`Could not start: ${e.message}`,!0),i()}const p=this.options.start?.current(),d=new L(this.targets,this.plugins,n,e=>this.updateSession("recording",e));a?.resume();const c=performance.now();this.setSession({mode:"recording",filming:Boolean(a),microphone:Boolean(r||a&&o.microphone),step:0,caption:"",actions:0}),this.nextStepRecording=()=>d.nextStep(),this.sayRecording=e=>d.say(e),this.stopRecording=async()=>{this.stopRecording=this.nextStepRecording=this.sayRecording=void 0;const l=Boolean(r||a&&o.microphone),g=d.stop(l),m=performance.now()-c;this.setSession({mode:"preparing",title:"Recording",text:"Keeping what was recorded"});try{const[i,o]=await Promise.all([r?.stop(),a?.stop()]),d=i??o?.voice;let c=[];if(d){this.updateSession("preparing",{text:"Transcribing what was said"});try{c=await this.transcribe(d,n);const e=f(g.stepStarts,c);g.steps.forEach((t,s)=>{!t.say[n]&&e[s]&&(t.say[n]=e[s])})}catch(e){this.say(`Transcribing failed: ${e.message}`,!0)}}const l=g.steps.filter(e=>e.actions.length>0||Object.values(e.say).some(Boolean)),u=t.into?e(t.into):{...s("Recorded demo",p),steps:[]},y=t.after??u.steps.length-1,w={...u,steps:[...u.steps.slice(0,y+1),...l,...u.steps.slice(y+1)]};0===w.steps.length&&w.steps.push({say:{},actions:[]}),o&&await this.store.saveVideo({id:w.id,blob:o.video,at:Date.now(),json:JSON.stringify(w),vtt:h(c),language:n,timing:{duration:m,steps:g.stepStarts.map((e,t)=>({step:t,start:e,end:g.stepStarts[t+1]??m})),cues:c.map(e=>({...e,step:0})),actions:[]},...o.voice?{voice:o.voice}:{}}),this.setSession({mode:"idle"}),this.say(`Recorded ${l.length} step${1===l.length?"":"s"}${o?", and filmed":""}.`),t.into&&this.state.studio?.demo.id===t.into.id?this.set({studio:{...this.state.studio,recorded:{steps:w.steps,at:Date.now()}}}):this.openStudio(w)}catch(e){this.setSession({mode:"idle"}),this.say(e.message,!0)}i()}}nextStep(){this.nextStepRecording?.()}narrate(e){this.sayRecording?.(e)}async finishRecording(){await(this.stopRecording?.())}link(e){return P(e)}downloadDemo(e,t="json"){if("md"===t)return b(e.scenario??o(e,this.language()),S(e.id,"md"),"text/markdown");const{scenario:s,savedAt:i,...n}=e;b(JSON.stringify(n,null,2)+"\n",S(e.id,"demo.json"),"application/json")}downloadVideo(e,t,s=!1){return"vtt"===s?b(e.vtt,S(t,"vtt"),"text/vtt"):"srt"===s?b(r(a(e.vtt)),S(t,"srt"),"application/x-subrip"):void b(e.blob,S(t,T(e.blob)))}shareVideo(e,t){return x([new File([e.blob],S(t,T(e.blob)),{type:e.blob.type}),new File([e.vtt],S(t,"vtt"),{type:"text/vtt"})],t)}languagesOf(e){return t(e)}}export{O as DEFAULT_SETTINGS};
1
+ import{copyOf as e,languagesOf as t,newDemo as s,sayOf as i,scenarioOf as o,sentences as n}from"../model/Demo.js";import{parseSubtitles as a,toSrt as r,toVtt as h}from"../model/Subtitles.js";import{actionTime as p,estimate as d}from"../model/Timing.js";import{parseDemo as c,validate as l}from"../model/Validate.js";import{Hand as g}from"../page/Input.js";import{Overlay as m}from"../page/Overlay.js";import{Targets as u}from"../page/Targets.js";import{Speech as y}from"../speech/Speech.js";import{narrationFor as f,transcribe as w}from"../speech/Transcribe.js";import{Store as v}from"../store/Store.js";import{demoFromLink as k,download as b,fileName as S,linkTo as P,shareFiles as x}from"../store/Share.js";import{extensionOf as T,recordMicrophone as j,startFilming as E,videoSize as $}from"../video/Film.js";import{renderMusic as M}from"../speech/Music.js";import{readPack as R,writePack as K}from"../speech/Pack.js";import{Player as N}from"./Player.js";import{Recorder as L}from"./Recorder.js";import{readAction as B}from"./Read.js";import{mountUI as D}from"../ui/EngineUI.js";import{agentTools as F}from"../agent/Agent.js";import{openPresenter as I}from"../ui/Presenter.js";import{DEFAULT_SETTINGS as O,loadSettings as A,saveSettings as C}from"./Settings.js";const J=["pointerdown","pointerup","pointermove","pointerover","pointerout","mousedown","mouseup","mousemove","mouseover","mouseout","click","dblclick","contextmenu","wheel","touchstart","touchmove","touchend","keydown","keyup","keypress"];export class DemoEngine{constructor(e){this.options=e,this.listeners=new Set,this.packs=new Map,this.getState=()=>this.state,this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e)),this.hintTimer=0,this.targets=new u({...e.targets,labels:e.labels}),this.overlay=new m(e.overlay),this.hand=new g(this.overlay.cursor,()=>this.player?.speedNow??1),this.settingsKey=`protomaze-demo-engine:${e.app}:settings`,this.state={session:{mode:"idle"},settings:A(this.settingsKey),speech:{}},this.speech=new y(()=>this.state.settings.speech,()=>this.set({speech:{...this.speech.state}})),this.store=new v(`protomaze-demo-engine:${e.app}`),this.store.subscribe(()=>this.emit()),this.plugins=e.plugins??[]}emit(){this.state={...this.state},this.listeners.forEach(e=>e())}set(e){this.state={...this.state,...e},this.listeners.forEach(e=>e())}setSession(e){this.set({session:e})}updateSession(e,t){this.state.session.mode===e&&this.setSession({...this.state.session,...t})}say(e,t=!1){this.set({message:e?{text:e,error:t}:void 0})}changeSettings(e){const t={...this.state.settings,...e};C(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);J.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]=F(this)),this.unmount=()=>{e(),window.removeEventListener("keydown",t,!0),J.forEach(e=>window.removeEventListener(e,s,{capture:!0})),i&&delete window[i],this.overlay.unmount()},await this.arrived()}destroy(){this.stopLoop(),this.stop(),this.unmount?.(),this.unmount=void 0}async arrived(){const e=sessionStorage.getItem(this.pendingKey());if(sessionStorage.removeItem(this.pendingKey()),e){const{demo:t,verb:s,from:i,loop:o}=JSON.parse(e);return"loop"===s&&o?void this.loop(o.demos,{gap:o.gap,idle:o.idle,reset:o.reload?"reload":void 0},o.index):this.whenClicked(t.title,"film"===s?"Film":"Play",()=>"film"===s?this.film(t):this.play(t,{from:i}),!0)}const t=await k();if(t){const e=l(t,this.pluginKinds());return e.length?this.say(`The link's demo: ${e[0].path} ${e[0].message}`,!0):(await this.save(t),this.say(`"${t.title}" came with the link: it is kept here.`),this.openStudio(t))}const s=new URL(window.location.href),i=s.searchParams.get("demo");if(i){s.searchParams.delete("demo"),window.history.replaceState(window.history.state,"",s.toString());const e=(await this.entries()).find(e=>e.demo.id===i);e&&this.whenClicked(e.demo.title,"Play",()=>this.play(e.demo),!0)}}gate(e){const t=this.state.session;if(!e.isTrusted||"playing"!==t.mode||t.paused||t.looping)return;const s=e.composedPath();if(s.includes(this.overlay.host))return;if(t.guided&&t.instruction){const i=t.player.viewerTarget();if(i&&(s.includes(i)||e instanceof KeyboardEvent&&i.contains(document.activeElement)))return;if(!i&&e instanceof KeyboardEvent)return}const i=e.defaultPrevented;e.cancelable&&e.preventDefault(),e.stopImmediatePropagation(),i||"pointerdown"!==e.type&&"keydown"!==e.type&&"wheel"!==e.type||this.hint(t.guided?'Only the ringed part now: or "Do it for me"':"Playing: Space pauses, and the app is yours then. Esc stops.")}hint(e){window.clearTimeout(this.hintTimer),this.set({hint:e}),this.hintTimer=window.setTimeout(()=>this.set({hint:void 0}),3e3)}pendingKey(){return`protomaze-demo-engine:${this.options.app}:pending`}key(e){if(!e.isTrusted)return;const t=e.composedPath(),s=t.some(e=>e instanceof HTMLElement&&(e.isContentEditable||e.matches("input, textarea, select"))),i=t.includes(this.overlay.host),o=this.state.session,n=()=>{e.preventDefault(),e.stopPropagation()};if("ready"!==o.mode)if("recording"!==o.mode){if("l"===e.key.toLowerCase()&&e.ctrlKey&&e.shiftKey&&this.looping)return n(),this.stopLoop();if(!("playing"!==o.mode||o.looping||o.checking||s&&(i||o.guided&&o.instruction))){if("Escape"===e.key)this.stop();else if(" "===e.key||"b"===e.key||"."===e.key)this.togglePause();else if("ArrowRight"===e.key||"Enter"===e.key||"PageDown"===e.key)o.player.next();else if("ArrowLeft"===e.key||"PageUp"===e.key)o.player.back();else if("Home"===e.key)o.player.goTo(0);else if("End"===e.key)o.player.goTo(o.steps-1);else{if(!/^[1-9]$/.test(e.key)||e.ctrlKey||e.metaKey||e.altKey)return;o.player.goTo(Number(e.key)-1)}n()}}else"Escape"!==e.key||s||(n(),this.stopRecording?.());else"Escape"===e.key&&(n(),o.cancel())}async entries(){return await this.store.ready(),this.entriesNow()}entriesNow(){const{demos:e,videos:t}=this.store.get(),s=new Map(e.map(e=>[e.id,e])),i=this.language(),n=(this.options.demos??[]).map(e=>"demo"in e?e:{demo:e,scenario:void 0});return[...n.map(({demo:e,scenario:n})=>{const a=s.get(e.id);return a?{demo:a,scenario:a.scenario??n??o(a,i),origin:"edited",video:t.get(e.id)}:{demo:e,scenario:n??o(e,i),origin:"app",video:t.get(e.id)}}),...e.filter(e=>!n.some(t=>t.demo.id===e.id)).map(e=>({demo:e,scenario:e.scenario??o(e,i),origin:"here",video:t.get(e.id)}))]}async save(t){const s=l(t,this.pluginKinds());if(s.length)throw new Error(`Not a demo: ${s.map(e=>`${e.path} ${e.message}`).join("; ")}`);await this.store.saveDemo(e(t))}async remove(e){await this.store.deleteDemo(e),this.state.studio?.demo.id===e&&this.closeStudio()}parse(e){return c(e,this.pluginKinds())}create(e){return s(e,this.options.start?.current())}openStudio(t){this.set({studio:{demo:e(t),opened:Date.now()}})}closeStudio(){this.set({studio:void 0})}activated(){const e=navigator.userActivation;return!e||e.isActive}whenClicked(e,t,s,i=!1){const o=()=>{this.setSession({mode:"idle"}),this.speech.wake(),s().catch(e=>this.say(e.message,!0))};if(!i&&this.activated())return o();this.setSession({mode:"ready",title:e,verb:t,go:o,cancel:()=>this.setSession({mode:"idle"})})}async goToStart(e,t,s,i){if(!e.start||!this.options.start)return!0;sessionStorage.setItem(this.pendingKey(),JSON.stringify({demo:e,verb:t,from:s,loop:i}));return"reload"!==await this.options.start.go(e.start)&&(sessionStorage.removeItem(this.pendingKey()),!0)}busy(){return"idle"!==this.state.session.mode&&"ready"!==this.state.session.mode}play(e,t={}){return new Promise(s=>this.whenClicked(e.title,"Play",async()=>{if(this.busy())return s(void 0);if(this.say(void 0),!await this.goToStart(e,"play",t.from))return s(void 0);const i=await this.run(e,t);s(i)}))}async run(e,t={}){const{settings:s}=this.state,i=t.language??this.language(),o=s.music.on&&!t.checking&&!t.guided&&await Promise.race([this.loadMusic(),new Promise(e=>setTimeout(()=>e(!1),t.filming?6e4:1500))]);this.speech.setPack(s.usePacks?await this.pack(e):void 0);const n=new N(e,{language:i,subtitles:s.subtitles,waitForPresenter:s.waitForPresenter&&!t.looping,catchUp:s.catchUp,music:Boolean(o),...t},{hand:this.hand,targets:this.targets,overlay:this.overlay,speech:this.speech,plugins:this.plugins,ready:this.options.ready,read:(e,t)=>this.read(e,t),reset:async()=>!e.start||!this.options.start||"reload"!==await this.options.start.go(e.start),update:e=>this.updateSession("playing",e)});this.setSession({mode:"playing",title:e.title,demo:e,steps:e.steps.length,filming:Boolean(t.filming),checking:Boolean(t.checking),guided:Boolean(t.guided),looping:Boolean(t.looping),player:n,step:t.from??0,caption:"",paused:!1,waiting:!1,catchingUp:!1}),this.player=n;const a=await n.play().finally(()=>this.player=void 0);return this.setSession({mode:"idle"}),t.checking||a.navigated||(this.set({lastRun:{json:JSON.stringify(e),language:i,timing:a.timing}}),a.error&&"Stopped."!==a.error&&this.say(a.error,!0)),a}stop(){const e=this.state.session;"playing"===e.mode&&e.player.stop(),"recording"===e.mode&&this.stopRecording?.(),"ready"!==e.mode&&"preparing"!==e.mode||this.setSession({mode:"idle"})}togglePause(){const e=this.state.session;"playing"===e.mode&&(e.paused?e.player.resume():e.player.pause())}resume(){const e=this.state.session;"playing"===e.mode&&e.player.resume()}next(){const e=this.state.session;"playing"===e.mode&&e.player.next()}back(){const e=this.state.session;"playing"===e.mode&&e.player.back()}openPresenter(e={}){return I(this,e)}presenterKey(e){this.key(e)}present(e,t={}){const s=this.play(e,{...t,waitForPresenter:!0});return this.openPresenter(),s}goTo(e){const t=this.state.session;return"playing"===t.mode&&t.player.goTo(e)}guide(e,t={}){return this.play(e,{...t,guided:!0})}doItForMe(){const e=this.state.session;"playing"===e.mode&&e.player.doItForMe()}pack(e){let t=this.packs.get(e.id);return t||(t=(async()=>{const t=await this.store.asset(`narration:${e.id}`);if(t)return R(await t.arrayBuffer());const s=this.options.narration?.(e);if(!s)return;const i=await fetch(s);return i.ok?R(await i.arrayBuffer()):void 0})().catch(()=>{}),this.packs.set(e.id,t)),t}async makePack(e,s=()=>{}){const i=await this.pack(e);this.speech.setPack(i);const o=t(e).flatMap(t=>e.steps.flatMap(e=>n(e.say[t]??"").map(e=>({language:t,text:e})))),a=o.filter((e,t)=>o.findIndex(t=>t.language===e.language&&t.text===e.text)===t),r=[];for(const e of a)s(r.length,a.length),r.push({...await this.speech.packable(e.text,e.language),...e});s(r.length,a.length);const h=K(e.id,r);return await this.store.saveAsset(`narration:${e.id}`,h),this.packs.delete(e.id),h}async downloadPack(e){try{const t=await this.makePack(e,(e,t)=>this.say(`Making the narration pack: ${e} / ${t}`));b(t,`${e.id}.narration.zip`),this.say(`Narration pack: ${Math.round(t.size/1e5)/10} MB, kept here too. Check it in beside ${e.id}.demo.json, for every viewer.`)}catch(e){this.say(`Narration pack: ${e.message}`,!0)}}async dropPack(e){await this.store.saveAsset(`narration:${e.id}`,void 0),this.packs.delete(e.id)}async setMusic(e){await this.store.saveAsset("music",e),this.musicLoaded=void 0;const{music:t}=this.state.settings;this.changeSettings({music:e?{...t,on:!0,track:"file",name:e.name??"music"}:{...t,track:"calm",name:void 0}})}async loadMusic(){const{music:e}=this.state.settings,t="file"===e.track?`file:${e.name}`:e.track;if(this.musicLoaded!==t){if("file"===e.track){const t=await this.store.asset("music");if(!t)return!1;await this.speech.setMusic(t,e.volume).catch(()=>{})}else this.speech.setMusicBuffer(await M(e.track),e.volume);this.musicLoaded=t}return this.speech.setMusicVolume(e.volume),this.speech.hasMusic}async listenToMusic(e=20){if(this.speech.wake(),!await this.loadMusic())return()=>{};this.speech.startMusic();const t=setTimeout(()=>this.speech.stopMusic(),1e3*e);return()=>{clearTimeout(t),this.speech.stopMusic(.6)}}async loop(e,t={},s=0){if(0===e.length)return;this.stopLoop();let i=!1,o=0,n=s;const a=t.idle??this.state.settings.loopIdle,r=t.gap??1500,h=e.map(e=>e.title),p=e=>{if(!e.isTrusted||e.composedPath().includes(this.overlay.host))return;o=performance.now();const t=this.state.session;"playing"===t.mode&&t.looping&&t.player.stop(!0)},d=["pointerdown","keydown","wheel","touchstart"];d.forEach(e=>window.addEventListener(e,p,{capture:!0,passive:!0}));this.looping={demos:e,options:t,stop:()=>{i=!0,d.forEach(e=>window.removeEventListener(e,p,{capture:!0}));const e=this.state.session;"playing"===e.mode&&e.looping&&e.player.stop(),this.set({loop:void 0})}};const c=e=>new Promise(t=>setTimeout(t,e));for(;!i;){const s=e[n%e.length];this.set({loop:{titles:h,index:n%e.length,visitor:!1}});if(!await this.goToStart(s,"loop",void 0,{demos:e,index:n%e.length,gap:t.gap,idle:t.idle,reload:"reload"===t.reset})||i)return;const p=await this.run(s,{looping:!0,catchUp:!1});if(i)break;if(p.error&&performance.now()-o<1e3){for(;!i&&performance.now()-o<a;)this.set({loop:{titles:h,index:n%e.length,visitor:!0,resumesAt:Date.now()+a-(performance.now()-o)}}),await c(1e3);if(i)break;if("reload"===t.reset)return sessionStorage.setItem(this.pendingKey(),JSON.stringify({demo:s,verb:"loop",loop:{demos:e,index:n%e.length,gap:t.gap,idle:t.idle,reload:!0}})),window.location.reload();await(t.reset?.())}else n++,await c(r)}}stopLoop(){this.looping?.stop(),this.looping=void 0}elapsed(){const e=this.state.session;return"playing"===e.mode?e.player.elapsed():void 0}async check(e,t={}){const s=l(e,this.pluginKinds());if(s.length)return{ok:!1,problems:s,failures:[],duration:0,error:"Not a valid demo"};if(this.busy())return{ok:!1,problems:s,failures:[],duration:0,error:`Busy: ${this.state.session.mode}`};if(!1!==t.fromStart&&e.start&&this.options.start){if("reload"===await this.options.start.go(e.start))return{ok:!1,problems:s,failures:[],duration:0,error:"Its start reloads the page: check again once it is back"}}const i=await this.run(e,{...t,speed:t.speed??8,keepGoing:!0,checking:!0,catchUp:!0,subtitles:!1}),o=i.failures.map(t=>({...t,action:e.steps[t.step].actions[t.index]}));return{ok:!i.error&&0===o.length,error:i.error,failures:o,problems:s,duration:i.timing.duration}}timing(e,t=this.language()){const s=this.state.lastRun;return s&&s.language===t&&s.json===JSON.stringify(e)&&s.timing.steps.length===e.steps.length?s.timing:d(e,{language:t,sayTime:e=>this.speech.duration(e,t),actionTime:e=>{const t=this.pluginAction(e.do);return t?.duration?.(e)??p(e)}})}film(e,t={}){return new Promise(s=>this.whenClicked(e.title,"Film",async()=>this.busy()?s(void 0):(this.say(void 0),await this.goToStart(e,"film")?void s(await this.filmNow(e,t)):s(void 0))))}async filmNow(e,t){const s=t.language??this.language();let o=!1;const a=await E({soundtrack:this.speech.soundtrack(),microphone:t.microphone,crop:this.options.filmElement?.(),...this.filmQuality(),onEnded:()=>{o=!0,this.stop()}});let r;try{const t=e.steps.flatMap(e=>n(i(e,s)));this.setSession({mode:"preparing",title:e.title,text:"Preparing the narration"}),await this.speech.prepare(t,s,(e,t)=>this.updateSession("preparing",{text:`Preparing the narration: ${e} / ${t}`})),o||"preparing"!==this.state.session.mode||(r=await this.run(e,{language:s,filming:a}))}finally{"preparing"===this.state.session.mode&&this.setSession({mode:"idle"})}const{video:p,voice:d}=await a.stop();if(!r||r.error)return void this.say("Stopped."!==r?.error&&r?`Filming failed: ${r.error}`:"Filming stopped: nothing kept.",Boolean(r?.error&&"Stopped."!==r.error));let c=r.timing.cues;d&&"off"===this.state.settings.speech.voice&&(this.setSession({mode:"preparing",title:e.title,text:"Transcribing what was said"}),c=await this.transcribe(d,s).catch(()=>c),this.setSession({mode:"idle"}));const l={id:e.id,blob:p,at:Date.now(),json:JSON.stringify(e),vtt:h(c),timing:r.timing,language:s,...d?{voice:d}:{}};return await this.store.saveVideo(l),this.say(`Filmed "${e.title}": ${Math.round(p.size/1e6)} MB, kept here.`),l}filmQuality(){const{frameRate:e,bitrate:t,lines:s,aspect:i,fit:o}=this.state.settings.film;return{frameRate:e,bitrate:t,fit:o,...s?{size:$(s,i)}:{}}}async transcribe(e,t=this.language()){const{settings:s}=this.state;return w(e,{language:t,with:s.transcriber,model:s.whisperModel,elevenLabsKey:s.speech.elevenlabs.key,progress:e=>this.set({speech:e<1?{loading:e}:{}})})}record(e={}){return new Promise(t=>this.whenClicked(e.into?.title??"New demo","Record",async()=>{if(this.busy())return t();this.say(void 0),await this.recordNow(e,t)}))}async recordNow(t,i){const{settings:o}=this.state,n=this.language();let a,r;try{o.filmRecording?a=await E({soundtrack:this.speech.soundtrack(),microphone:o.microphone,crop:this.options.filmElement?.(),...this.filmQuality(),onEnded:()=>{this.stopRecording?.()}}):o.microphone&&(r=await j())}catch(e){return this.say(`Could not start: ${e.message}`,!0),i()}const p=this.options.start?.current(),d=new L(this.targets,this.plugins,n,e=>this.updateSession("recording",e));a?.resume();const c=performance.now();this.setSession({mode:"recording",filming:Boolean(a),microphone:Boolean(r||a&&o.microphone),step:0,caption:"",actions:0}),this.nextStepRecording=()=>d.nextStep(),this.sayRecording=e=>d.say(e),this.stopRecording=async()=>{this.stopRecording=this.nextStepRecording=this.sayRecording=void 0;const l=Boolean(r||a&&o.microphone),g=d.stop(l),m=performance.now()-c;this.setSession({mode:"preparing",title:"Recording",text:"Keeping what was recorded"});try{const[i,o]=await Promise.all([r?.stop(),a?.stop()]),d=i??o?.voice;let c=[];if(d){this.updateSession("preparing",{text:"Transcribing what was said"});try{c=await this.transcribe(d,n);const e=f(g.stepStarts,c);g.steps.forEach((t,s)=>{!t.say[n]&&e[s]&&(t.say[n]=e[s])})}catch(e){this.say(`Transcribing failed: ${e.message}`,!0)}}const l=g.steps.filter(e=>e.actions.length>0||Object.values(e.say).some(Boolean)),u=t.into?e(t.into):{...s("Recorded demo",p),steps:[]},y=t.after??u.steps.length-1,w={...u,steps:[...u.steps.slice(0,y+1),...l,...u.steps.slice(y+1)]};0===w.steps.length&&w.steps.push({say:{},actions:[]}),o&&await this.store.saveVideo({id:w.id,blob:o.video,at:Date.now(),json:JSON.stringify(w),vtt:h(c),language:n,timing:{duration:m,steps:g.stepStarts.map((e,t)=>({step:t,start:e,end:g.stepStarts[t+1]??m})),cues:c.map(e=>({...e,step:0})),actions:[]},...o.voice?{voice:o.voice}:{}}),this.setSession({mode:"idle"}),this.say(`Recorded ${l.length} step${1===l.length?"":"s"}${o?", and filmed":""}.`),t.into&&this.state.studio?.demo.id===t.into.id?this.set({studio:{...this.state.studio,recorded:{steps:w.steps,at:Date.now()}}}):this.openStudio(w)}catch(e){this.setSession({mode:"idle"}),this.say(e.message,!0)}i()}}nextStep(){this.nextStepRecording?.()}narrate(e){this.sayRecording?.(e)}async finishRecording(){await(this.stopRecording?.())}link(e){return P(e)}downloadDemo(e,t="json"){if("md"===t)return b(e.scenario??o(e,this.language()),S(e.id,"md"),"text/markdown");const{scenario:s,savedAt:i,...n}=e;b(JSON.stringify(n,null,2)+"\n",S(e.id,"demo.json"),"application/json")}downloadVideo(e,t,s=!1){return"vtt"===s?b(e.vtt,S(t,"vtt"),"text/vtt"):"srt"===s?b(r(a(e.vtt)),S(t,"srt"),"application/x-subrip"):void b(e.blob,S(t,T(e.blob)))}shareVideo(e,t){return x([new File([e.blob],S(t,T(e.blob)),{type:e.blob.type}),new File([e.vtt],S(t,"vtt"),{type:"text/vtt"})],t)}languagesOf(e){return t(e)}}export{O as DEFAULT_SETTINGS};
@@ -124,6 +124,8 @@ export declare class Player {
124
124
  goTo(step: number): boolean;
125
125
  /** The step playing, 0-based. */
126
126
  get step(): number;
127
+ /** ms played when the step playing started. */
128
+ get stepStartedAt(): number;
127
129
  private get waiting();
128
130
  private waitingNow;
129
131
  /** Guided: the demo does what the viewer was to do. */
package/engine/Player.js CHANGED
@@ -1 +1 @@
1
- import{DEFAULT_WAIT as t,isBuiltIn as e,isPresent as s,sayOf as i,sentences as o}from"../model/Demo.js";import{readingTime as a}from"../model/Timing.js";import{at as n}from"../page/Input.js";import{pointIn as r}from"../page/Targets.js";import{isGuided as h,waitForViewer as p}from"./Guided.js";const c=t=>new Promise(e=>setTimeout(e,t));export class Player{constructor(t,e,s){this.demo=t,this.options=e,this.context=s,this.stopped=!1,this.held=0,this.t0=performance.now(),this.silence=()=>{},this.hurrying=!1,this.dropping=!1,this.navigated=!1,this.stepNow=0,this.stepStart=0,this.last=0,this.skipViewer=()=>{},this.viewerDid=!1,this.keepApp=!1,this.waitingNow=!1,this.sleep=async t=>{let e=t/this.speed;for(;e>0&&!this.stopped&&!this.hurrying&&!this.dropping;){if(void 0!==this.pausedAt){await c(50);continue}const t=Math.min(e,50),s=performance.now();await c(t),e-=performance.now()-s}},this.speed=e.speed??1}elapsed(){return(this.pausedAt??performance.now())-this.t0-this.held}get paused(){return void 0!==this.pausedAt}pause(t=!1){void 0===this.pausedAt&&(this.pausedAt=performance.now(),this.waitingNow=t,this.context.speech.pause(),this.options.filming?.pause(),this.context.update({paused:!0,waiting:t}))}resume(){void 0!==this.pausedAt&&(this.held+=performance.now()-this.pausedAt,this.pausedAt=void 0,this.context.speech.resume(),this.options.filming?.resume(),this.context.update({paused:!1,waiting:!1}))}stop(t=!1){this.stopped=!0,this.keepApp=t,this.silence(),this.skipViewer(),this.resume()}viewerTarget(){return this.target?.()}get speedNow(){return this.hurrying?20:this.speed}next(){if(this.waiting)return this.resume();this.goTo(this.stepNow+1)}back(){const t=!this.waiting&&this.elapsed()-this.stepStart<3e3;this.goTo(t?this.stepNow-1:this.stepNow)}goTo(t){if(this.options.filming||this.stopped)return!1;const e=Math.max(0,Math.min(t,this.last));return!(e>this.stepNow&&this.stepNow===this.last)&&(this.jump=e,this.navigated=!0,e>this.stepNow?this.hurrying=!0:this.dropping=!0,this.silence(),this.skipViewer(),this.resume(),!0)}get step(){return this.stepNow}get waiting(){return void 0!==this.pausedAt&&this.waitingNow}doItForMe(){this.skipViewer()}async whilePaused(){for(;void 0!==this.pausedAt&&!this.stopped;)await c(50)}async find(t){const e=await this.context.targets.find(t,1e4,()=>this.stopped);if(!e)throw new Error(this.stopped?"Stopped.":`Not found: ${describeTarget(t)}`);return e}follow(t,e){let s=e;return()=>(s?.isConnected||(s=this.context.targets.matches(t)[t.index??0]),s)}async play(){const{demo:e,options:n,context:r}=this,p=n.language,d=Math.max(0,Math.min(n.from??0,e.steps.length-1)),l=Math.min(n.to??e.steps.length-1,e.steps.length-1),u=this.speed>1,w={duration:0,steps:[],cues:[],actions:[]},g=[];let f;const m=new Set;try{this.last=l,d>0&&!1!==n.catchUp&&await this.catchUp(0,d);const f=e.steps.map(t=>u?[]:o(i(t,p))),y=[...f.slice(d),...f.slice(0,d)].flat();y.forEach(t=>r.speech.make(t,p)?.catch(()=>{}));const v=y.map(t=>r.speech.make(t,p))[0]?.catch(()=>{});v&&await Promise.race([v,c(n.filming?6e5:3e3)]),await(r.ready?.()),this.t0=performance.now(),this.held=0,n.filming?.resume(),n.music&&!u&&r.speech.startMusic();let x=d;for(;x<=l&&!this.stopped;){const i=e.steps[x];this.stepNow=x,r.update({step:x,caption:""}),r.overlay.raise();const o=this.elapsed();this.stepStart=o;const c=[],y=f[x].map((t,e)=>new Promise(t=>c[e]=t));let v=!1,k=()=>{};const b=new Promise(t=>k=t),$=async()=>{for(const[t,e]of f[x].entries()){if(await this.whilePaused(),this.stopped||this.hurrying||this.dropping)break;const s=await r.speech.say(e,p,n.filming?1/0:0===t&&x===d?0:1500);await this.whilePaused();const i=this.elapsed();c[t](),!1!==n.subtitles&&r.overlay.subtitle(e),r.update({caption:e}),s?(this.silence=s.stop,this.hurrying&&s.stop(),await s.done):await this.sleep(a(e)),w.cues.push({step:x,start:i,end:this.elapsed(),text:e})}v=!0,c.forEach(t=>t()),k(),r.overlay.subtitle(void 0),r.update({caption:""})},N=async()=>{for(const[e,o]of i.actions.entries()){if(this.stopped||this.dropping)break;if(void 0===o.cue||v||u||await(y[o.cue]??b),await this.sleep(o.wait??t),await this.whilePaused(),this.stopped||this.dropping)break;if(this.hurrying&&s(o))continue;const i=this.elapsed(),a={step:x,index:e,start:i,end:i};w.actions.push(a);try{const t=n.guided&&h(o)&&!this.hurrying;t&&await this.viewerDoes(o);const e=t&&this.viewerDid?void 0:await this.perform(o,p);if(a.end=this.elapsed(),e){const t=()=>{m.delete(t)&&(e(),a.end=this.elapsed())};m.add(t);const s=o.for;void 0!==s&&this.sleep(s).then(t)}"clear"===o.do&&[...m].forEach(t=>t())}catch(t){const s=t.message;if(a.end=this.elapsed(),a.error=s,this.stopped)break;if(!n.keepGoing)throw new Error(`Step ${x+1}, action ${e+1} (${o.do}): ${s}`);g.push({step:x,index:e,error:s})}}};if(await Promise.all([$(),N()]),i.hold&&await this.sleep(i.hold),[...m].forEach(t=>t()),w.steps.push({step:x,start:o,end:this.elapsed()}),this.hurrying=!1,void 0===this.jump&&(i.pause||n.waitForPresenter)&&x<l&&!this.stopped&&!u&&(this.pause(!0),await this.whilePaused()),this.stopped)break;if(void 0!==this.jump){const t=this.jump;this.jump=void 0,this.dropping=!1,t<=x?await this.rewind(t):t>x+1&&await this.covered(t,()=>this.catchUp(x+1,t)),x=t;continue}x++}this.stopped||await this.sleep(u?0:1e3)}catch(t){f=t.message}finally{[...m].forEach(t=>t()),r.speech.stopMusic(),this.keepApp||await this.cleanup(),r.update({instruction:void 0}),r.overlay.clear(),r.overlay.subtitle(void 0),r.overlay.hideCursor(),r.hand.reset(),this.stopped&&(f??(f="Stopped."))}return w.duration=this.elapsed(),{timing:w,error:f,failures:g,...this.navigated?{navigated:!0}:{}}}async viewerDoes(t){this.viewerDid=!1;const e=t.target,s=e?await this.find(e):void 0;s?.scrollIntoView({block:"nearest",inline:"nearest"});const i=this.context.read(t,s);this.target=s&&e?this.follow(e,s):void 0;const o=s&&e?[this.context.overlay.show({kind:"ring",element:this.follow(e,s)}),this.context.overlay.show({kind:"callout",text:i,element:this.follow(e,s)})]:[this.context.overlay.show({kind:"callout",text:i,corner:"top-right"})];this.context.update({instruction:i});const a=p(t,this.context.targets);let n=!1;this.skipViewer=()=>{n=!0,a.cancel()},await a.done,this.target=void 0,this.skipViewer=()=>{},o.forEach(t=>t()),this.context.update({instruction:void 0}),this.viewerDid=!n}async cleanup(){const e=this.demo.cleanup??[];if(0===e.length)return;const[i,o]=[this.stopped,this.speed];this.stopped=!1,this.hurrying=!1,this.speed=Math.max(o,12),this.context.update({caption:""}),this.context.overlay.quiet=!0;try{for(const i of e)s(i)||(await this.sleep(Math.min(i.wait??t,1e3)),await this.perform(i,this.options.language).catch(()=>{}))}finally{this.context.overlay.quiet=!1,[this.stopped,this.speed]=[i,o]}}async covered(t,e){const s=this.demo.steps[t]?.title,i=this.context.overlay.show({kind:"card",title:`${t+1}${s?` · ${s}`:""}`,text:`${t+1} / ${this.last+1}`});this.context.overlay.quiet=!0,this.context.overlay.subtitle(void 0);try{await e()}finally{this.context.overlay.quiet=!1,this.context.overlay.hideCursor(),await c(250),i()}}async rewind(t){await this.covered(t,async()=>{this.context.overlay.clear(),await this.cleanup(),await(this.context.reset?.()),await this.catchUp(0,t)})}async catchUp(e,i){const o=this.speed;this.speed=Math.max(o,12),this.context.update({catchingUp:!0});try{for(let o=e;o<i&&!this.stopped;o++){this.context.update({step:o});for(const e of this.demo.steps[o].actions){if(this.stopped)return;if(!s(e)){await this.sleep(Math.min(e.wait??t,1500));try{await this.perform(e,this.options.language)}catch(t){throw new Error(`Catching up, step ${o+1}: ${t.message}`)}}}}await this.sleep(1500)}finally{this.speed=o,this.context.update({catchingUp:!1})}}async perform(t,s){const{hand:i,overlay:o}=this.context;if(!e(t)){const e=this.context.plugins.map(e=>e.actions?.[t.do]).find(Boolean);if(!e)throw new Error(`No plugin plays "${t.do}"`);const a={hand:i,overlay:o,targets:this.context.targets,language:s,speed:this.speed,find:t=>this.find(t),sleep:this.sleep,stopped:()=>this.stopped};return void await e.play(t,a)}const a=t=>o.show(t);switch(t.do){case"click":{const e=await this.find(t.target);return e.scrollIntoView({block:"nearest",inline:"nearest"}),i.click(e,n(e,t.at),t)}case"hover":{const e=await this.find(t.target);return e.scrollIntoView({block:"nearest",inline:"nearest"}),i.point(e,n(e,t.at))}case"type":{const e=await this.find(t.target);return e.scrollIntoView({block:"nearest",inline:"nearest"}),await i.point(e,n(e)),i.type(e,t.text)}case"key":{const e=t.target?await this.find(t.target):void 0;return this.speed<=1&&o.keys(t.key),i.key(t.key,e)}case"select":{const e=await this.find(t.target);if(!(e instanceof HTMLSelectElement))throw new Error("Not a <select>: click its options instead");return e.scrollIntoView({block:"nearest",inline:"nearest"}),i.select(e,t.option,n(e))}case"drag":{const e=await this.find(t.target);e.scrollIntoView({block:"nearest",inline:"nearest"});const s=n(e,t.at),o=t.to.target?await this.find(t.to.target):e;return i.drag(e,s,r(o,t.to.at),t)}case"scroll":{const e=t.target?await this.find(t.target):void 0;return i.scroll(e,t.by)}case"waitFor":{const e=performance.now()+(t.timeout??1e4);for(;!this.stopped;){if(this.context.targets.matches(t.target).some(t=>t.getClientRects().length>0)!==Boolean(t.gone))return;if(performance.now()>e)throw new Error(`${t.gone?"Still there":"Not found"}: ${describeTarget(t.target)}`);await c(100)}return}case"clear":return void o.clear();case"card":return a({kind:"card",title:t.title,text:t.text});case"callout":{const e=t.target?await this.find(t.target):void 0;return a({kind:"callout",text:t.text,side:t.side,corner:t.corner,element:e&&this.follow(t.target,e)})}default:{const e=await this.find(t.target);e.scrollIntoView({block:"nearest",inline:"nearest"});const s=this.follow(t.target,e);switch(t.do){case"spotlight":return a({kind:"spotlight",element:s,text:t.text,padding:t.padding});case"ring":return a({kind:"ring",element:s,text:t.text,color:t.color,shape:t.shape,padding:t.padding});case"arrow":return a({kind:"arrow",element:s,text:t.text,from:t.from,color:t.color});case"blur":return a({kind:"blur",element:s});case"zoom":{const e=a({kind:"zoom",element:s,scale:t.scale});return await this.sleep(700),e}}}}}}export function describeTarget(t){const e=t.key??t.text;return`${e?`"${e}" `:""}${t.css}${t.index?` #${t.index+1}`:""}`}
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}`:""}`}
package/index.d.ts CHANGED
@@ -23,5 +23,6 @@ export { GUIDE } from './agent/Guide';
23
23
  export { DemoLibrary, Library, Narration, Recording, Shadow } from './ui/Library';
24
24
  export { Studio } from './ui/Studio';
25
25
  export { Timeline } from './ui/Timeline';
26
+ export { openPresenter, mountPresenter } from './ui/Presenter';
26
27
  export { useEngine, useDemos } from './ui/Hooks';
27
28
  export { UI_CSS } from './ui/Styles';
package/index.js CHANGED
@@ -1 +1 @@
1
- export*from"./model/Demo.js";export*from"./model/Timing.js";export*from"./model/Subtitles.js";export*from"./model/Validate.js";export*from"./engine/DemoEngine.js";export*from"./engine/Player.js";export*from"./engine/Recorder.js";export*from"./engine/Plugin.js";export*from"./engine/Settings.js";export*from"./page/Targets.js";export*from"./page/Input.js";export*from"./page/Overlay.js";export*from"./speech/Speech.js";export*from"./speech/Transcribe.js";export*from"./speech/Pack.js";export*from"./speech/Music.js";export*from"./store/Zip.js";export*from"./video/Film.js";export*from"./store/Store.js";export*from"./store/Share.js";export*from"./agent/Agent.js";export{GUIDE}from"./agent/Guide.js";export{DemoLibrary,Library,Narration,Recording,Shadow}from"./ui/Library.js";export{Studio}from"./ui/Studio.js";export{Timeline}from"./ui/Timeline.js";export{useEngine,useDemos}from"./ui/Hooks.js";export{UI_CSS}from"./ui/Styles.js";
1
+ export*from"./model/Demo.js";export*from"./model/Timing.js";export*from"./model/Subtitles.js";export*from"./model/Validate.js";export*from"./engine/DemoEngine.js";export*from"./engine/Player.js";export*from"./engine/Recorder.js";export*from"./engine/Plugin.js";export*from"./engine/Settings.js";export*from"./page/Targets.js";export*from"./page/Input.js";export*from"./page/Overlay.js";export*from"./speech/Speech.js";export*from"./speech/Transcribe.js";export*from"./speech/Pack.js";export*from"./speech/Music.js";export*from"./store/Zip.js";export*from"./video/Film.js";export*from"./store/Store.js";export*from"./store/Share.js";export*from"./agent/Agent.js";export{GUIDE}from"./agent/Guide.js";export{DemoLibrary,Library,Narration,Recording,Shadow}from"./ui/Library.js";export{Studio}from"./ui/Studio.js";export{Timeline}from"./ui/Timeline.js";export{openPresenter,mountPresenter}from"./ui/Presenter.js";export{useEngine,useDemos}from"./ui/Hooks.js";export{UI_CSS}from"./ui/Styles.js";
package/model/Demo.d.ts CHANGED
@@ -28,6 +28,8 @@ export type DemoStep = {
28
28
  hold?: number;
29
29
  /** Wait for the presenter (→, Enter or Continue) once the step is done. */
30
30
  pause?: boolean;
31
+ /** For the presenter's screen only: never said, never shown to the audience. */
32
+ notes?: string;
31
33
  };
32
34
  /**
33
35
  * The `index`th element matching `css` whose label (`labelOf`) is the locale `key`'s text in the
package/model/Validate.js CHANGED
@@ -1 +1 @@
1
- import{BUILT_IN_KINDS as t,isTarget as e}from"./Demo.js";const o={click:["target"],hover:["target"],type:["target","text"],key:["key"],select:["target","option"],drag:["target","to"],scroll:[],waitFor:["target"],spotlight:["target"],ring:["target"],arrow:["target"],callout:["text"],blur:["target"],card:["title"],zoom:["target"],clear:[]},r=new Set(["target"]),n=["top","right","bottom","left"],a=["top-left","top-right","bottom-left","bottom-right"];export function validate(i,c=[]){const d=[],f=(t,e)=>d.push({path:t,message:e});if("object"!=typeof i||null===i)return[{path:"",message:"not an object"}];const g=i;if("string"==typeof g.id&&g.id||f("id","needs a string"),"string"==typeof g.title&&g.title||f("title","needs a string"),void 0!==g.description&&"string"!=typeof g.description&&f("description","is a string"),void 0===g.start||"object"==typeof g.start&&!Object.values(g.start).some(t=>"string"!=typeof t)||f("start","is an object of strings"),!Array.isArray(g.steps))return f("steps","needs an array"),d;const l=[...t,...c];return g.steps.forEach((t,e)=>{const o=`steps[${e}]`;return"object"!=typeof t||null===t?f(o,"not an object"):("object"!=typeof t.say||null===t.say||Array.isArray(t.say)?f(`${o}.say`,"needs an object: language → narration, {} for none"):Object.entries(t.say).forEach(([t,e])=>{"string"!=typeof e&&f(`${o}.say.${t}`,"is a string")}),Array.isArray(t.actions)?void t.actions.forEach((t,e)=>p(t,`${o}.actions[${e}]`)):f(`${o}.actions`,"needs an array, [] for none"))}),void 0!==g.cleanup&&(Array.isArray(g.cleanup)?g.cleanup.forEach((t,e)=>p(t,`cleanup[${e}]`)):f("cleanup","needs an array of actions")),d;function p(t,i){if("object"!=typeof t||null===t)return f(i,"not an object");if(!l.includes(t.do))return f(`${i}.do`,`unknown action "${t.do}": one of ${l.join(", ")}`);for(const n of o[t.do]??[]){const o=t[n];void 0===o||""===o&&"text"!==n?f(`${i}.${n}`,"is required"):r.has(n)&&!e(o)&&f(`${i}.${n}`,"needs { css, text?, key?, index? }")}void 0!==t.wait&&("number"!=typeof t.wait||t.wait<0)&&f(`${i}.wait`,"is ms, 0 or more"),void 0!==t.cue&&(!Number.isInteger(t.cue)||t.cue<0)&&f(`${i}.cue`,"is a sentence's index, 0 or more");const c=t;if(void 0===c.at||s(c.at)||f(`${i}.at`,"is [x, y], fractions of the box"),void 0===c.from||n.includes(c.from)||f(`${i}.from`,`one of ${n.join(", ")}`),void 0===c.side||n.includes(c.side)||f(`${i}.side`,`one of ${n.join(", ")}`),void 0===c.corner||a.includes(c.corner)||f(`${i}.corner`,`one of ${a.join(", ")}`),"drag"===t.do){const t=c.to;t&&void 0!==t.target&&!e(t.target)&&f(`${i}.to.target`,"needs { css, text?, key?, index? }"),t&&void 0!==t.at&&!s(t.at)&&f(`${i}.to.at`,"is [x, y], fractions of the box"),t&&void 0===t.target&&void 0===t.at&&f(`${i}.to`,"needs a target, an at, or both")}}}function s(t){return Array.isArray(t)&&2===t.length&&t.every(t=>"number"==typeof t&&Number.isFinite(t))}export function parseDemo(t,e=[]){let o;try{o=JSON.parse(t)}catch(t){return{problems:[{path:"",message:t.message}]}}const r=validate(o,e);return r.length?{problems:r}:{demo:o,problems:r}}
1
+ import{BUILT_IN_KINDS as t,isTarget as e}from"./Demo.js";const o={click:["target"],hover:["target"],type:["target","text"],key:["key"],select:["target","option"],drag:["target","to"],scroll:[],waitFor:["target"],spotlight:["target"],ring:["target"],arrow:["target"],callout:["text"],blur:["target"],card:["title"],zoom:["target"],clear:[]},r=new Set(["target"]),n=["top","right","bottom","left"],a=["top-left","top-right","bottom-left","bottom-right"];export function validate(i,c=[]){const d=[],f=(t,e)=>d.push({path:t,message:e});if("object"!=typeof i||null===i)return[{path:"",message:"not an object"}];const g=i;if("string"==typeof g.id&&g.id||f("id","needs a string"),"string"==typeof g.title&&g.title||f("title","needs a string"),void 0!==g.description&&"string"!=typeof g.description&&f("description","is a string"),void 0===g.start||"object"==typeof g.start&&!Object.values(g.start).some(t=>"string"!=typeof t)||f("start","is an object of strings"),!Array.isArray(g.steps))return f("steps","needs an array"),d;const l=[...t,...c];return g.steps.forEach((t,e)=>{const o=`steps[${e}]`;return"object"!=typeof t||null===t?f(o,"not an object"):("object"!=typeof t.say||null===t.say||Array.isArray(t.say)?f(`${o}.say`,"needs an object: language → narration, {} for none"):Object.entries(t.say).forEach(([t,e])=>{"string"!=typeof e&&f(`${o}.say.${t}`,"is a string")}),void 0!==t.notes&&"string"!=typeof t.notes&&f(`${o}.notes`,"is a string"),Array.isArray(t.actions)?void t.actions.forEach((t,e)=>p(t,`${o}.actions[${e}]`)):f(`${o}.actions`,"needs an array, [] for none"))}),void 0!==g.cleanup&&(Array.isArray(g.cleanup)?g.cleanup.forEach((t,e)=>p(t,`cleanup[${e}]`)):f("cleanup","needs an array of actions")),d;function p(t,i){if("object"!=typeof t||null===t)return f(i,"not an object");if(!l.includes(t.do))return f(`${i}.do`,`unknown action "${t.do}": one of ${l.join(", ")}`);for(const n of o[t.do]??[]){const o=t[n];void 0===o||""===o&&"text"!==n?f(`${i}.${n}`,"is required"):r.has(n)&&!e(o)&&f(`${i}.${n}`,"needs { css, text?, key?, index? }")}void 0!==t.wait&&("number"!=typeof t.wait||t.wait<0)&&f(`${i}.wait`,"is ms, 0 or more"),void 0!==t.cue&&(!Number.isInteger(t.cue)||t.cue<0)&&f(`${i}.cue`,"is a sentence's index, 0 or more");const c=t;if(void 0===c.at||s(c.at)||f(`${i}.at`,"is [x, y], fractions of the box"),void 0===c.from||n.includes(c.from)||f(`${i}.from`,`one of ${n.join(", ")}`),void 0===c.side||n.includes(c.side)||f(`${i}.side`,`one of ${n.join(", ")}`),void 0===c.corner||a.includes(c.corner)||f(`${i}.corner`,`one of ${a.join(", ")}`),"drag"===t.do){const t=c.to;t&&void 0!==t.target&&!e(t.target)&&f(`${i}.to.target`,"needs { css, text?, key?, index? }"),t&&void 0!==t.at&&!s(t.at)&&f(`${i}.to.at`,"is [x, y], fractions of the box"),t&&void 0===t.target&&void 0===t.at&&f(`${i}.to`,"needs a target, an at, or both")}}}function s(t){return Array.isArray(t)&&2===t.length&&t.every(t=>"number"==typeof t&&Number.isFinite(t))}export function parseDemo(t,e=[]){let o;try{o=JSON.parse(t)}catch(t){return{problems:[{path:"",message:t.message}]}}const r=validate(o,e);return r.length?{problems:r}:{demo:o,problems:r}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protomaze/demo-engine",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
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",
package/ui/EngineUI.js CHANGED
@@ -1 +1 @@
1
- import e,{useEffect as t,useState as a}from"react";import{createRoot as n}from"react-dom/client";import{useEngine as l}from"./Hooks.js";import{Button as i,Icon as o,Menu as s,useTheme as m}from"./Kit.js";import{Library as r}from"./Library.js";import{Studio as c}from"./Studio.js";import{UI_CSS as d}from"./Styles.js";export function mountUI(t){t.overlay.addStyles(d);const a=n(t.overlay.ui);return a.render(e.createElement(p,{engine:t})),()=>a.unmount()}function p({engine:t}){const n=l(t),d=m(t.options.theme??"dark"),[p,h]=a(!1),{session:E}=n,f="playing"===E.mode&&(E.filming&&!E.paused||E.looping)||"recording"===E.mode&&E.filming;return e.createElement(e.Fragment,null,"ready"===E.mode&&e.createElement("div",{className:"pde ready","data-theme":d,onClick:e=>e.target===e.currentTarget&&E.cancel()},e.createElement("div",{className:"box"},e.createElement(i,{icon:"Film"===E.verb?"film":"Record"===E.verb?"record":"play",kind:"primary",autoFocus:!0,onClick:E.go},E.verb," “",E.title,"”"),e.createElement("div",{className:"small muted"},"A click here, in the app's window, lets it speak","Play"===E.verb?"":" and be filmed","."),e.createElement(i,{kind:"bare",onClick:E.cancel},"Cancel"))),"preparing"===E.mode&&e.createElement("div",{className:"pde bar","data-theme":d},e.createElement("span",null,E.title),e.createElement("span",{className:"muted"},E.text),void 0!==n.speech.loading&&e.createElement("span",{className:"muted"},Math.round(100*n.speech.loading)," %"),e.createElement(i,{icon:"stop",small:!0,kind:"bare",title:"Stop",onClick:()=>t.stop()})),"playing"===E.mode&&!E.checking&&!f&&e.createElement("div",{className:"pde bar","data-theme":d},E.filming&&e.createElement("span",{className:"dot",title:"Filming: paused time is left out"}),e.createElement("span",{className:"ellipsis",style:{maxWidth:320}},E.title),!E.filming&&e.createElement(i,{icon:"back",small:!0,kind:"bare",title:"Back: this step again; pressed early, the one before (←, PageUp)",onClick:()=>t.back()}),E.filming?e.createElement("span",{className:"muted"},`${E.step+1} / ${E.steps}`):e.createElement(s,{title:"Go to a step (1-9, Home, End)",icon:"expand",label:e.createElement("span",{className:"muted"},E.catchingUp?`… ${E.step+1}`:`${E.step+1} / ${E.steps}`),align:"left",items:E.demo.steps.map((a,n)=>({label:e.createElement("span",{style:{fontWeight:n===E.step?700:400}},`${n+1}. ${a.title??(Object.values(a.say).find(Boolean)??"").slice(0,48)}`),onClick:()=>t.goTo(n)}))}),void 0!==n.speech.loading&&e.createElement("span",{className:"muted small",title:"Downloaded once, then kept by the browser: subtitles meanwhile"},"voice ",Math.round(100*n.speech.loading)," %"),n.hint&&e.createElement("span",{className:"small",style:{color:"var(--accent)"}},n.hint),E.paused&&!E.waiting&&!n.hint&&e.createElement("span",{className:"muted small",title:"What you do now, the demo goes on from"},"paused: the app is yours"),E.guided&&E.instruction&&e.createElement("span",{className:"ellipsis",style:{maxWidth:360,fontWeight:600}},E.instruction),E.guided&&E.instruction&&e.createElement(i,{icon:"flash",title:"The demo does it",onClick:()=>t.doItForMe()},"Do it for me"),e.createElement(i,{icon:E.paused?"play":"pause",kind:E.paused?"primary":void 0,title:"Space",onClick:()=>E.waiting?t.next():t.togglePause()},E.waiting?"Continue":E.paused?"Resume":"Pause"),!E.waiting&&e.createElement(i,{icon:"right",title:"Next step (→, PageDown)",onClick:()=>t.next()}),e.createElement(i,{icon:"stop",title:"Esc",onClick:()=>t.stop()},E.guided?"Exit":"Stop")),n.loop?.visitor&&e.createElement("div",{className:"pde bar","data-theme":d,style:{top:"auto",bottom:12,left:"auto",right:12,transform:"none",padding:"4px 6px 4px 12px",opacity:.85}},e.createElement(o,{name:"loop"}),e.createElement("span",{className:"small muted"},"The demo plays again after ",Math.round(t.getState().settings.loopIdle/1e3)," s without input"),e.createElement(i,{icon:"stop",small:!0,kind:"bare",title:"Stop the loop (Ctrl+Shift+L)",onClick:()=>t.stopLoop()})),"recording"===E.mode&&e.createElement(u,{engine:t,theme:d,filmed:E.filming}),n.message&&"idle"===E.mode&&e.createElement(g,{engine:t,theme:d,text:n.message.text,error:n.message.error}),n.studio&&!f&&e.createElement(c,{key:n.studio.opened,engine:t,theme:d}),t.options.launcher&&"idle"===E.mode&&!n.loop&&!n.studio&&e.createElement(e.Fragment,null,e.createElement("div",{className:"pde launcher","data-theme":d},e.createElement(i,{kind:p?"primary":void 0,onClick:()=>h(!p)},e.createElement(o,{name:"demos"}),"Demos")),p&&e.createElement(r,{engine:t,theme:d,floating:!0})))}function u({engine:t,theme:a,filmed:n}){const{session:o}=l(t);return"recording"!==o.mode?null:n?e.createElement("div",{className:"pde bar","data-theme":a,style:{top:"auto",bottom:12,padding:"4px 6px 4px 10px"}},e.createElement("span",{className:"dot"}),e.createElement("span",{className:"small muted"},"Step ",o.step+1),e.createElement(i,{icon:"right",small:!0,kind:"bare",title:"Next step (Alt+N)",onClick:()=>t.nextStep()}),e.createElement(i,{icon:"stop",small:!0,kind:"bare",title:"Stop (Esc)",onClick:()=>{t.finishRecording()}})):e.createElement("div",{className:"pde bar","data-theme":a},e.createElement("span",{className:"dot"}),e.createElement("span",null,"Step ",o.step+1),e.createElement("span",{className:"muted small"},o.actions," action",1===o.actions?"":"s",o.microphone?" · 🎙 listening":""),!o.microphone&&e.createElement("input",{className:"field",style:{width:340},placeholder:"This step's narration (or leave it for later)",value:o.caption,onChange:e=>t.narrate(e.target.value)}),e.createElement(i,{icon:"right",title:"Alt+N",onClick:()=>t.nextStep()},"Next step"),e.createElement(i,{icon:"stop",kind:"primary",title:"Esc",onClick:()=>{t.finishRecording()}},"Stop"),e.createElement("span",{className:"small muted"},"Alt+H: hover here"))}function g({engine:a,theme:n,text:l,error:o}){return t(()=>{if(o)return;const e=setTimeout(()=>a.say(void 0),6e3);return()=>clearTimeout(e)},[l]),e.createElement("div",{className:"pde toast"+(o?" error":""),"data-theme":n,style:{bottom:a.getState().studio?"auto":24,top:a.getState().studio?70:"auto"}},e.createElement("span",{className:"grow"},l),e.createElement(i,{icon:"close",small:!0,kind:"bare",title:"Close",onClick:()=>a.say(void 0)}))}
1
+ import e,{useEffect as t,useState as a}from"react";import{createRoot as n}from"react-dom/client";import{useEngine as l}from"./Hooks.js";import{Button as i,Icon as o,Menu as s,useTheme as r}from"./Kit.js";import{Library as m}from"./Library.js";import{Studio as c}from"./Studio.js";import{UI_CSS as d}from"./Styles.js";export function mountUI(t){t.overlay.addStyles(d);const a=n(t.overlay.ui);return a.render(e.createElement(p,{engine:t})),()=>a.unmount()}function p({engine:t}){const n=l(t),d=r(t.options.theme??"dark"),[p,h]=a(!1),{session:E}=n,f="playing"===E.mode&&(E.filming&&!E.paused||E.looping)||"recording"===E.mode&&E.filming;return e.createElement(e.Fragment,null,"ready"===E.mode&&e.createElement("div",{className:"pde ready","data-theme":d,onClick:e=>e.target===e.currentTarget&&E.cancel()},e.createElement("div",{className:"box"},e.createElement(i,{icon:"Film"===E.verb?"film":"Record"===E.verb?"record":"play",kind:"primary",autoFocus:!0,onClick:E.go},E.verb," “",E.title,"”"),e.createElement("div",{className:"small muted"},"A click here, in the app's window, lets it speak","Play"===E.verb?"":" and be filmed","."),e.createElement(i,{kind:"bare",onClick:E.cancel},"Cancel"))),"preparing"===E.mode&&e.createElement("div",{className:"pde bar","data-theme":d},e.createElement("span",null,E.title),e.createElement("span",{className:"muted"},E.text),void 0!==n.speech.loading&&e.createElement("span",{className:"muted"},Math.round(100*n.speech.loading)," %"),e.createElement(i,{icon:"stop",small:!0,kind:"bare",title:"Stop",onClick:()=>t.stop()})),"playing"===E.mode&&!E.checking&&!f&&e.createElement("div",{className:"pde bar","data-theme":d},E.filming&&e.createElement("span",{className:"dot",title:"Filming: paused time is left out"}),e.createElement("span",{className:"ellipsis",style:{maxWidth:320}},E.title),!E.filming&&e.createElement(i,{icon:"back",small:!0,kind:"bare",title:"Back: this step again; pressed early, the one before (←, PageUp)",onClick:()=>t.back()}),E.filming?e.createElement("span",{className:"muted"},`${E.step+1} / ${E.steps}`):e.createElement(s,{title:"Go to a step (1-9, Home, End)",icon:"expand",label:e.createElement("span",{className:"muted"},E.catchingUp?`… ${E.step+1}`:`${E.step+1} / ${E.steps}`),align:"left",items:E.demo.steps.map((a,n)=>({label:e.createElement("span",{style:{fontWeight:n===E.step?700:400}},`${n+1}. ${a.title??(Object.values(a.say).find(Boolean)??"").slice(0,48)}`),onClick:()=>t.goTo(n)}))}),void 0!==n.speech.loading&&e.createElement("span",{className:"muted small",title:"Downloaded once, then kept by the browser: subtitles meanwhile"},"voice ",Math.round(100*n.speech.loading)," %"),n.hint&&e.createElement("span",{className:"small",style:{color:"var(--accent)"}},n.hint),E.paused&&!E.waiting&&!n.hint&&e.createElement("span",{className:"muted small",title:"What you do now, the demo goes on from"},"paused: the app is yours"),E.guided&&E.instruction&&e.createElement("span",{className:"ellipsis",style:{maxWidth:360,fontWeight:600}},E.instruction),E.guided&&E.instruction&&e.createElement(i,{icon:"flash",title:"The demo does it",onClick:()=>t.doItForMe()},"Do it for me"),e.createElement(i,{icon:E.paused?"play":"pause",kind:E.paused?"primary":void 0,title:"Space",onClick:()=>E.waiting?t.next():t.togglePause()},E.waiting?"Continue":E.paused?"Resume":"Pause"),!E.waiting&&e.createElement(i,{icon:"right",title:"Next step (→, PageDown)",onClick:()=>t.next()}),e.createElement(i,{icon:"present",kind:"bare",title:"The presenter's screen, in a window of its own",onClick:()=>{t.openPresenter()}}),e.createElement(i,{icon:"stop",title:"Esc",onClick:()=>t.stop()},E.guided?"Exit":"Stop")),n.loop?.visitor&&e.createElement("div",{className:"pde bar","data-theme":d,style:{top:"auto",bottom:12,left:"auto",right:12,transform:"none",padding:"4px 6px 4px 12px",opacity:.85}},e.createElement(o,{name:"loop"}),e.createElement("span",{className:"small muted"},"The demo plays again after ",Math.round(t.getState().settings.loopIdle/1e3)," s without input"),e.createElement(i,{icon:"stop",small:!0,kind:"bare",title:"Stop the loop (Ctrl+Shift+L)",onClick:()=>t.stopLoop()})),"recording"===E.mode&&e.createElement(u,{engine:t,theme:d,filmed:E.filming}),n.message&&"idle"===E.mode&&e.createElement(g,{engine:t,theme:d,text:n.message.text,error:n.message.error}),n.studio&&!f&&e.createElement(c,{key:n.studio.opened,engine:t,theme:d}),t.options.launcher&&"idle"===E.mode&&!n.loop&&!n.studio&&e.createElement(e.Fragment,null,e.createElement("div",{className:"pde launcher","data-theme":d},e.createElement(i,{kind:p?"primary":void 0,onClick:()=>h(!p)},e.createElement(o,{name:"demos"}),"Demos")),p&&e.createElement(m,{engine:t,theme:d,floating:!0})))}function u({engine:t,theme:a,filmed:n}){const{session:o}=l(t);return"recording"!==o.mode?null:n?e.createElement("div",{className:"pde bar","data-theme":a,style:{top:"auto",bottom:12,padding:"4px 6px 4px 10px"}},e.createElement("span",{className:"dot"}),e.createElement("span",{className:"small muted"},"Step ",o.step+1),e.createElement(i,{icon:"right",small:!0,kind:"bare",title:"Next step (Alt+N)",onClick:()=>t.nextStep()}),e.createElement(i,{icon:"stop",small:!0,kind:"bare",title:"Stop (Esc)",onClick:()=>{t.finishRecording()}})):e.createElement("div",{className:"pde bar","data-theme":a},e.createElement("span",{className:"dot"}),e.createElement("span",null,"Step ",o.step+1),e.createElement("span",{className:"muted small"},o.actions," action",1===o.actions?"":"s",o.microphone?" · 🎙 listening":""),!o.microphone&&e.createElement("input",{className:"field",style:{width:340},placeholder:"This step's narration (or leave it for later)",value:o.caption,onChange:e=>t.narrate(e.target.value)}),e.createElement(i,{icon:"right",title:"Alt+N",onClick:()=>t.nextStep()},"Next step"),e.createElement(i,{icon:"stop",kind:"primary",title:"Esc",onClick:()=>{t.finishRecording()}},"Stop"),e.createElement("span",{className:"small muted"},"Alt+H: hover here"))}function g({engine:a,theme:n,text:l,error:o}){return t(()=>{if(o)return;const e=setTimeout(()=>a.say(void 0),6e3);return()=>clearTimeout(e)},[l]),e.createElement("div",{className:"pde toast"+(o?" error":""),"data-theme":n,style:{bottom:a.getState().studio?"auto":24,top:a.getState().studio?70:"auto"}},e.createElement("span",{className:"grow"},l),e.createElement(i,{icon:"close",small:!0,kind:"bare",title:"Close",onClick:()=>a.say(void 0)}))}
package/ui/Library.js CHANGED
@@ -1 +1 @@
1
- import e,{useEffect as t,useLayoutEffect as a,useRef as n,useState as l}from"react";import{createPortal as o}from"react-dom";import{clock as i}from"../model/Timing.js";import{elevenLabsVoices as r,KOKORO_VOICES as s,piperVoices as c}from"../speech/Speech.js";import{MUSIC_TRACKS as m}from"../speech/Music.js";import{videoSize as d}from"../video/Film.js";import{pickFile as p}from"../store/Share.js";import{useDemos as h,useEngine as g}from"./Hooks.js";import{Button as u,Check as E,Icon as v,Labelled as b,Menu as f,Segmented as w,useTheme as y}from"./Kit.js";import{UI_CSS as k}from"./Styles.js";const N=[["free","Free","Neural voices in the browser, no key: Kokoro for English, Piper for ~40 languages. Downloaded once (80-330 MB), then kept."],["elevenlabs","ElevenLabs","Premium voices with your own key. Each sentence is paid for once, then kept in this browser."],["system","System","The browser's own voices: instant, but videos don't hear them."],["off","Off","Subtitles only, timed to reading."]];export function DemoLibrary({engine:t,theme:a}){const n=y(a??t.options.theme??"auto");return e.createElement(Shadow,null,e.createElement(Library,{engine:t,theme:n}))}export function Shadow({children:t}){const i=n(null),[r,s]=l();return a(()=>{const e=i.current,t=e.shadowRoot??e.attachShadow({mode:"open"});if(!t.querySelector("style[data-pde]")){const a=e.ownerDocument.createElement("style");a.setAttribute("data-pde",""),a.textContent=k,t.append(a)}s(t)},[]),e.createElement("div",{ref:i,"data-demo-ignore":!0,style:{display:"contents"}},r&&o(t,r))}export function Library({engine:t,theme:a,floating:n}){const l=g(t),o=h(t),i="idle"!==l.session.mode,r=async e=>{const{demo:a,problems:n}=t.parse(e);if(!a)return t.say(`Not a demo: ${n.slice(0,3).map(e=>`${e.path||"demo"} ${e.message}`).join("; ")}`,!0);await t.save(a),t.openStudio(a)};return e.createElement("div",{className:"pde library"+(n?" floating":""),"data-theme":a,"data-demo-ignore":!0},l.message&&e.createElement("div",{className:"small "+(l.message.error?"error":"muted")},l.message.text),e.createElement("section",{className:"section"},e.createElement("h3",null,"Demos"),0===o.length&&e.createElement("div",{className:"small muted"},"None yet: record one, or ask an AI to make one (demoEngine.help())."),o.map(a=>e.createElement(S,{key:a.demo.id,engine:t,entry:a,busy:i})),e.createElement("div",{className:"row",style:{flexWrap:"wrap"}},l.loop?e.createElement(u,{icon:"stop",onClick:()=>t.stopLoop()},"Stop the loop"):e.createElement(u,{icon:"loop",disabled:i||0===o.length,title:"Every demo, one after the other, again and again: an expo booth",onClick:()=>{t.loop(o.map(e=>e.demo))}},"Loop all"),e.createElement(u,{icon:"record",disabled:i,onClick:()=>{t.record()},style:{color:"var(--danger)"}},"Record"),e.createElement(u,{icon:"add",disabled:i,onClick:()=>t.openStudio(t.create())},"New"),e.createElement(u,{icon:"upload",onClick:()=>{p().then(e=>e?.text()).then(e=>{if(e)return r(e)})}},"Import"),e.createElement(u,{icon:"copy",title:"Paste a demo’s JSON",onClick:()=>{navigator.clipboard.readText().then(r,()=>t.say("Could not read the clipboard",!0))}},"Paste"))),e.createElement(Narration,{engine:t}),e.createElement(Production,{engine:t}),e.createElement(Recording,{engine:t}))}export function Production({engine:t}){const{settings:a}=g(t),{music:n,film:o}=a,[i,r]=l(),s=n.on?n.track:"none",c=o.lines?d(o.lines,o.aspect):void 0,h={width:Math.round(innerWidth*devicePixelRatio),height:Math.round(innerHeight*devicePixelRatio)};return e.createElement("section",{className:"section"},e.createElement("h3",null,"Production"),e.createElement("div",{className:"row",style:{flexWrap:"wrap",gap:10,alignItems:"flex-end"}},e.createElement(b,{label:"Music"},e.createElement("select",{className:"field",value:s,onChange:e=>(e=>{if(i?.(),r(void 0),"none"===e)return t.changeSettings({music:{...n,on:!1}});"pick"!==e?t.changeSettings({music:{...n,on:!0,track:e}}):p("audio/*").then(e=>e&&t.setMusic(e))})(e.target.value)},e.createElement("option",{value:"none"},"None"),m.map(t=>e.createElement("option",{key:t.id,value:t.id,title:t.hint},t.name)),n.name&&e.createElement("option",{value:"file"},n.name),e.createElement("option",{value:"pick"},"Your own file…"))),e.createElement(u,{small:!0,icon:i?"stop":"listen",disabled:!n.on,onClick:()=>{(async()=>{if(i)return i(),r(void 0);const e=await t.listenToMusic(20);r(()=>e),setTimeout(()=>r(void 0),2e4)})()}},i?"Stop":"Listen"),e.createElement(b,{label:`Volume ${Math.round(100*n.volume)} %`},e.createElement("input",{type:"range",min:.02,max:.6,step:.01,value:n.volume,disabled:!n.on,onChange:e=>{t.changeSettings({music:{...n,volume:Number(e.target.value)}}),t.speech.setMusicVolume(Number(e.target.value))}}))),e.createElement("div",{className:"small muted"},n.on&&"file"!==n.track?`${m.find(e=>e.id===n.track)?.hint}. Composed by the engine: free to use anywhere. `:"","Under the narration, quieter while it speaks; in videos too."),e.createElement("div",{className:"row",style:{flexWrap:"wrap",gap:10}},e.createElement(b,{label:"Video size"},e.createElement("select",{className:"field",value:o.lines,onChange:e=>t.changeSettings({film:{...o,lines:Number(e.target.value)}})},e.createElement("option",{value:0},"The tab's own (",h.width,"×",h.height,")"),[720,1080,1440,2160].map(t=>{const{width:a,height:n}=d(t,o.aspect);return e.createElement("option",{key:t,value:t},2160===t?"4K":`${t}p`," (",a,"×",n,")")}))),o.lines>0&&e.createElement(e.Fragment,null,e.createElement(b,{label:"Shape"},e.createElement("select",{className:"field",value:o.aspect,onChange:e=>t.changeSettings({film:{...o,aspect:e.target.value}})},e.createElement("option",{value:"16:9"},"16:9 landscape"),e.createElement("option",{value:"9:16"},"9:16 portrait"),e.createElement("option",{value:"1:1"},"1:1 square"))),e.createElement(b,{label:"The tab"},e.createElement("select",{className:"field",value:o.fit,onChange:e=>t.changeSettings({film:{...o,fit:e.target.value}})},e.createElement("option",{value:"fit"},"Whole, with bars"),e.createElement("option",{value:"fill"},"Filling it, edges cut")))),e.createElement(b,{label:"Frames"},e.createElement("select",{className:"field",value:o.frameRate,onChange:e=>t.changeSettings({film:{...o,frameRate:Number(e.target.value)}})},e.createElement("option",{value:30},"30 a second"),e.createElement("option",{value:60},"60 a second"))),e.createElement(b,{label:"Quality"},e.createElement("select",{className:"field",value:o.bitrate,onChange:e=>t.changeSettings({film:{...o,bitrate:Number(e.target.value)}})},e.createElement("option",{value:4},"Small (4 Mb/s)"),e.createElement("option",{value:8},"Good (8 Mb/s)"),e.createElement("option",{value:16},"High (16 Mb/s)"),e.createElement("option",{value:25},"Master (25 Mb/s)")))),c&&(c.width>1.05*h.width||c.height>1.05*h.height)&&e.createElement("div",{className:"small muted"},"The tab is ",h.width,"×",h.height,": a ",c.width,"×",c.height," video scales it up, a little soft. A bigger window, or a screen with more pixels, keeps it sharp."),e.createElement("div",{className:"row",style:{flexWrap:"wrap",gap:10}},e.createElement(b,{label:"Loop: plays again after"},e.createElement("select",{className:"field",value:a.loopIdle,onChange:e=>t.changeSettings({loopIdle:Number(e.target.value)})},[10,20,30,60,120].map(t=>e.createElement("option",{key:t,value:1e3*t},t," s idle"))))))}function S({engine:t,entry:a,busy:n}){const{demo:l,origin:o,video:r}=a,s=i(t.timing(l).duration);return e.createElement("div",{className:"demo"},e.createElement("div",{className:"row"},e.createElement("span",{className:"title grow ellipsis",title:l.description},l.title),"app"!==o&&e.createElement("span",{className:"badge"},"edited"===o?"edited here":"made here"),r&&e.createElement("span",{className:"badge accent",title:`Filmed ${new Date(r.at).toLocaleString()}`},"video")),l.description&&e.createElement("div",{className:"small muted"},l.description),e.createElement("div",{className:"row"},e.createElement("span",{className:"small muted grow"},l.steps.length," steps · ~",s," · ",t.languagesOf(l).join(", ")||"no narration"),e.createElement(u,{icon:"play",small:!0,kind:"primary",title:"Play",disabled:n,onClick:()=>{t.play(l)}}),e.createElement(u,{icon:"film",small:!0,title:"Film: a video with narration and subtitles",disabled:n,onClick:()=>{t.film(l)}}),e.createElement(u,{icon:"edit",small:!0,title:"Open in the studio",onClick:()=>t.openStudio(l)}),e.createElement(f,{title:"More",items:[{heading:"Play"},{label:"Present: waits after each step",icon:"present",disabled:n,onClick:()=>{t.play(l,{waitForPresenter:!0})}},{label:"Guide: the viewer does it",icon:"guide",disabled:n,onClick:()=>{t.guide(l)}},{label:"Loop it: an expo booth",icon:"loop",disabled:n,onClick:()=>{t.loop([l])}},{heading:"Share"},{label:"Copy a link with the demo",icon:"link",onClick:()=>{t.link(l).then(e=>navigator.clipboard.writeText(e)).then(()=>t.say("Link copied."))}},{label:"Download .demo.json",icon:"download",onClick:()=>t.downloadDemo(l)},{label:"Download scenario .md",icon:"download",onClick:()=>t.downloadDemo({...l,scenario:a.scenario},"md")},{label:"Narration pack (.zip)",icon:"listen",onClick:()=>{t.downloadPack(l)}},r&&{heading:"Video"},r&&{label:"Download the video",icon:"film",onClick:()=>t.downloadVideo(r,l.title)},r&&{label:"Subtitles .vtt",icon:"subtitles",onClick:()=>t.downloadVideo(r,l.title,"vtt")},r&&{label:"Subtitles .srt",icon:"subtitles",onClick:()=>t.downloadVideo(r,l.title,"srt")},r&&{label:"Share…",icon:"share",onClick:()=>{t.shareVideo(r,l.title).then(e=>!e&&t.say("No share sheet here: download it instead."))}},{heading:"Demo"},{label:"Clone",icon:"duplicate",onClick:()=>t.openStudio({...t.create(`${l.title} (copy)`),...JSON.parse(JSON.stringify(l)),id:t.create(l.title).id,title:`${l.title} (copy)`})},"edited"===o&&{label:"Revert to the app’s version",icon:"undo",onClick:()=>window.confirm("Drop the changes kept here?")&&void t.remove(l.id)},"here"===o&&{label:"Delete",icon:"delete",onClick:()=>window.confirm(`Delete "${l.title}"?`)&&void t.remove(l.id)}]})))}export function Narration({engine:t}){const{settings:a,speech:n}=g(t),l=a.speech.voice,o=t.language(),i=e=>t.changeSettings({speech:{...a.speech,...e}});return e.createElement("section",{className:"section"},e.createElement("h3",null,"Narration"),e.createElement(w,{value:l,onChange:e=>i({voice:e}),options:N.map(([e,t,a])=>[e,t,a])}),e.createElement("div",{className:"small muted"},N.find(([e])=>e===l)?.[2]),"free"===l&&e.createElement(C,{engine:t}),"elevenlabs"===l&&e.createElement(x,{engine:t}),"system"===l&&e.createElement(P,{engine:t,language:o}),e.createElement("div",{className:"row",style:{flexWrap:"wrap",gap:12}},e.createElement(b,{label:"Language"},e.createElement("select",{className:"field",value:a.language,onChange:e=>t.changeSettings({language:e.target.value})},e.createElement("option",{value:"page"},"The page's (",t.options.language?.()??o,")"),t.languages().map(t=>e.createElement("option",{key:t,value:t},t)))),e.createElement(b,{label:`Speed ${a.speech.rate.toFixed(2)}×`},e.createElement("input",{type:"range",min:.7,max:1.4,step:.05,value:a.speech.rate,onChange:e=>i({rate:Number(e.target.value)})}))),e.createElement("div",{className:"row",style:{flexWrap:"wrap",gap:12}},e.createElement(E,{label:"Subtitles",checked:a.subtitles,onChange:e=>t.changeSettings({subtitles:e})}),e.createElement(E,{label:"Wait for the presenter after each step",checked:a.waitForPresenter,onChange:e=>t.changeSettings({waitForPresenter:e})}),e.createElement(E,{label:"From a step: catch up first",title:"Earlier steps' actions quickly, so the app is where the step expects it",checked:a.catchUp,onChange:e=>t.changeSettings({catchUp:e})}),e.createElement(E,{label:"The demo's narration pack, where it has one",title:"Its audio made once and checked in: no key, no download; what changed since, the voice says",checked:a.usePacks,onChange:e=>t.changeSettings({usePacks:e})})),e.createElement("div",{className:"small muted"},"Playing: Space pauses, → or PageDown goes on, ← or PageUp goes back, 1-9, Home and End go to a step, Esc stops: a presenter's clicker works."),void 0!==n.loading&&e.createElement("div",{className:"col",style:{gap:2}},e.createElement("span",{className:"small muted"},"Downloading a model: ",Math.round(100*n.loading)," %"),e.createElement("div",{className:"progress"},e.createElement("div",{style:{width:100*n.loading+"%"}}))),n.error&&e.createElement("div",{className:"small error"},"Voice: ",n.error))}function C({engine:a}){const{settings:n}=g(a),[o,i]=l([]);return t(()=>{c().then(i,()=>i([]))},[]),e.createElement("div",{className:"col"},a.languages().map(t=>{const l=a.speech.freeVoice(t)??"",i=t.split(/[-_]/)[0],r=o.filter(e=>e.language.split("_")[0]===i);return e.createElement(b,{key:t,label:`Voice for ${t}`},e.createElement("select",{className:"field",value:l,onChange:e=>a.changeSettings({speech:{...n.speech,free:{...n.speech.free,[t]:e.target.value}}})},!l&&e.createElement("option",{value:""},"None: choose one"),"en"===i&&e.createElement("optgroup",{label:"Kokoro"},s.map(t=>e.createElement("option",{key:t.id,value:`kokoro:${t.id}`},t.name))),e.createElement("optgroup",{label:"Piper"},l.startsWith("piper:")&&!r.some(e=>`piper:${e.id}`===l)&&e.createElement("option",{value:l},l.slice(6)),r.map(t=>e.createElement("option",{key:t.id,value:`piper:${t.id}`},t.name)))))}))}function x({engine:a}){const{settings:n}=g(a),{key:o,voice:i}=n.speech.elevenlabs,[s,c]=l([]),m=e=>a.changeSettings({speech:{...n.speech,elevenlabs:{...n.speech.elevenlabs,...e}}});return t(()=>{o&&r(o).then(c,()=>c([]))},[o]),e.createElement("div",{className:"row"},e.createElement(b,{label:"API key, kept in this browser",className:"grow"},e.createElement("input",{className:"field",type:"password",autoComplete:"off",value:o,onChange:e=>m({key:e.target.value.trim()})})),s.length>0&&e.createElement(b,{label:"Voice",className:"grow"},e.createElement("select",{className:"field",value:s.some(e=>e.id===i)?i:"",onChange:e=>m({voice:e.target.value})},s.map(t=>e.createElement("option",{key:t.id,value:t.id},t.name)))))}function P({engine:a,language:n}){const{settings:o}=g(a),[i,r]=l(()=>speechSynthesis.getVoices());t(()=>{const e=()=>r(speechSynthesis.getVoices());return speechSynthesis.addEventListener("voiceschanged",e),()=>speechSynthesis.removeEventListener("voiceschanged",e)},[]);const s=i.filter(e=>e.lang.toLowerCase().startsWith(n.toLowerCase().split("-")[0]));return e.createElement(b,{label:`Voice for ${n}`},e.createElement("select",{className:"field",value:o.speech.system[n]??"",onChange:e=>a.changeSettings({speech:{...o.speech,system:{...o.speech.system,[n]:e.target.value}}})},e.createElement("option",{value:""},"The default"),s.map(t=>e.createElement("option",{key:t.name,value:t.name},t.name))))}export function Recording({engine:t}){const{settings:a}=g(t);return e.createElement("section",{className:"section"},e.createElement("h3",null,"Recording"),e.createElement("div",{className:"row",style:{flexWrap:"wrap",gap:12}},e.createElement(E,{label:e.createElement(e.Fragment,null,e.createElement(v,{name:"mic"})," Microphone: what I say becomes the narration"),checked:a.microphone,onChange:e=>t.changeSettings({microphone:e})}),e.createElement(E,{label:e.createElement(e.Fragment,null,e.createElement(v,{name:"film"})," Film it too"),checked:a.filmRecording,onChange:e=>t.changeSettings({filmRecording:e})})),a.microphone&&e.createElement("div",{className:"row",style:{flexWrap:"wrap"}},e.createElement(b,{label:"Speech to text"},e.createElement("select",{className:"field",value:a.transcriber,onChange:e=>t.changeSettings({transcriber:e.target.value})},e.createElement("option",{value:"whisper"},"Whisper, in the browser (private, free)"),e.createElement("option",{value:"elevenlabs"},"ElevenLabs Scribe (your key)"))),"whisper"===a.transcriber&&e.createElement(b,{label:"Model"},e.createElement("select",{className:"field",value:a.whisperModel,onChange:e=>t.changeSettings({whisperModel:e.target.value})},e.createElement("option",{value:"tiny"},"tiny: quick"),e.createElement("option",{value:"base"},"base"),e.createElement("option",{value:"small"},"small: best")))),e.createElement("div",{className:"small muted"},"Recording: Alt+N starts the next step, Alt+H records a hover where the pointer is, Esc stops."))}
1
+ import e,{useEffect as t,useLayoutEffect as a,useRef as n,useState as l}from"react";import{createPortal as o}from"react-dom";import{clock as i}from"../model/Timing.js";import{elevenLabsVoices as s,KOKORO_VOICES as r,piperVoices as c}from"../speech/Speech.js";import{MUSIC_TRACKS as m}from"../speech/Music.js";import{videoSize as d}from"../video/Film.js";import{pickFile as p}from"../store/Share.js";import{useDemos as h,useEngine as g}from"./Hooks.js";import{Button as u,Check as E,Icon as v,Labelled as b,Menu as f,Segmented as w,useTheme as y}from"./Kit.js";import{UI_CSS as k}from"./Styles.js";const N=[["free","Free","Neural voices in the browser, no key: Kokoro for English, Piper for ~40 languages. Downloaded once (80-330 MB), then kept."],["elevenlabs","ElevenLabs","Premium voices with your own key. Each sentence is paid for once, then kept in this browser."],["system","System","The browser's own voices: instant, but videos don't hear them."],["off","Off","Subtitles only, timed to reading."]];export function DemoLibrary({engine:t,theme:a}){const n=y(a??t.options.theme??"auto");return e.createElement(Shadow,null,e.createElement(Library,{engine:t,theme:n}))}export function Shadow({children:t}){const i=n(null),[s,r]=l();return a(()=>{const e=i.current,t=e.shadowRoot??e.attachShadow({mode:"open"});if(!t.querySelector("style[data-pde]")){const a=e.ownerDocument.createElement("style");a.setAttribute("data-pde",""),a.textContent=k,t.append(a)}r(t)},[]),e.createElement("div",{ref:i,"data-demo-ignore":!0,style:{display:"contents"}},s&&o(t,s))}export function Library({engine:t,theme:a,floating:n}){const l=g(t),o=h(t),i="idle"!==l.session.mode,s=async e=>{const{demo:a,problems:n}=t.parse(e);if(!a)return t.say(`Not a demo: ${n.slice(0,3).map(e=>`${e.path||"demo"} ${e.message}`).join("; ")}`,!0);await t.save(a),t.openStudio(a)};return e.createElement("div",{className:"pde library"+(n?" floating":""),"data-theme":a,"data-demo-ignore":!0},l.message&&e.createElement("div",{className:"small "+(l.message.error?"error":"muted")},l.message.text),e.createElement("section",{className:"section"},e.createElement("h3",null,"Demos"),0===o.length&&e.createElement("div",{className:"small muted"},"None yet: record one, or ask an AI to make one (demoEngine.help())."),o.map(a=>e.createElement(S,{key:a.demo.id,engine:t,entry:a,busy:i})),e.createElement("div",{className:"row",style:{flexWrap:"wrap"}},l.loop?e.createElement(u,{icon:"stop",onClick:()=>t.stopLoop()},"Stop the loop"):e.createElement(u,{icon:"loop",disabled:i||0===o.length,title:"Every demo, one after the other, again and again: an expo booth",onClick:()=>{t.loop(o.map(e=>e.demo))}},"Loop all"),e.createElement(u,{icon:"record",disabled:i,onClick:()=>{t.record()},style:{color:"var(--danger)"}},"Record"),e.createElement(u,{icon:"add",disabled:i,onClick:()=>t.openStudio(t.create())},"New"),e.createElement(u,{icon:"upload",onClick:()=>{p().then(e=>e?.text()).then(e=>{if(e)return s(e)})}},"Import"),e.createElement(u,{icon:"copy",title:"Paste a demo’s JSON",onClick:()=>{navigator.clipboard.readText().then(s,()=>t.say("Could not read the clipboard",!0))}},"Paste"))),e.createElement(Narration,{engine:t}),e.createElement(Production,{engine:t}),e.createElement(Recording,{engine:t}))}export function Production({engine:t}){const{settings:a}=g(t),{music:n,film:o}=a,[i,s]=l(),r=n.on?n.track:"none",c=o.lines?d(o.lines,o.aspect):void 0,h={width:Math.round(innerWidth*devicePixelRatio),height:Math.round(innerHeight*devicePixelRatio)};return e.createElement("section",{className:"section"},e.createElement("h3",null,"Production"),e.createElement("div",{className:"row",style:{flexWrap:"wrap",gap:10,alignItems:"flex-end"}},e.createElement(b,{label:"Music"},e.createElement("select",{className:"field",value:r,onChange:e=>(e=>{if(i?.(),s(void 0),"none"===e)return t.changeSettings({music:{...n,on:!1}});"pick"!==e?t.changeSettings({music:{...n,on:!0,track:e}}):p("audio/*").then(e=>e&&t.setMusic(e))})(e.target.value)},e.createElement("option",{value:"none"},"None"),m.map(t=>e.createElement("option",{key:t.id,value:t.id,title:t.hint},t.name)),n.name&&e.createElement("option",{value:"file"},n.name),e.createElement("option",{value:"pick"},"Your own file…"))),e.createElement(u,{small:!0,icon:i?"stop":"listen",disabled:!n.on,onClick:()=>{(async()=>{if(i)return i(),s(void 0);const e=await t.listenToMusic(20);s(()=>e),setTimeout(()=>s(void 0),2e4)})()}},i?"Stop":"Listen"),e.createElement(b,{label:`Volume ${Math.round(100*n.volume)} %`},e.createElement("input",{type:"range",min:.02,max:.6,step:.01,value:n.volume,disabled:!n.on,onChange:e=>{t.changeSettings({music:{...n,volume:Number(e.target.value)}}),t.speech.setMusicVolume(Number(e.target.value))}}))),e.createElement("div",{className:"small muted"},n.on&&"file"!==n.track?`${m.find(e=>e.id===n.track)?.hint}. Composed by the engine: free to use anywhere. `:"","Under the narration, quieter while it speaks; in videos too."),e.createElement("div",{className:"row",style:{flexWrap:"wrap",gap:10}},e.createElement(b,{label:"Video size"},e.createElement("select",{className:"field",value:o.lines,onChange:e=>t.changeSettings({film:{...o,lines:Number(e.target.value)}})},e.createElement("option",{value:0},"The tab's own (",h.width,"×",h.height,")"),[720,1080,1440,2160].map(t=>{const{width:a,height:n}=d(t,o.aspect);return e.createElement("option",{key:t,value:t},2160===t?"4K":`${t}p`," (",a,"×",n,")")}))),o.lines>0&&e.createElement(e.Fragment,null,e.createElement(b,{label:"Shape"},e.createElement("select",{className:"field",value:o.aspect,onChange:e=>t.changeSettings({film:{...o,aspect:e.target.value}})},e.createElement("option",{value:"16:9"},"16:9 landscape"),e.createElement("option",{value:"9:16"},"9:16 portrait"),e.createElement("option",{value:"1:1"},"1:1 square"))),e.createElement(b,{label:"The tab"},e.createElement("select",{className:"field",value:o.fit,onChange:e=>t.changeSettings({film:{...o,fit:e.target.value}})},e.createElement("option",{value:"fit"},"Whole, with bars"),e.createElement("option",{value:"fill"},"Filling it, edges cut")))),e.createElement(b,{label:"Frames"},e.createElement("select",{className:"field",value:o.frameRate,onChange:e=>t.changeSettings({film:{...o,frameRate:Number(e.target.value)}})},e.createElement("option",{value:30},"30 a second"),e.createElement("option",{value:60},"60 a second"))),e.createElement(b,{label:"Quality"},e.createElement("select",{className:"field",value:o.bitrate,onChange:e=>t.changeSettings({film:{...o,bitrate:Number(e.target.value)}})},e.createElement("option",{value:4},"Small (4 Mb/s)"),e.createElement("option",{value:8},"Good (8 Mb/s)"),e.createElement("option",{value:16},"High (16 Mb/s)"),e.createElement("option",{value:25},"Master (25 Mb/s)")))),c&&(c.width>1.05*h.width||c.height>1.05*h.height)&&e.createElement("div",{className:"small muted"},"The tab is ",h.width,"×",h.height,": a ",c.width,"×",c.height," video scales it up, a little soft. A bigger window, or a screen with more pixels, keeps it sharp."),e.createElement("div",{className:"row",style:{flexWrap:"wrap",gap:10}},e.createElement(b,{label:"Loop: plays again after"},e.createElement("select",{className:"field",value:a.loopIdle,onChange:e=>t.changeSettings({loopIdle:Number(e.target.value)})},[10,20,30,60,120].map(t=>e.createElement("option",{key:t,value:1e3*t},t," s idle"))))))}function S({engine:t,entry:a,busy:n}){const{demo:l,origin:o,video:s}=a,r=i(t.timing(l).duration);return e.createElement("div",{className:"demo"},e.createElement("div",{className:"row"},e.createElement("span",{className:"title grow ellipsis",title:l.description},l.title),"app"!==o&&e.createElement("span",{className:"badge"},"edited"===o?"edited here":"made here"),s&&e.createElement("span",{className:"badge accent",title:`Filmed ${new Date(s.at).toLocaleString()}`},"video")),l.description&&e.createElement("div",{className:"small muted"},l.description),e.createElement("div",{className:"row"},e.createElement("span",{className:"small muted grow"},l.steps.length," steps · ~",r," · ",t.languagesOf(l).join(", ")||"no narration"),e.createElement(u,{icon:"play",small:!0,kind:"primary",title:"Play",disabled:n,onClick:()=>{t.play(l)}}),e.createElement(u,{icon:"film",small:!0,title:"Film: a video with narration and subtitles",disabled:n,onClick:()=>{t.film(l)}}),e.createElement(u,{icon:"edit",small:!0,title:"Open in the studio",onClick:()=>t.openStudio(l)}),e.createElement(f,{title:"More",items:[{heading:"Play"},{label:"Present: waits after each step, the presenter's screen beside it",icon:"present",disabled:n,onClick:()=>{t.present(l)}},{label:"Guide: the viewer does it",icon:"guide",disabled:n,onClick:()=>{t.guide(l)}},{label:"Loop it: an expo booth",icon:"loop",disabled:n,onClick:()=>{t.loop([l])}},{heading:"Share"},{label:"Copy a link with the demo",icon:"link",onClick:()=>{t.link(l).then(e=>navigator.clipboard.writeText(e)).then(()=>t.say("Link copied."))}},{label:"Download .demo.json",icon:"download",onClick:()=>t.downloadDemo(l)},{label:"Download scenario .md",icon:"download",onClick:()=>t.downloadDemo({...l,scenario:a.scenario},"md")},{label:"Narration pack (.zip)",icon:"listen",onClick:()=>{t.downloadPack(l)}},s&&{heading:"Video"},s&&{label:"Download the video",icon:"film",onClick:()=>t.downloadVideo(s,l.title)},s&&{label:"Subtitles .vtt",icon:"subtitles",onClick:()=>t.downloadVideo(s,l.title,"vtt")},s&&{label:"Subtitles .srt",icon:"subtitles",onClick:()=>t.downloadVideo(s,l.title,"srt")},s&&{label:"Share…",icon:"share",onClick:()=>{t.shareVideo(s,l.title).then(e=>!e&&t.say("No share sheet here: download it instead."))}},{heading:"Demo"},{label:"Clone",icon:"duplicate",onClick:()=>t.openStudio({...t.create(`${l.title} (copy)`),...JSON.parse(JSON.stringify(l)),id:t.create(l.title).id,title:`${l.title} (copy)`})},"edited"===o&&{label:"Revert to the app’s version",icon:"undo",onClick:()=>window.confirm("Drop the changes kept here?")&&void t.remove(l.id)},"here"===o&&{label:"Delete",icon:"delete",onClick:()=>window.confirm(`Delete "${l.title}"?`)&&void t.remove(l.id)}]})))}export function Narration({engine:t}){const{settings:a,speech:n}=g(t),l=a.speech.voice,o=t.language(),i=e=>t.changeSettings({speech:{...a.speech,...e}});return e.createElement("section",{className:"section"},e.createElement("h3",null,"Narration"),e.createElement(w,{value:l,onChange:e=>i({voice:e}),options:N.map(([e,t,a])=>[e,t,a])}),e.createElement("div",{className:"small muted"},N.find(([e])=>e===l)?.[2]),"free"===l&&e.createElement(C,{engine:t}),"elevenlabs"===l&&e.createElement(x,{engine:t}),"system"===l&&e.createElement(P,{engine:t,language:o}),e.createElement("div",{className:"row",style:{flexWrap:"wrap",gap:12}},e.createElement(b,{label:"Language"},e.createElement("select",{className:"field",value:a.language,onChange:e=>t.changeSettings({language:e.target.value})},e.createElement("option",{value:"page"},"The page's (",t.options.language?.()??o,")"),t.languages().map(t=>e.createElement("option",{key:t,value:t},t)))),e.createElement(b,{label:`Speed ${a.speech.rate.toFixed(2)}×`},e.createElement("input",{type:"range",min:.7,max:1.4,step:.05,value:a.speech.rate,onChange:e=>i({rate:Number(e.target.value)})}))),e.createElement("div",{className:"row",style:{flexWrap:"wrap",gap:12}},e.createElement(E,{label:"Subtitles",checked:a.subtitles,onChange:e=>t.changeSettings({subtitles:e})}),e.createElement(E,{label:"Wait for the presenter after each step",checked:a.waitForPresenter,onChange:e=>t.changeSettings({waitForPresenter:e})}),e.createElement(E,{label:"From a step: catch up first",title:"Earlier steps' actions quickly, so the app is where the step expects it",checked:a.catchUp,onChange:e=>t.changeSettings({catchUp:e})}),e.createElement(E,{label:"The demo's narration pack, where it has one",title:"Its audio made once and checked in: no key, no download; what changed since, the voice says",checked:a.usePacks,onChange:e=>t.changeSettings({usePacks:e})})),e.createElement("div",{className:"small muted"},"Playing: Space pauses, → or PageDown goes on, ← or PageUp goes back, 1-9, Home and End go to a step, Esc stops: a presenter's clicker works."),void 0!==n.loading&&e.createElement("div",{className:"col",style:{gap:2}},e.createElement("span",{className:"small muted"},"Downloading a model: ",Math.round(100*n.loading)," %"),e.createElement("div",{className:"progress"},e.createElement("div",{style:{width:100*n.loading+"%"}}))),n.error&&e.createElement("div",{className:"small error"},"Voice: ",n.error))}function C({engine:a}){const{settings:n}=g(a),[o,i]=l([]);return t(()=>{c().then(i,()=>i([]))},[]),e.createElement("div",{className:"col"},a.languages().map(t=>{const l=a.speech.freeVoice(t)??"",i=t.split(/[-_]/)[0],s=o.filter(e=>e.language.split("_")[0]===i);return e.createElement(b,{key:t,label:`Voice for ${t}`},e.createElement("select",{className:"field",value:l,onChange:e=>a.changeSettings({speech:{...n.speech,free:{...n.speech.free,[t]:e.target.value}}})},!l&&e.createElement("option",{value:""},"None: choose one"),"en"===i&&e.createElement("optgroup",{label:"Kokoro"},r.map(t=>e.createElement("option",{key:t.id,value:`kokoro:${t.id}`},t.name))),e.createElement("optgroup",{label:"Piper"},l.startsWith("piper:")&&!s.some(e=>`piper:${e.id}`===l)&&e.createElement("option",{value:l},l.slice(6)),s.map(t=>e.createElement("option",{key:t.id,value:`piper:${t.id}`},t.name)))))}))}function x({engine:a}){const{settings:n}=g(a),{key:o,voice:i}=n.speech.elevenlabs,[r,c]=l([]),m=e=>a.changeSettings({speech:{...n.speech,elevenlabs:{...n.speech.elevenlabs,...e}}});return t(()=>{o&&s(o).then(c,()=>c([]))},[o]),e.createElement("div",{className:"row"},e.createElement(b,{label:"API key, kept in this browser",className:"grow"},e.createElement("input",{className:"field",type:"password",autoComplete:"off",value:o,onChange:e=>m({key:e.target.value.trim()})})),r.length>0&&e.createElement(b,{label:"Voice",className:"grow"},e.createElement("select",{className:"field",value:r.some(e=>e.id===i)?i:"",onChange:e=>m({voice:e.target.value})},r.map(t=>e.createElement("option",{key:t.id,value:t.id},t.name)))))}function P({engine:a,language:n}){const{settings:o}=g(a),[i,s]=l(()=>speechSynthesis.getVoices());t(()=>{const e=()=>s(speechSynthesis.getVoices());return speechSynthesis.addEventListener("voiceschanged",e),()=>speechSynthesis.removeEventListener("voiceschanged",e)},[]);const r=i.filter(e=>e.lang.toLowerCase().startsWith(n.toLowerCase().split("-")[0]));return e.createElement(b,{label:`Voice for ${n}`},e.createElement("select",{className:"field",value:o.speech.system[n]??"",onChange:e=>a.changeSettings({speech:{...o.speech,system:{...o.speech.system,[n]:e.target.value}}})},e.createElement("option",{value:""},"The default"),r.map(t=>e.createElement("option",{key:t.name,value:t.name},t.name))))}export function Recording({engine:t}){const{settings:a}=g(t);return e.createElement("section",{className:"section"},e.createElement("h3",null,"Recording"),e.createElement("div",{className:"row",style:{flexWrap:"wrap",gap:12}},e.createElement(E,{label:e.createElement(e.Fragment,null,e.createElement(v,{name:"mic"})," Microphone: what I say becomes the narration"),checked:a.microphone,onChange:e=>t.changeSettings({microphone:e})}),e.createElement(E,{label:e.createElement(e.Fragment,null,e.createElement(v,{name:"film"})," Film it too"),checked:a.filmRecording,onChange:e=>t.changeSettings({filmRecording:e})})),a.microphone&&e.createElement("div",{className:"row",style:{flexWrap:"wrap"}},e.createElement(b,{label:"Speech to text"},e.createElement("select",{className:"field",value:a.transcriber,onChange:e=>t.changeSettings({transcriber:e.target.value})},e.createElement("option",{value:"whisper"},"Whisper, in the browser (private, free)"),e.createElement("option",{value:"elevenlabs"},"ElevenLabs Scribe (your key)"))),"whisper"===a.transcriber&&e.createElement(b,{label:"Model"},e.createElement("select",{className:"field",value:a.whisperModel,onChange:e=>t.changeSettings({whisperModel:e.target.value})},e.createElement("option",{value:"tiny"},"tiny: quick"),e.createElement("option",{value:"base"},"base"),e.createElement("option",{value:"small"},"small: best")))),e.createElement("div",{className:"small muted"},"Recording: Alt+N starts the next step, Alt+H records a hover where the pointer is, Esc stops."))}
@@ -0,0 +1,17 @@
1
+ import type { DemoEngine } from '../engine/DemoEngine';
2
+ /**
3
+ * The presenter's own screen, in a window of its own - beside the slides' laptop, never in a video -
4
+ * or always on top (Document Picture-in-Picture, where the browser has it). The script with the
5
+ * sentence being said, notes for the presenter, what comes next, the clock, every step to go to.
6
+ * From a click: browsers open windows only then. Returns false where none could be opened.
7
+ */
8
+ export declare function openPresenter(engine: DemoEngine, { onTop }?: {
9
+ onTop?: boolean;
10
+ }): Promise<boolean>;
11
+ /**
12
+ * The presenter's screen in a document of the app's choosing - a window it opened itself, a frame,
13
+ * its own panel's window - filling it. Its keys, a clicker's, drive the demo. Returns its unmount.
14
+ */
15
+ export declare function mountPresenter(engine: DemoEngine, doc: Document, { compact }?: {
16
+ compact?: boolean;
17
+ }): () => void;
@@ -0,0 +1 @@
1
+ import e,{useEffect as t,useState as n}from"react";import{createRoot as r}from"react-dom/client";import{sayOf as a,sentences as s}from"../model/Demo.js";import{clock as p}from"../model/Timing.js";import{useEngine as o}from"./Hooks.js";import{Button as i}from"./Kit.js";import{UI_CSS as l}from"./Styles.js";export async function openPresenter(e,{onTop:t=!1}={}){let n=null;const r=window.documentPictureInPicture;if(t&&r&&(n=await r.requestWindow({width:460,height:380}).catch(()=>null)),n||(n=window.open("","protomaze-demo-presenter","popup,width=1000,height=700")),!n)return!1;if(n.document.getElementById("pde-presenter"))return n.focus(),!0;n.document.title="Presenter";const a=mountPresenter(e,n.document,{compact:t&&Boolean(r)});return n.addEventListener("pagehide",a,{once:!0}),!0}export function mountPresenter(t,n,{compact:a=!1}={}){const s=n.createElement("style");s.textContent=l+"\nhtml, body { margin: 0; height: 100%; background: #17181c; }\n.pde.presenter { position: fixed; inset: 0; display: grid; grid-template-rows: auto 1fr auto; gap: 14px; padding: 16px 20px; background: var(--bg); font-size: 16px; }\n.pde.presenter .top { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; }\n.pde.presenter .clock { font: 600 30px ui-monospace, monospace; }\n.pde.presenter .clock small { font-size: 14px; color: var(--muted); font-weight: 400; margin-left: 6px; }\n.pde.presenter .middle { display: grid; grid-template-columns: 1fr 260px; gap: 18px; min-height: 0; }\n.pde.presenter .now { overflow: auto; display: flex; flex-direction: column; gap: 12px; min-height: 0; }\n.pde.presenter h2 { margin: 0; font-size: 22px; }\n.pde.presenter .script p { margin: 0 0 10px; font-size: 26px; line-height: 1.45; color: var(--muted); }\n.pde.presenter .script p.on { color: var(--fg); }\n.pde.presenter .script p.said { opacity: .55; }\n.pde.presenter .notes { border-left: 4px solid var(--accent); padding: 8px 14px; background: var(--panel); white-space: pre-wrap; font-size: 18px; border-radius: 0 8px 8px 0; }\n.pde.presenter .next { border-top: 1px solid var(--line); padding-top: 10px; color: var(--muted); }\n.pde.presenter .steps { overflow: auto; display: flex; flex-direction: column; gap: 2px; border-left: 1px solid var(--line); padding-left: 12px; }\n.pde.presenter .steps button { text-align: left; border: 0; background: none; padding: 6px 8px; border-radius: 6px; cursor: pointer; color: var(--muted); font-size: 14px; }\n.pde.presenter .steps button.on { background: var(--raised); color: var(--fg); box-shadow: inset 3px 0 0 var(--accent); }\n.pde.presenter .controls { display: flex; gap: 12px; justify-content: center; flex-wrap: wrap; }\n.pde.presenter .controls .btn { height: 64px; min-width: 96px; font-size: 18px; border-radius: 12px; }\n.pde.presenter .controls .btn svg.i { width: 28px; height: 28px; }\n.pde.presenter.compact { padding: 10px; gap: 8px; font-size: 14px; }\n.pde.presenter.compact .middle { grid-template-columns: 1fr; }\n.pde.presenter.compact .steps { display: none; }\n.pde.presenter.compact .script p { font-size: 18px; }\n.pde.presenter.compact .controls .btn { height: 44px; min-width: 56px; }\n.pde.presenter .idle { display: flex; flex-direction: column; gap: 8px; overflow: auto; }\n",n.head.append(s);const p=n.createElement("div");p.id="pde-presenter",p.setAttribute("data-demo-ignore",""),n.body.append(p);const o=r(p);o.render(e.createElement(c,{engine:t,compact:a}));const i=e=>t.presenterKey(e);return n.defaultView?.addEventListener("keydown",i,!0),()=>{n.defaultView?.removeEventListener("keydown",i,!0),o.unmount(),p.remove(),s.remove()}}function c({engine:r,compact:l}){const c=o(r),[,d]=n(0);t(()=>{const e=setInterval(()=>d(e=>e+1),500);return()=>clearInterval(e)},[]);const m=c.session,u="pde presenter"+(l?" compact":"");if("playing"!==m.mode||m.checking)return e.createElement("div",{className:u,"data-theme":"dark"},e.createElement("div",{className:"top"},e.createElement("h2",null,"Presenter"),e.createElement("span",{className:"muted"},"ready"===m.mode?"Waiting for a click in the app’s window":"Nothing plays")),e.createElement("div",{className:"idle"},e.createElement("span",{className:"muted"},"Start a demo in the app (Present waits after each step). Its script, your notes and the controls show here; a clicker works in either window."),r.entriesNow().map(({demo:t})=>e.createElement("div",{key:t.id,className:"row"},e.createElement("span",{className:"grow"},t.title),e.createElement(i,{icon:"present",onClick:()=>{r.play(t,{waitForPresenter:!0})}},"Present")))),e.createElement("div",null));const{demo:g,step:x,player:f}=m,h=g.steps[x],w=g.steps[x+1],E=r.language(),v=h?s(a(h,E)):[],y=v.indexOf(m.caption),b=f.elapsed(),N=b-f.stepStartedAt,k=r.timing(g,E),P=k.steps.find(e=>e.step===x);return e.createElement("div",{className:u,"data-theme":"dark"},e.createElement("div",{className:"top"},e.createElement("span",{className:"clock"},p(b),e.createElement("small",null,"/ ",p(k.duration))),e.createElement("span",{className:"clock",style:{fontSize:20}},p(N),e.createElement("small",null,"step",P?`, ~${p(P.end-P.start)}`:"")),e.createElement("span",{className:"grow"}),e.createElement("span",{className:"muted"},g.title),e.createElement("span",{className:"badge accent"},x+1," / ",g.steps.length),m.waiting&&e.createElement("span",{className:"badge"},"waiting for you"),m.paused&&!m.waiting&&e.createElement("span",{className:"badge"},"paused"),m.catchingUp&&e.createElement("span",{className:"badge"},"catching up")),e.createElement("div",{className:"middle"},e.createElement("div",{className:"now"},e.createElement("h2",null,h?.title??`Step ${x+1}`),e.createElement("div",{className:"script"},v.length?v.map((t,n)=>e.createElement("p",{key:n,className:n===y?"on":y>=0&&n<y?"said":""},t)):e.createElement("p",null,"No narration: in your own words.")),h?.notes&&e.createElement("div",{className:"notes"},h.notes),w&&e.createElement("div",{className:"next"},e.createElement("strong",null,"Next: ",w.title??`step ${x+2}`),e.createElement("div",null,s(a(w,E))[0]??""))),e.createElement("div",{className:"steps"},g.steps.map((t,n)=>e.createElement("button",{key:n,type:"button",className:n===x?"on":"",disabled:m.filming,onClick:()=>r.goTo(n)},n+1,". ",t.title??(s(a(t,E))[0]??"").slice(0,40))))),e.createElement("div",{className:"controls"},e.createElement(i,{icon:"back",title:"This step again; pressed early, the one before (←, PageUp)",disabled:m.filming,onClick:()=>r.back()}),e.createElement(i,{icon:m.paused?"play":"pause",kind:"primary",onClick:()=>m.waiting?r.next():r.togglePause()},m.waiting?"Continue":m.paused?"Resume":"Pause"),e.createElement(i,{icon:"right",title:"Next step (→, PageDown)",onClick:()=>r.next()}),e.createElement(i,{icon:"stop",title:"Stop (Esc)",onClick:()=>r.stop()})))}
package/ui/Studio.js CHANGED
@@ -1 +1 @@
1
- import e,{useEffect as t,useMemo as a,useRef as n,useState as i}from"react";import{copyOf as l,sayOf as o,scenarioOf as s,sentences as r}from"../model/Demo.js";import{clock as c}from"../model/Timing.js";import{fileName as d}from"../store/Share.js";import{recordMicrophone as m}from"../video/Film.js";import{ActionRow as p,addActionItems as g,readAction as h}from"./Actions.js";import{useEngine as u}from"./Hooks.js";import{Button as v,Check as f,Menu as w,NumberField as E,Segmented as k}from"./Kit.js";import{Timeline as y}from"./Timeline.js";const b="protomaze-demo-engine:studio-height";export function Studio({engine:d,theme:m}){const S=u(d),D=S.studio,[j,$]=i(()=>l(D.demo)),[L,O]=i(()=>JSON.stringify(D.demo)),R=n({back:[],forward:[]}),[T,M]=i(0),[J,U]=i(),[A,F]=i("steps"),[P,V]=i({json:"",scenario:""}),[z,B]=i(),[W,H]=i(new Map),[K,q]=i(()=>Number(localStorage.getItem(b))||Math.round(.46*innerHeight)),[I,Y]=i(!1),[G,Z]=i(!1),[Q,X]=i(!1),[_,ee]=i(()=>d.language()),te=S.session,ae="idle"!==te.mode,ne="playing"!==te.mode||te.checking?void 0:te,ie=j.steps,le=Math.min(T,Math.max(0,ie.length-1)),oe=ne&&ne.demo.id===j.id?ne.step:le,se=JSON.stringify(j)!==L,re=a(()=>Array.from(new Set([...d.languages(),...d.languagesOf(j)])),[j]),ce=d.entriesNow().find(e=>e.demo.id===j.id),de=d.timing(j,_),me=S.lastRun?.json===JSON.stringify(j)&&S.lastRun.language===_,pe=(e,t=!0)=>{t&&(R.current.back.push(j),R.current.back.length>200&&R.current.back.shift(),R.current.forward=[]),$(e)},ge=()=>{const e=R.current.back.pop();e&&(R.current.forward.push(j),$(e))},he=()=>{const e=R.current.forward.pop();e&&(R.current.back.push(j),$(e))},ue=e=>pe({...j,...e}),ve=e=>ue({steps:e}),fe=e=>ve(ie.map((t,a)=>a===le?e:t));t(()=>{D.recorded&&pe({...j,steps:D.recorded.steps})},[D.recorded?.at]);const we=()=>{const{demo:e,problems:t}=d.parse(P.json);if(e)return B(void 0),{...e,scenario:P.scenario};B(t.slice(0,4).map(e=>`${e.path||"demo"}: ${e.message}`).join(" · "))},Ee=async()=>{const e="text"===A?we():j;if(e)try{await d.save(e),$(e),O(JSON.stringify(e)),d.say(`Saved "${e.title}".`)}catch(e){d.say(e.message,!0)}},ke=e=>{d.play(j,{from:e,language:_})},ye=e=>{const t=le+e;if(t<0||t>=ie.length)return;const a=[...ie];[a[le],a[t]]=[a[t],a[le]],ve(a),M(t)},be=I||Q||"recording"===te.mode||Boolean(ne),Ne=ie[le],Ce=e=>{const t=de.steps.find(t=>t.step===e);return t?`${((t.end-t.start)/1e3).toFixed(1)} s`:""};return e.createElement("div",{className:"pde studio"+(be?" collapsed":""),"data-theme":m,"data-demo-ignore":!0,onKeyDown:e=>{if(!(e.ctrlKey||e.metaKey))return;const t=e.key.toLowerCase();"s"===t?(e.preventDefault(),Ee()):"z"!==t||e.shiftKey||"text"===A?("y"===t||"z"===t&&e.shiftKey)&&"text"!==A&&(e.preventDefault(),he()):(e.preventDefault(),ge())},style:{height:be?void 0:K,display:Q?"none":void 0}},e.createElement("div",{className:"grip",onPointerDown:e=>{const t=e.clientY,a=K,n=e=>q(Math.max(180,Math.min(innerHeight-40,a+t-e.clientY))),i=()=>{window.removeEventListener("pointermove",n),window.removeEventListener("pointerup",i),q(e=>(localStorage.setItem(b,String(e)),e))};window.addEventListener("pointermove",n),window.addEventListener("pointerup",i)}}),e.createElement("div",{className:"head"},e.createElement("input",{className:"field",style:{width:240,fontWeight:600},value:j.title,title:"Title",onChange:e=>ue({title:e.target.value})}),e.createElement("input",{className:"field grow",style:{minWidth:120},placeholder:"Description: who it is for, what it shows",value:j.description??"",onChange:e=>ue({description:e.target.value})}),re.length>1&&e.createElement("select",{className:"field",title:"The language played, and timed",value:_,onChange:e=>ee(e.target.value)},re.map(t=>e.createElement("option",{key:t,value:t},t))),e.createElement("div",{className:"sep"}),!ne&&e.createElement(e.Fragment,null,e.createElement(v,{icon:"first",title:"Play from the start",disabled:ae,onClick:()=>ke(0)}),e.createElement(v,{icon:"play",kind:"primary",title:`Play from step ${le+1}`,disabled:ae,onClick:()=>ke(le)})),!ne&&e.createElement(w,{title:"Present, guide, loop",icon:"present",items:[{label:`Present from step ${le+1}: waits after each step`,icon:"present",disabled:ae,onClick:()=>{d.play(j,{from:le,language:_,waitForPresenter:!0})}},{label:`Guide from step ${le+1}: the viewer does it`,icon:"guide",disabled:ae,onClick:()=>{d.guide(j,{from:le,language:_})}},{label:"Loop it: an expo booth",icon:"loop",disabled:ae,onClick:()=>{d.loop([j])}}]}),ne&&e.createElement(e.Fragment,null,e.createElement(v,{icon:ne.paused?"play":"pause",kind:"primary",title:ne.waiting?"Continue":ne.paused?"Resume":"Pause",onClick:()=>ne.waiting?d.next():d.togglePause()}),e.createElement(v,{icon:"right",title:"Next step",onClick:()=>d.next()}),e.createElement(v,{icon:"stop",title:"Stop",onClick:()=>d.stop()})),e.createElement(v,{icon:"record",title:`Record new steps after step ${le+1}`,disabled:ae,onClick:()=>{d.record({into:j,after:le})},style:{color:"var(--danger)"}}),e.createElement(v,{icon:"film",title:"Film it: a video with narration and subtitles",disabled:ae,onClick:()=>{d.film(j,{language:_})}}),e.createElement(v,{icon:"check",title:"Check: plays it fast and silent, and marks what fails",disabled:ae,onClick:()=>{(async()=>{const e=await d.check(j);H(new Map(e.failures.map(e=>[`${e.step}.${e.index}`,e.error]))),e.ok?d.say(`Every step plays: ${c(e.duration)} at speed.`):d.say(e.failures.length?`${e.failures.length} action${1===e.failures.length?"":"s"} failed: in red.`:e.error??"Failed",!0);const t=e.failures[0];t&&(M(t.step),U(t.index))})()}}),e.createElement("div",{className:"sep"}),e.createElement(v,{icon:"undo",kind:"bare",title:"Undo (Ctrl+Z)",disabled:0===R.current.back.length,onClick:ge}),e.createElement(v,{icon:"redo",kind:"bare",title:"Redo (Ctrl+Y)",disabled:0===R.current.forward.length,onClick:he}),e.createElement(v,{icon:"save",kind:se?"primary":void 0,title:"Save here (Ctrl+S)",onClick:()=>{Ee()}},se?"Save":"Saved"),e.createElement(w,{title:"Share, export",icon:"share",items:[{label:"Download .demo.json",icon:"download",onClick:()=>d.downloadDemo(j)},{label:"Download scenario .md",icon:"download",onClick:()=>d.downloadDemo(j,"md")},{label:"Copy a link with the demo",icon:"link",onClick:()=>{d.link(j).then(e=>navigator.clipboard.writeText(e)).then(()=>d.say("Link copied: it opens the app with this demo."))}},{label:"Copy JSON",icon:"copy",onClick:()=>{navigator.clipboard.writeText(JSON.stringify({...j,scenario:void 0,savedAt:void 0},null,2)).then(()=>d.say("JSON copied."))}},{label:"Narration pack (.zip): no key, no download, for every viewer",icon:"listen",onClick:()=>{d.downloadPack(j)}},ce?.video&&{label:"Download the video",icon:"film",onClick:()=>d.downloadVideo(ce.video,j.title)},{heading:"This demo"},"edited"===ce?.origin&&{label:"Revert to the app’s version",icon:"undo",onClick:()=>{window.confirm("Drop the changes kept here?")&&d.remove(j.id)}},"here"===ce?.origin&&{label:"Delete",icon:"delete",onClick:()=>{window.confirm(`Delete "${j.title}"?`)&&d.remove(j.id)}}]}),e.createElement(k,{value:A,onChange:e=>{if(e!==A){if("text"===A){const e=we();if(!e)return;JSON.stringify(e)!==JSON.stringify(j)&&pe(e)}"text"===e&&(()=>{const{scenario:e,savedAt:t,...a}=j;V({json:JSON.stringify(a,null,2),scenario:j.scenario??s(j,_)}),B(void 0)})(),F(e)}},options:[["steps","Steps"],["text","Text"],["video","Video",ce?.video?"Its last video":"Not filmed yet"]]}),e.createElement(v,{icon:I?"maximize":"minimize",kind:"bare",title:I?"Unfold":"Fold",onClick:()=>Y(!I)}),e.createElement(v,{icon:"close",kind:"bare",title:"Close",onClick:()=>{se&&!window.confirm("Close without saving?")||d.closeStudio()}})),e.createElement(y,{demo:j,timing:de,measured:me,step:oe,action:J,theme:m,accent:"#ffb300",playhead:ne&&ne.demo.id===j.id?()=>d.elapsed():void 0,read:e=>h(d,e),onPick:(e,t)=>{ne&&ne.demo.id===j.id&&d.goTo(e)||(M(e),U(t),I&&Y(!1))}}),z&&e.createElement("div",{className:"error small",style:{padding:"4px 12px"}},z),e.createElement("div",{className:"body"},"text"!==A&&e.createElement("div",{className:"steps"},ie.map((t,a)=>e.createElement("div",{key:a,className:["step",a===le&&!G&&"on",ne&&a===oe&&"playing"].filter(Boolean).join(" "),onClick:()=>{M(a),U(void 0),Z(!1),function(e){if("video"!==A)return;const t=ce?.video?.timing?.steps.find(t=>t.step===e),a=document.querySelector("protomaze-demo-engine")?.shadowRoot?.querySelector("video");t&&a&&(a.currentTime=t.start/1e3)}(a)}},e.createElement("span",{className:"n"},a+1),e.createElement("div",{className:"col grow",style:{gap:2}},e.createElement("div",{className:"row"},e.createElement("span",{className:"grow ellipsis",style:{fontWeight:500}},t.title||function(e,t){return r(o(e,t))[0]}(t,_)||"Untitled"),e.createElement("span",{className:"small muted"},Ce(a))),t.title&&e.createElement("span",{className:"say"},o(t,_)),e.createElement("span",{className:"small muted"},t.actions.length," action",1===t.actions.length?"":"s",t.pause?" · waits":"")))),e.createElement(v,{icon:"add",small:!0,onClick:()=>{ve([...ie.slice(0,le+1),{say:{},actions:[]},...ie.slice(le+1)]),M(le+1),Z(!1)}},"New step"),e.createElement("div",{className:["step",G&&"on"].filter(Boolean).join(" "),style:{marginTop:6},onClick:()=>{Z(!0),U(void 0)},title:"Done after the demo, quickly and unseen, so the app is as it found it"},e.createElement("span",{className:"n"},"↺"),e.createElement("div",{className:"col grow",style:{gap:2}},e.createElement("span",{style:{fontWeight:500}},"Cleanup"),e.createElement("span",{className:"small muted"},(j.cleanup??[]).length," action",1===(j.cleanup??[]).length?"":"s"," after it, unseen")))),"steps"===A&&G&&e.createElement("div",{className:"pane"},e.createElement("div",{className:"row"},e.createElement("strong",{className:"grow"},"Cleanup"),e.createElement(w,{title:"Add an action",icon:"add",label:"Add",items:g(d,e=>{ue({cleanup:[...j.cleanup??[],e]}),U((j.cleanup??[]).length)})})),e.createElement("div",{className:"small muted"},"Done after the demo - when it ends, or is stopped - quickly and unseen: filters cleared, what it opened closed, what it changed changed back. So it plays again, and the next one starts where it expects. What the app cannot undo itself, its start resets (the app's ",e.createElement("span",{className:"mono"},"start.go"),")."),(j.cleanup??[]).map((t,a)=>e.createElement(p,{key:`cleanup.${a}`,engine:d,action:t,index:a,count:(j.cleanup??[]).length,open:J===a,sentences:[],onOpen:()=>U(J===a?void 0:a),onChange:e=>ue({cleanup:(j.cleanup??[]).map((t,n)=>n===a?e:t)}),onMove:e=>{const t=[...j.cleanup??[]],n=a+e;n<0||n>=t.length||([t[a],t[n]]=[t[n],t[a]],ue({cleanup:t}),U(n))},onDuplicate:()=>ue({cleanup:[...(j.cleanup??[]).slice(0,a+1),l(t),...(j.cleanup??[]).slice(a+1)]}),onDelete:()=>{ue({cleanup:(j.cleanup??[]).filter((e,t)=>t!==a)}),U(void 0)},picking:X}))),"steps"===A&&Ne&&!G&&e.createElement(e.Fragment,null,e.createElement("div",{className:"pane"},e.createElement("div",{className:"row"},e.createElement("strong",{className:"grow"},"Step ",le+1," of ",ie.length),e.createElement(v,{icon:"up",small:!0,kind:"bare",title:"Earlier",disabled:0===le,onClick:()=>ye(-1)}),e.createElement(v,{icon:"down",small:!0,kind:"bare",title:"Later",disabled:le===ie.length-1,onClick:()=>ye(1)}),e.createElement(v,{icon:"duplicate",small:!0,kind:"bare",title:"Duplicate",onClick:()=>{ve([...ie.slice(0,le+1),l(Ne),...ie.slice(le+1)]),M(le+1)}}),e.createElement(v,{icon:"delete",small:!0,kind:"bare",title:"Delete this step",disabled:ie.length<2,onClick:()=>{ve(ie.filter((e,t)=>t!==le)),M(Math.max(0,le-1))}})),e.createElement("input",{className:"field",placeholder:"Title, for the editor and the timeline",value:Ne.title??"",onChange:e=>fe(N(Ne,"title",e.target.value||void 0))}),re.map(t=>e.createElement(C,{key:t,engine:d,language:t,text:Ne.say[t]??"",onChange:e=>fe({...Ne,say:N(Ne.say,t,e||void 0)})})),e.createElement("div",{className:"row",style:{flexWrap:"wrap",gap:12}},e.createElement("span",{className:"small muted"},"Hold after, ms"),e.createElement(E,{value:Ne.hold,width:70,placeholder:"0",onChange:e=>fe(N(Ne,"hold",e))}),e.createElement(f,{label:"Wait for the presenter after it",checked:Boolean(Ne.pause),onChange:e=>fe(N(Ne,"pause",e||void 0))}),e.createElement("span",{className:"small muted"},Ce(le)))),e.createElement("div",{className:"pane",style:{flex:1.3}},e.createElement("div",{className:"row"},e.createElement("strong",{className:"grow"},"Actions"),e.createElement("span",{className:"small muted"},"played one after the other, while the narration speaks"),e.createElement(w,{title:"Add an action",icon:"add",label:"Add",items:g(d,e=>{fe({...Ne,actions:[...Ne.actions,e]}),U(Ne.actions.length)})})),0===Ne.actions.length&&e.createElement("div",{className:"muted small"},"None yet: add one, or record them (●) by doing them on the page."),Ne.actions.map((t,a)=>e.createElement(p,{key:`${le}.${a}`,engine:d,action:t,index:a,count:Ne.actions.length,open:J===a,error:W.get(`${le}.${a}`),sentences:r(o(Ne,_)),onOpen:()=>U(J===a?void 0:a),onChange:e=>((e,t)=>fe({...ie[le],actions:ie[le].actions.map((a,n)=>n===e?t:a)}))(a,e),onMove:e=>((e,t)=>{const a=e+t,n=[...ie[le].actions];a<0||a>=n.length||([n[e],n[a]]=[n[a],n[e]],fe({...ie[le],actions:n}),U(a))})(a,e),onDuplicate:()=>fe({...Ne,actions:[...Ne.actions.slice(0,a+1),l(t),...Ne.actions.slice(a+1)]}),onDelete:()=>{fe({...Ne,actions:Ne.actions.filter((e,t)=>t!==a)}),U(void 0)},picking:X})))),"text"===A&&e.createElement("div",{className:"pane",style:{flexDirection:"row"}},e.createElement("textarea",{className:"field mono grow",spellCheck:!1,value:P.json,onChange:e=>V({...P,json:e.target.value})}),e.createElement("textarea",{className:"field mono grow",spellCheck:!1,value:P.scenario,placeholder:"The scenario, for people (.md)",onChange:e=>V({...P,scenario:e.target.value})})),"video"===A&&e.createElement(x,{engine:d,draft:j})))}function N(e,t,a){const n={...e,[t]:a};return void 0===a&&delete n[t],n}function C({engine:t,language:a,text:n,onChange:l}){const[o,s]=i(),[c,d]=i(),[p,g]=i(),h=r(n);return e.createElement("div",{className:"col",style:{gap:4}},e.createElement("div",{className:"row"},e.createElement("span",{className:"badge accent"},a),e.createElement("span",{className:"small muted grow"},h.length," sentence",1===h.length?"":"s",c?` · ${c}`:""),e.createElement(v,{icon:p?"stop":"listen",small:!0,kind:"bare",title:p?"Stop":"Listen, in the voice chosen",disabled:!n.trim(),onClick:()=>{(async()=>{if(p)return p();let e=!1,i=()=>{};g(()=>()=>{e=!0,i()}),t.speech.wake();for(const l of r(n)){if(e)break;d("Making the voice…");const n=await t.speech.say(l,a).catch(e=>{t.say(e.message,!0)});if(d(void 0),!n)break;i=n.stop,await n.done}d(void 0),g(void 0)})()}}),e.createElement(v,{icon:o?"stop":"mic",small:!0,kind:"bare",on:Boolean(o),title:o?"Stop, and write what was said":"Dictate: speak, then stop",onClick:()=>{(async()=>{if(o){s(void 0),d("Transcribing…");try{const e=(await t.transcribe(await o.stop(),a)).map(e=>e.text).join(" ").trim();e&&l([n.trim(),e].filter(Boolean).join(" "))}catch(e){t.say(e.message,!0)}d(void 0)}else try{s(await m())}catch(e){t.say(`Microphone: ${e.message}`,!0)}})()},style:o?{color:"var(--danger)"}:void 0})),e.createElement("textarea",{className:"field",rows:3,placeholder:`Narration (${a}): what the viewer should notice, a sentence a subtitle`,value:n,onChange:e=>l(e.target.value)}))}function x({engine:n,draft:i}){const l=n.entriesNow().find(e=>e.demo.id===i.id),o=l?.video,s=a(()=>o&&{video:URL.createObjectURL(o.blob),vtt:URL.createObjectURL(new Blob([o.vtt],{type:"text/vtt"}))},[o]);if(t(()=>()=>{s&&(URL.revokeObjectURL(s.video),URL.revokeObjectURL(s.vtt))},[s]),!o||!s)return e.createElement("div",{className:"pane muted"},"Not filmed yet: film it (the film button) to make a video with narration and subtitles, kept here.");const r=o.json!==JSON.stringify({...i,scenario:void 0,savedAt:void 0})&&o.json!==JSON.stringify(i);return e.createElement("div",{className:"pane",style:{flexDirection:"row"}},e.createElement("div",{className:"grow",style:{minHeight:0,display:"flex"}},e.createElement("video",{src:s.video,controls:!0,style:{maxHeight:"100%"}},e.createElement("track",{kind:"subtitles",src:s.vtt,srcLang:o.language??"en",label:"Narration",default:!0}))),e.createElement("div",{className:"col",style:{width:240}},e.createElement("span",{className:"small muted"},new Date(o.at).toLocaleString()," · ",Math.round(o.blob.size/1e5)/10," MB · ",o.blob.type.split(";")[0]),r&&e.createElement("span",{className:"small error"},"Filmed from an older version of the demo."),e.createElement(v,{icon:"download",onClick:()=>n.downloadVideo(o,i.title)},"Video"),e.createElement(v,{icon:"subtitles",onClick:()=>n.downloadVideo(o,i.title,"vtt")},"Subtitles .vtt"),e.createElement(v,{icon:"subtitles",onClick:()=>n.downloadVideo(o,i.title,"srt")},"Subtitles .srt"),e.createElement(v,{icon:"share",onClick:()=>{n.shareVideo(o,i.title).then(e=>!e&&n.say("No share sheet here: download it instead."))}},"Share…"),o.voice&&e.createElement(v,{icon:"download",onClick:()=>n.downloadVideo({...o,blob:o.voice},`${i.title} voice`)},"The presenter's voice"),e.createElement(v,{icon:"delete",kind:"danger",onClick:()=>{n.store.deleteVideo(o.id)}},"Delete the video"),e.createElement("span",{className:"small muted"},d(i.title,o.blob.type.includes("mp4")?"mp4":"webm"))))}
1
+ import e,{useEffect as t,useMemo as a,useRef as n,useState as i}from"react";import{copyOf as o,sayOf as l,scenarioOf as s,sentences as r}from"../model/Demo.js";import{clock as c}from"../model/Timing.js";import{fileName as d}from"../store/Share.js";import{recordMicrophone as m}from"../video/Film.js";import{ActionRow as p,addActionItems as h,readAction as g}from"./Actions.js";import{useEngine as u}from"./Hooks.js";import{Button as v,Check as f,Menu as w,NumberField as E,Segmented as k}from"./Kit.js";import{Timeline as y}from"./Timeline.js";const b="protomaze-demo-engine:studio-height";export function Studio({engine:d,theme:m}){const S=u(d),D=S.studio,[j,$]=i(()=>o(D.demo)),[L,O]=i(()=>JSON.stringify(D.demo)),T=n({back:[],forward:[]}),[R,M]=i(0),[J,U]=i(),[A,P]=i("steps"),[F,V]=i({json:"",scenario:""}),[z,B]=i(),[W,H]=i(new Map),[K,q]=i(()=>Number(localStorage.getItem(b))||Math.round(.46*innerHeight)),[I,Y]=i(!1),[G,Z]=i(!1),[Q,X]=i(!1),[_,ee]=i(()=>d.language()),te=S.session,ae="idle"!==te.mode,ne="playing"!==te.mode||te.checking?void 0:te,ie=j.steps,oe=Math.min(R,Math.max(0,ie.length-1)),le=ne&&ne.demo.id===j.id?ne.step:oe,se=JSON.stringify(j)!==L,re=a(()=>Array.from(new Set([...d.languages(),...d.languagesOf(j)])),[j]),ce=d.entriesNow().find(e=>e.demo.id===j.id),de=d.timing(j,_),me=S.lastRun?.json===JSON.stringify(j)&&S.lastRun.language===_,pe=(e,t=!0)=>{t&&(T.current.back.push(j),T.current.back.length>200&&T.current.back.shift(),T.current.forward=[]),$(e)},he=()=>{const e=T.current.back.pop();e&&(T.current.forward.push(j),$(e))},ge=()=>{const e=T.current.forward.pop();e&&(T.current.back.push(j),$(e))},ue=e=>pe({...j,...e}),ve=e=>ue({steps:e}),fe=e=>ve(ie.map((t,a)=>a===oe?e:t));t(()=>{D.recorded&&pe({...j,steps:D.recorded.steps})},[D.recorded?.at]);const we=()=>{const{demo:e,problems:t}=d.parse(F.json);if(e)return B(void 0),{...e,scenario:F.scenario};B(t.slice(0,4).map(e=>`${e.path||"demo"}: ${e.message}`).join(" · "))},Ee=async()=>{const e="text"===A?we():j;if(e)try{await d.save(e),$(e),O(JSON.stringify(e)),d.say(`Saved "${e.title}".`)}catch(e){d.say(e.message,!0)}},ke=e=>{d.play(j,{from:e,language:_})},ye=e=>{const t=oe+e;if(t<0||t>=ie.length)return;const a=[...ie];[a[oe],a[t]]=[a[t],a[oe]],ve(a),M(t)},be=I||Q||"recording"===te.mode||Boolean(ne),Ne=ie[oe],Ce=e=>{const t=de.steps.find(t=>t.step===e);return t?`${((t.end-t.start)/1e3).toFixed(1)} s`:""};return e.createElement("div",{className:"pde studio"+(be?" collapsed":""),"data-theme":m,"data-demo-ignore":!0,onKeyDown:e=>{if(!(e.ctrlKey||e.metaKey))return;const t=e.key.toLowerCase();"s"===t?(e.preventDefault(),Ee()):"z"!==t||e.shiftKey||"text"===A?("y"===t||"z"===t&&e.shiftKey)&&"text"!==A&&(e.preventDefault(),ge()):(e.preventDefault(),he())},style:{height:be?void 0:K,display:Q?"none":void 0}},e.createElement("div",{className:"grip",onPointerDown:e=>{const t=e.clientY,a=K,n=e=>q(Math.max(180,Math.min(innerHeight-40,a+t-e.clientY))),i=()=>{window.removeEventListener("pointermove",n),window.removeEventListener("pointerup",i),q(e=>(localStorage.setItem(b,String(e)),e))};window.addEventListener("pointermove",n),window.addEventListener("pointerup",i)}}),e.createElement("div",{className:"head"},e.createElement("input",{className:"field",style:{width:240,fontWeight:600},value:j.title,title:"Title",onChange:e=>ue({title:e.target.value})}),e.createElement("input",{className:"field grow",style:{minWidth:120},placeholder:"Description: who it is for, what it shows",value:j.description??"",onChange:e=>ue({description:e.target.value})}),re.length>1&&e.createElement("select",{className:"field",title:"The language played, and timed",value:_,onChange:e=>ee(e.target.value)},re.map(t=>e.createElement("option",{key:t,value:t},t))),e.createElement("div",{className:"sep"}),!ne&&e.createElement(e.Fragment,null,e.createElement(v,{icon:"first",title:"Play from the start",disabled:ae,onClick:()=>ke(0)}),e.createElement(v,{icon:"play",kind:"primary",title:`Play from step ${oe+1}`,disabled:ae,onClick:()=>ke(oe)})),!ne&&e.createElement(w,{title:"Present, guide, loop",icon:"present",items:[{label:`Present from step ${oe+1}: waits after each step, the presenter's screen beside it`,icon:"present",disabled:ae,onClick:()=>{d.present(j,{from:oe,language:_})}},{label:"The presenter's screen, always on top",icon:"present",onClick:()=>{d.openPresenter({onTop:!0})}},{label:`Guide from step ${oe+1}: the viewer does it`,icon:"guide",disabled:ae,onClick:()=>{d.guide(j,{from:oe,language:_})}},{label:"Loop it: an expo booth",icon:"loop",disabled:ae,onClick:()=>{d.loop([j])}}]}),ne&&e.createElement(e.Fragment,null,e.createElement(v,{icon:ne.paused?"play":"pause",kind:"primary",title:ne.waiting?"Continue":ne.paused?"Resume":"Pause",onClick:()=>ne.waiting?d.next():d.togglePause()}),e.createElement(v,{icon:"right",title:"Next step",onClick:()=>d.next()}),e.createElement(v,{icon:"stop",title:"Stop",onClick:()=>d.stop()})),e.createElement(v,{icon:"record",title:`Record new steps after step ${oe+1}`,disabled:ae,onClick:()=>{d.record({into:j,after:oe})},style:{color:"var(--danger)"}}),e.createElement(v,{icon:"film",title:"Film it: a video with narration and subtitles",disabled:ae,onClick:()=>{d.film(j,{language:_})}}),e.createElement(v,{icon:"check",title:"Check: plays it fast and silent, and marks what fails",disabled:ae,onClick:()=>{(async()=>{const e=await d.check(j);H(new Map(e.failures.map(e=>[`${e.step}.${e.index}`,e.error]))),e.ok?d.say(`Every step plays: ${c(e.duration)} at speed.`):d.say(e.failures.length?`${e.failures.length} action${1===e.failures.length?"":"s"} failed: in red.`:e.error??"Failed",!0);const t=e.failures[0];t&&(M(t.step),U(t.index))})()}}),e.createElement("div",{className:"sep"}),e.createElement(v,{icon:"undo",kind:"bare",title:"Undo (Ctrl+Z)",disabled:0===T.current.back.length,onClick:he}),e.createElement(v,{icon:"redo",kind:"bare",title:"Redo (Ctrl+Y)",disabled:0===T.current.forward.length,onClick:ge}),e.createElement(v,{icon:"save",kind:se?"primary":void 0,title:"Save here (Ctrl+S)",onClick:()=>{Ee()}},se?"Save":"Saved"),e.createElement(w,{title:"Share, export",icon:"share",items:[{label:"Download .demo.json",icon:"download",onClick:()=>d.downloadDemo(j)},{label:"Download scenario .md",icon:"download",onClick:()=>d.downloadDemo(j,"md")},{label:"Copy a link with the demo",icon:"link",onClick:()=>{d.link(j).then(e=>navigator.clipboard.writeText(e)).then(()=>d.say("Link copied: it opens the app with this demo."))}},{label:"Copy JSON",icon:"copy",onClick:()=>{navigator.clipboard.writeText(JSON.stringify({...j,scenario:void 0,savedAt:void 0},null,2)).then(()=>d.say("JSON copied."))}},{label:"Narration pack (.zip): no key, no download, for every viewer",icon:"listen",onClick:()=>{d.downloadPack(j)}},ce?.video&&{label:"Download the video",icon:"film",onClick:()=>d.downloadVideo(ce.video,j.title)},{heading:"This demo"},"edited"===ce?.origin&&{label:"Revert to the app’s version",icon:"undo",onClick:()=>{window.confirm("Drop the changes kept here?")&&d.remove(j.id)}},"here"===ce?.origin&&{label:"Delete",icon:"delete",onClick:()=>{window.confirm(`Delete "${j.title}"?`)&&d.remove(j.id)}}]}),e.createElement(k,{value:A,onChange:e=>{if(e!==A){if("text"===A){const e=we();if(!e)return;JSON.stringify(e)!==JSON.stringify(j)&&pe(e)}"text"===e&&(()=>{const{scenario:e,savedAt:t,...a}=j;V({json:JSON.stringify(a,null,2),scenario:j.scenario??s(j,_)}),B(void 0)})(),P(e)}},options:[["steps","Steps"],["text","Text"],["video","Video",ce?.video?"Its last video":"Not filmed yet"]]}),e.createElement(v,{icon:I?"maximize":"minimize",kind:"bare",title:I?"Unfold":"Fold",onClick:()=>Y(!I)}),e.createElement(v,{icon:"close",kind:"bare",title:"Close",onClick:()=>{se&&!window.confirm("Close without saving?")||d.closeStudio()}})),e.createElement(y,{demo:j,timing:de,measured:me,step:le,action:J,theme:m,accent:"#ffb300",playhead:ne&&ne.demo.id===j.id?()=>d.elapsed():void 0,read:e=>g(d,e),onPick:(e,t)=>{ne&&ne.demo.id===j.id&&d.goTo(e)||(M(e),U(t),I&&Y(!1))}}),z&&e.createElement("div",{className:"error small",style:{padding:"4px 12px"}},z),e.createElement("div",{className:"body"},"text"!==A&&e.createElement("div",{className:"steps"},ie.map((t,a)=>e.createElement("div",{key:a,className:["step",a===oe&&!G&&"on",ne&&a===le&&"playing"].filter(Boolean).join(" "),onClick:()=>{M(a),U(void 0),Z(!1),function(e){if("video"!==A)return;const t=ce?.video?.timing?.steps.find(t=>t.step===e),a=document.querySelector("protomaze-demo-engine")?.shadowRoot?.querySelector("video");t&&a&&(a.currentTime=t.start/1e3)}(a)}},e.createElement("span",{className:"n"},a+1),e.createElement("div",{className:"col grow",style:{gap:2}},e.createElement("div",{className:"row"},e.createElement("span",{className:"grow ellipsis",style:{fontWeight:500}},t.title||function(e,t){return r(l(e,t))[0]}(t,_)||"Untitled"),e.createElement("span",{className:"small muted"},Ce(a))),t.title&&e.createElement("span",{className:"say"},l(t,_)),e.createElement("span",{className:"small muted"},t.actions.length," action",1===t.actions.length?"":"s",t.pause?" · waits":"")))),e.createElement(v,{icon:"add",small:!0,onClick:()=>{ve([...ie.slice(0,oe+1),{say:{},actions:[]},...ie.slice(oe+1)]),M(oe+1),Z(!1)}},"New step"),e.createElement("div",{className:["step",G&&"on"].filter(Boolean).join(" "),style:{marginTop:6},onClick:()=>{Z(!0),U(void 0)},title:"Done after the demo, quickly and unseen, so the app is as it found it"},e.createElement("span",{className:"n"},"↺"),e.createElement("div",{className:"col grow",style:{gap:2}},e.createElement("span",{style:{fontWeight:500}},"Cleanup"),e.createElement("span",{className:"small muted"},(j.cleanup??[]).length," action",1===(j.cleanup??[]).length?"":"s"," after it, unseen")))),"steps"===A&&G&&e.createElement("div",{className:"pane"},e.createElement("div",{className:"row"},e.createElement("strong",{className:"grow"},"Cleanup"),e.createElement(w,{title:"Add an action",icon:"add",label:"Add",items:h(d,e=>{ue({cleanup:[...j.cleanup??[],e]}),U((j.cleanup??[]).length)})})),e.createElement("div",{className:"small muted"},"Done after the demo - when it ends, or is stopped - quickly and unseen: filters cleared, what it opened closed, what it changed changed back. So it plays again, and the next one starts where it expects. What the app cannot undo itself, its start resets (the app's ",e.createElement("span",{className:"mono"},"start.go"),")."),(j.cleanup??[]).map((t,a)=>e.createElement(p,{key:`cleanup.${a}`,engine:d,action:t,index:a,count:(j.cleanup??[]).length,open:J===a,sentences:[],onOpen:()=>U(J===a?void 0:a),onChange:e=>ue({cleanup:(j.cleanup??[]).map((t,n)=>n===a?e:t)}),onMove:e=>{const t=[...j.cleanup??[]],n=a+e;n<0||n>=t.length||([t[a],t[n]]=[t[n],t[a]],ue({cleanup:t}),U(n))},onDuplicate:()=>ue({cleanup:[...(j.cleanup??[]).slice(0,a+1),o(t),...(j.cleanup??[]).slice(a+1)]}),onDelete:()=>{ue({cleanup:(j.cleanup??[]).filter((e,t)=>t!==a)}),U(void 0)},picking:X}))),"steps"===A&&Ne&&!G&&e.createElement(e.Fragment,null,e.createElement("div",{className:"pane"},e.createElement("div",{className:"row"},e.createElement("strong",{className:"grow"},"Step ",oe+1," of ",ie.length),e.createElement(v,{icon:"up",small:!0,kind:"bare",title:"Earlier",disabled:0===oe,onClick:()=>ye(-1)}),e.createElement(v,{icon:"down",small:!0,kind:"bare",title:"Later",disabled:oe===ie.length-1,onClick:()=>ye(1)}),e.createElement(v,{icon:"duplicate",small:!0,kind:"bare",title:"Duplicate",onClick:()=>{ve([...ie.slice(0,oe+1),o(Ne),...ie.slice(oe+1)]),M(oe+1)}}),e.createElement(v,{icon:"delete",small:!0,kind:"bare",title:"Delete this step",disabled:ie.length<2,onClick:()=>{ve(ie.filter((e,t)=>t!==oe)),M(Math.max(0,oe-1))}})),e.createElement("input",{className:"field",placeholder:"Title, for the editor and the timeline",value:Ne.title??"",onChange:e=>fe(N(Ne,"title",e.target.value||void 0))}),re.map(t=>e.createElement(C,{key:t,engine:d,language:t,text:Ne.say[t]??"",onChange:e=>fe({...Ne,say:N(Ne.say,t,e||void 0)})})),e.createElement("textarea",{className:"field",rows:2,placeholder:"Notes for the presenter: on their screen only, never said or shown",value:Ne.notes??"",onChange:e=>fe(N(Ne,"notes",e.target.value||void 0))}),e.createElement("div",{className:"row",style:{flexWrap:"wrap",gap:12}},e.createElement("span",{className:"small muted"},"Hold after, ms"),e.createElement(E,{value:Ne.hold,width:70,placeholder:"0",onChange:e=>fe(N(Ne,"hold",e))}),e.createElement(f,{label:"Wait for the presenter after it",checked:Boolean(Ne.pause),onChange:e=>fe(N(Ne,"pause",e||void 0))}),e.createElement("span",{className:"small muted"},Ce(oe)))),e.createElement("div",{className:"pane",style:{flex:1.3}},e.createElement("div",{className:"row"},e.createElement("strong",{className:"grow"},"Actions"),e.createElement("span",{className:"small muted"},"played one after the other, while the narration speaks"),e.createElement(w,{title:"Add an action",icon:"add",label:"Add",items:h(d,e=>{fe({...Ne,actions:[...Ne.actions,e]}),U(Ne.actions.length)})})),0===Ne.actions.length&&e.createElement("div",{className:"muted small"},"None yet: add one, or record them (●) by doing them on the page."),Ne.actions.map((t,a)=>e.createElement(p,{key:`${oe}.${a}`,engine:d,action:t,index:a,count:Ne.actions.length,open:J===a,error:W.get(`${oe}.${a}`),sentences:r(l(Ne,_)),onOpen:()=>U(J===a?void 0:a),onChange:e=>((e,t)=>fe({...ie[oe],actions:ie[oe].actions.map((a,n)=>n===e?t:a)}))(a,e),onMove:e=>((e,t)=>{const a=e+t,n=[...ie[oe].actions];a<0||a>=n.length||([n[e],n[a]]=[n[a],n[e]],fe({...ie[oe],actions:n}),U(a))})(a,e),onDuplicate:()=>fe({...Ne,actions:[...Ne.actions.slice(0,a+1),o(t),...Ne.actions.slice(a+1)]}),onDelete:()=>{fe({...Ne,actions:Ne.actions.filter((e,t)=>t!==a)}),U(void 0)},picking:X})))),"text"===A&&e.createElement("div",{className:"pane",style:{flexDirection:"row"}},e.createElement("textarea",{className:"field mono grow",spellCheck:!1,value:F.json,onChange:e=>V({...F,json:e.target.value})}),e.createElement("textarea",{className:"field mono grow",spellCheck:!1,value:F.scenario,placeholder:"The scenario, for people (.md)",onChange:e=>V({...F,scenario:e.target.value})})),"video"===A&&e.createElement(x,{engine:d,draft:j})))}function N(e,t,a){const n={...e,[t]:a};return void 0===a&&delete n[t],n}function C({engine:t,language:a,text:n,onChange:o}){const[l,s]=i(),[c,d]=i(),[p,h]=i(),g=r(n);return e.createElement("div",{className:"col",style:{gap:4}},e.createElement("div",{className:"row"},e.createElement("span",{className:"badge accent"},a),e.createElement("span",{className:"small muted grow"},g.length," sentence",1===g.length?"":"s",c?` · ${c}`:""),e.createElement(v,{icon:p?"stop":"listen",small:!0,kind:"bare",title:p?"Stop":"Listen, in the voice chosen",disabled:!n.trim(),onClick:()=>{(async()=>{if(p)return p();let e=!1,i=()=>{};h(()=>()=>{e=!0,i()}),t.speech.wake();for(const o of r(n)){if(e)break;d("Making the voice…");const n=await t.speech.say(o,a).catch(e=>{t.say(e.message,!0)});if(d(void 0),!n)break;i=n.stop,await n.done}d(void 0),h(void 0)})()}}),e.createElement(v,{icon:l?"stop":"mic",small:!0,kind:"bare",on:Boolean(l),title:l?"Stop, and write what was said":"Dictate: speak, then stop",onClick:()=>{(async()=>{if(l){s(void 0),d("Transcribing…");try{const e=(await t.transcribe(await l.stop(),a)).map(e=>e.text).join(" ").trim();e&&o([n.trim(),e].filter(Boolean).join(" "))}catch(e){t.say(e.message,!0)}d(void 0)}else try{s(await m())}catch(e){t.say(`Microphone: ${e.message}`,!0)}})()},style:l?{color:"var(--danger)"}:void 0})),e.createElement("textarea",{className:"field",rows:3,placeholder:`Narration (${a}): what the viewer should notice, a sentence a subtitle`,value:n,onChange:e=>o(e.target.value)}))}function x({engine:n,draft:i}){const o=n.entriesNow().find(e=>e.demo.id===i.id),l=o?.video,s=a(()=>l&&{video:URL.createObjectURL(l.blob),vtt:URL.createObjectURL(new Blob([l.vtt],{type:"text/vtt"}))},[l]);if(t(()=>()=>{s&&(URL.revokeObjectURL(s.video),URL.revokeObjectURL(s.vtt))},[s]),!l||!s)return e.createElement("div",{className:"pane muted"},"Not filmed yet: film it (the film button) to make a video with narration and subtitles, kept here.");const r=l.json!==JSON.stringify({...i,scenario:void 0,savedAt:void 0})&&l.json!==JSON.stringify(i);return e.createElement("div",{className:"pane",style:{flexDirection:"row"}},e.createElement("div",{className:"grow",style:{minHeight:0,display:"flex"}},e.createElement("video",{src:s.video,controls:!0,style:{maxHeight:"100%"}},e.createElement("track",{kind:"subtitles",src:s.vtt,srcLang:l.language??"en",label:"Narration",default:!0}))),e.createElement("div",{className:"col",style:{width:240}},e.createElement("span",{className:"small muted"},new Date(l.at).toLocaleString()," · ",Math.round(l.blob.size/1e5)/10," MB · ",l.blob.type.split(";")[0]),r&&e.createElement("span",{className:"small error"},"Filmed from an older version of the demo."),e.createElement(v,{icon:"download",onClick:()=>n.downloadVideo(l,i.title)},"Video"),e.createElement(v,{icon:"subtitles",onClick:()=>n.downloadVideo(l,i.title,"vtt")},"Subtitles .vtt"),e.createElement(v,{icon:"subtitles",onClick:()=>n.downloadVideo(l,i.title,"srt")},"Subtitles .srt"),e.createElement(v,{icon:"share",onClick:()=>{n.shareVideo(l,i.title).then(e=>!e&&n.say("No share sheet here: download it instead."))}},"Share…"),l.voice&&e.createElement(v,{icon:"download",onClick:()=>n.downloadVideo({...l,blob:l.voice},`${i.title} voice`)},"The presenter's voice"),e.createElement(v,{icon:"delete",kind:"danger",onClick:()=>{n.store.deleteVideo(l.id)}},"Delete the video"),e.createElement("span",{className:"small muted"},d(i.title,l.blob.type.includes("mp4")?"mp4":"webm"))))}