@protomaze/demo-engine 0.1.10 → 0.1.11

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
@@ -1,12 +1,12 @@
1
1
  <!-- Made from src/agent/Guide.ts by dev/guide.js: edit that. -->
2
2
 
3
- An app using @protomaze/demo-engine exposes these tools on `window.demoEngine` in development.
3
+ An app using @protomaze/demo-engine exposes these tools on `window.demoEngine` (unless it keeps them off).
4
4
  Drive them through a browser's JavaScript console or an agent's "run JavaScript in the page" tool.
5
5
 
6
6
  # Making a demo with demoEngine
7
7
 
8
- You see the app in a browser and run JavaScript in it. `window.demoEngine` has the tools; every
9
- result is plain data. A demo is steps; each step's narration is spoken (and subtitled) a sentence at
8
+ You see the app in a browser and run JavaScript in it. `window.demoEngine` has the tools: `await`
9
+ each call (most return a Promise); every result is plain data. A demo is steps; each step's narration is spoken (and subtitled) a sentence at
10
10
  a time while its actions play one after the other. Actions point at elements as a person would: by
11
11
  what they show, not where they are.
12
12
 
@@ -23,11 +23,20 @@ what they show, not where they are.
23
23
  5. `demoEngine.validate(demo)` - its shape. Then `await demoEngine.check(demo)` - from the demo's
24
24
  start, fast and silent, going past what fails, its cleanup after; fix every failure and check
25
25
  again until `ok` twice in a row (the second run proves the cleanup). The page's CSS transitions
26
- and animations are off while it runs, so it works in a background tab too.
27
- 6. `await demoEngine.save(demo)`, then `demoEngine.open(demo.id)` - the person sees it in the
28
- studio, can play, tune, film and share it. `demoEngine.play(id)` plays it with sound once the
26
+ and animations are off while it runs, so it works in a background tab too. After a failure, what
27
+ follows is waited for 2 s only (it mostly failed with it): fix the first failure first.
28
+ 6. `await demoEngine.save(demo)`, then `demoEngine.open(demo.id)` where the person watches your
29
+ browser - they see it in the studio, can play, tune, film and share it (else see below). `demoEngine.play(id)` plays it with sound once the
29
30
  person clicks. `demoEngine.estimate(demo)` gives its length.
30
31
 
32
+ ## Your browser and the person's
33
+
34
+ What `save` keeps stays in the browser you work in. Not the person's own (a browser of yours,
35
+ another profile)? Give them `await demoEngine.link(id)`: opened in their browser, the demo is kept
36
+ there and opens in their studio. Where you can write files, `await demoEngine.get(id)` is its
37
+ `.demo.json` as well (the library's New → Import takes it). A demo of theirs comes to you the same
38
+ way: open its link, or `save(link)`, and it is kept in yours. Signing in to the app is theirs: ask.
39
+
31
40
  ## Length
32
41
 
33
42
  - Short (a teaser, one feature): 4-7 steps, 30-60 s, one or two sentences a step.
@@ -66,9 +75,9 @@ what they show, not where they are.
66
75
  "title": "Find an order",
67
76
  "say": { "en": "Every order lands here, newest first. Let's find one from Berlin." },
68
77
  "actions": [
69
- { "do": "spotlight", "target": { "css": "table", "text": "orders" }, "for": 2500 },
78
+ { "do": "spotlight", "target": { "css": "[data-demo=\"orders\"]" }, "text": { "en": "Orders", "de": "Aufträge" }, "for": 2500 },
70
79
  { "do": "type", "target": { "css": "input[type=\"search\"]" }, "text": "Berlin", "cue": 1 },
71
- { "do": "click", "target": { "css": "tr", "text": "berlin #" }, "wait": 1200 }
80
+ { "do": "click", "target": { "css": "td", "text": "berlin" }, "wait": 1200 }
72
81
  ]
73
82
  }
74
83
  ]
@@ -79,10 +88,13 @@ A target: `{ css, text?, key?, index? }` - the `index`th (0-based) element match
79
88
  is `text` (or the app's locale `key`'s text: works in every language). Labels compare without case,
80
89
  spacing, and with every number as "#": a row "Berlin 42" is "berlin #". Use the targets `page()` and
81
90
  `describe()` give: they prefer locale keys and named regions. Avoid `index` where a scope does it:
82
- `{ css: '[data-demo="filters"] button', text: 'apply' }`.
91
+ `{ css: '[data-demo="filters"] button', text: 'apply' }`. A label is the element's whole text, or its
92
+ `data-demo` name, or its `aria-label` - never a part: a table row's is all its cells, which change
93
+ with the data and the language ("open", "offen"). Target what stays: a cell, a `key`, a named region.
83
94
 
84
95
  Every action has `wait` (ms before it, default 800) and `cue` (start with the step's sentence of that
85
- index, 0-based: syncs a click with the words about it, in every language and voice).
96
+ index, 0-based: sentences end with . ? or !; syncs a click with the words about it, in every
97
+ language and voice).
86
98
 
87
99
  Interactions:
88
100
  - `click` { target, at?: [x, y] fractions of the box, double?, right?, shift?, ctrl?, alt?, meta? }
@@ -94,12 +106,15 @@ Interactions:
94
106
  - `scroll` { target?, by?: [x, y] } - into view, or by pixels
95
107
  - `waitFor` { target, gone?, timeout? } - until it shows (or goes): after what loads
96
108
 
97
- Presentation (shown until the step ends, or `for` ms; `clear` takes all down):
109
+ Presentation (shown until the step ends, or `for` ms; `clear` takes all down). Their text on the
110
+ screen - a card's title and text, a note, a label - is one for every language, or one per language
111
+ as `say` is: `{ "en": "Orders", "de": "Aufträge" }`.
98
112
  - `spotlight` { target, text?, padding? } - dims everything else: the one thing to look at
99
113
  - `ring` { target, text?, color?, shape?: 'box' | 'circle' } - a pulsing outline
100
114
  - `arrow` { target, text?, from?: 'top' | 'right' | 'bottom' | 'left' } - points at it
101
115
  - `callout` { text, target?, side?, corner? } - a note by the target, or in a corner
102
- - `blur` { target } - hides names, addresses, anything private
116
+ - `blur` { target } - hides names, addresses, anything private; for its step only: blur again first
117
+ thing in each step it shows in (`wait: 0`)
103
118
  - `card` { title, text? } - full screen: an opening title, a chapter, the end
104
119
  - `zoom` { target, scale? } - magnifies the page around it (1.8 by default)
105
120
  - `clear`
@@ -129,6 +144,6 @@ not there within half a second is skipped, so list every reset that might be nee
129
144
 
130
145
  help() · languages() · start() · page({ within?, query?, limit? }) · find(target) ·
131
146
  describe(css | [x, y]) · try(action) · preview(presentationAction, ms?) · demos() · get(id) ·
132
- validate(demo) · estimate(demoOrId) · check(demoOrId, { from?, to?, animations? }) · save(demo) · remove(id) ·
147
+ validate(demo) · estimate(demoOrId) · check(demoOrId, { from?, to?, animations? }) · save(demo | link) · remove(id) ·
133
148
  open(demoOrId) · play(demoOrId, { from? }) · guide(demoOrId, { from? }) · loop([demoOrId]) ·
134
149
  stopLoop() · stop() · state() · link(demoOrId)
package/README.md CHANGED
@@ -2,9 +2,9 @@
2
2
 
3
3
  Demos of a web app, made and played in the app itself, in the browser: no backend.
4
4
 
5
- - **Make**: by asking Claude in the app, in words ("a one-minute tour of the orders"); by any AI that
6
- runs JavaScript in the page (`window.demoEngine`); by recording what you do (and say); or by hand
7
- in the studio, on a `@protomaze/time` timeline.
5
+ - **Make**: by one's own Claude, with only the app's URL ("a one-minute tour of the orders"), or any
6
+ AI that runs JavaScript in the page (`window.demoEngine`); by recording what you do (and say); or
7
+ by hand in the studio, on a `@protomaze/time` timeline.
8
8
  - **Narrate**: text to speech in the browser (Kokoro, Piper: free, no key) or ElevenLabs; speech to
9
9
  text (Whisper in the browser, or ElevenLabs) turns what you said into narration and subtitles.
10
10
  A **narration pack** keeps a demo's finished audio, so every viewer hears it without a key, tokens
@@ -57,14 +57,16 @@ recording's microphone; a booth's demos; where the presenter's screen goes - and
57
57
  click sound and filming need. Everything else - the studio, the bars while playing and recording,
58
58
  effects - the engine renders over the app, in the top layer.
59
59
 
60
- **Ask Claude** (New → Ask Claude, a demo's ⋯ menu, the studio's ✦ button): people say what a demo
61
- should show, or how to change, clone or translate one. Claude works in the app as they watch - looks
62
- at the page, walks the path, writes the narration in every language, checks the demo twice, saves it
63
- and opens it in the studio - with the tools an AI has on `window.demoEngine`. It runs in the browser
64
- with the person's own Anthropic API key (kept in local storage, billed to them; the panel shows the
65
- tokens and about what they cost): the app needs no backend, only `connect-src https://api.anthropic.com`
66
- where it has a Content-Security-Policy. Claude Opus 5.5 at high effort, with the API's own fallback on
67
- a refusal. `assistant: false` hides it.
60
+ **With your own Claude**: anyone with the app's URL - no source code, no servers of their own - has
61
+ their Claude make, clone and change demos, working in a browser where it runs JavaScript (Claude in
62
+ Chrome, the Claude app's browser). The library's New → "With your own Claude" copies a prompt to
63
+ paste into it: the app's address, where the tools are (`window.demoEngine`, whose `help()` is
64
+ [AGENTS.md](AGENTS.md)), and how to hand the demo back; a demo's ⋯ menu copies one that brings the
65
+ demo along, in its link. Claude walks the app, writes the narration in every language, checks the
66
+ demo twice and saves it; when its browser is not the person's, it gives them the demo's link, which
67
+ opens it in their studio. The tools are on the page wherever the engine mounts: `agent: false` keeps
68
+ them off, `agent: () => …` decides as it mounts (an environment, a role). They can do what the
69
+ library can, in that browser, as the person signed in.
68
70
 
69
71
  From code: `engine.play(demo, { from })`, `engine.guide(demo)`, `engine.film(demo)`,
70
72
  `engine.record()`, `engine.loop(demos, { idle, reset: 'reload' })`, `engine.check(demo)`,
@@ -99,7 +101,9 @@ action (800), `cue` starts it with a sentence of the step: synced in every langu
99
101
 
100
102
  Actions: `click`, `hover`, `type`, `key`, `select`, `drag`, `scroll`, `waitFor`; and to present,
101
103
  `spotlight`, `ring`, `arrow`, `callout`, `blur`, `card`, `zoom`, `clear` (shown till the step ends,
102
- or `for` ms). [AGENTS.md](AGENTS.md) has every field; it is also what an AI reads.
104
+ or `for` ms); their text on the screen is one for every language, or one per language as narration
105
+ is (`{ "en": "Orders", "de": "Aufträge" }`). [AGENTS.md](AGENTS.md) has every field; it is also what
106
+ an AI reads.
103
107
 
104
108
  A demo leaves the app as it found it, so it plays again and the next starts where it expects:
105
109
  its `cleanup` actions run after it - when it ends or is stopped - quickly and unseen (filters
package/agent/Agent.d.ts CHANGED
@@ -33,7 +33,10 @@ export declare function agentTools(engine: DemoEngine): {
33
33
  height: number;
34
34
  };
35
35
  headings: string[];
36
- dialogs: string[];
36
+ dialogs: {
37
+ target: DemoTarget;
38
+ text: string;
39
+ }[];
37
40
  targets: Listed[];
38
41
  };
39
42
  /** How many elements a target names, whether the one it means shows, and where. */
@@ -63,6 +66,10 @@ export declare function agentTools(engine: DemoEngine): {
63
66
  error?: string;
64
67
  appeared: Listed[];
65
68
  gone: string[];
69
+ opened: {
70
+ target: DemoTarget;
71
+ text: string;
72
+ }[];
66
73
  }>;
67
74
  /** Shows a presentation action - spotlight, ring, arrow, callout, blur, card, zoom - for `ms`, to see how it looks. */
68
75
  preview: (action: DemoAction, ms?: number) => Promise<{
@@ -100,10 +107,16 @@ export declare function agentTools(engine: DemoEngine): {
100
107
  to?: number;
101
108
  animations?: boolean;
102
109
  }) => Promise<CheckReport>;
103
- /** Kept in this browser; shows in the library. Over an app's demo of the same id, until removed. */
104
- save: (demo: Demo) => Promise<{
110
+ /**
111
+ * Kept in this browser; shows in the library. Over an app's demo of the same id, until removed.
112
+ * Or a link `link()` made: the demo in it is kept here.
113
+ */
114
+ save: (demoOrLink: Demo | string) => Promise<{
105
115
  ok: boolean;
106
- problems: import("..").Problem[];
116
+ problems: {
117
+ path: string;
118
+ message: string;
119
+ }[];
107
120
  id?: undefined;
108
121
  } | {
109
122
  ok: boolean;
@@ -149,8 +162,22 @@ export declare function agentTools(engine: DemoEngine): {
149
162
  state: () => {
150
163
  message: string | undefined;
151
164
  };
152
- /** A link that opens the app with the demo in it. */
165
+ /**
166
+ * A link that opens the app with the demo in it: in any browser, which keeps it and opens it
167
+ * in the studio. How a demo goes from a browser of the AI's own to the person's.
168
+ */
153
169
  link: (demo: DemoOrId) => Promise<string>;
154
170
  };
155
171
  export type AgentTools = ReturnType<typeof agentTools>;
172
+ /**
173
+ * What a person tells their own Claude - working in a browser where it runs JavaScript (Claude in
174
+ * Chrome, the Claude app's browser) - to make a demo of the app at `url`, or to change `demo`, which
175
+ * comes with `link`. Ends where the person says what they want.
176
+ */
177
+ export declare function promptForClaude({ url, agent, demo, link }: {
178
+ url: string;
179
+ agent: string;
180
+ demo?: Demo;
181
+ link?: string;
182
+ }): string;
156
183
  export {};
package/agent/Agent.js CHANGED
@@ -1 +1 @@
1
- import{copyOf as e,isTarget as t}from"../model/Demo.js";import{clock as o}from"../model/Timing.js";import{validate as i}from"../model/Validate.js";import{GUIDE as a}from"./Guide.js";export function agentTools(r){const s=async e=>{if("string"!=typeof e)return e;const t=(await r.entries()).find(t=>t.demo.id===e);if(!t)throw new Error(`No demo "${e}": demoEngine.demos() lists them`);return t.demo};return{help:()=>a,languages:()=>({write:r.languages(),plays:r.language()}),start:()=>r.options.start?.current()??null,page:({within:e,query:t,limit:o}={})=>{const i=e=>e.getClientRects().length>0&&!e.closest("[data-demo-ignore]"),a=e=>Array.from(document.querySelectorAll(e)).filter(i).map(e=>e.innerText?.trim().replace(/\s+/g," ").slice(0,100)).filter(Boolean);return{url:window.location.href,title:document.title,viewport:{width:innerWidth,height:innerHeight},headings:a('h1, h2, h3, h4, h5, h6, [role="heading"]').slice(0,60),dialogs:a('dialog[open], [role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]').slice(0,10),targets:r.targets.list({within:e,query:t,limit:o??250})}},find:e=>{if(!t(e))throw new Error("A target is { css, text?, key?, index? }");const o=r.targets.matches(e),i=o[e.index??0],a=i?.getBoundingClientRect();return{matches:o.length,shown:Boolean(i&&i.getClientRects().length>0),...i?{label:r.targets.labelOf(i),box:{x:Math.round(a.x),y:Math.round(a.y),width:Math.round(a.width),height:Math.round(a.height)}}:{}}},describe:e=>{const t="string"==typeof e?document.querySelector(e):r.targets.targetElement(document.elementsFromPoint(e[0],e[1]).find(e=>!e.closest("[data-demo-ignore]"))??null);if(!t)throw new Error(`Nothing at ${JSON.stringify(e)}`);const o=r.targets.targetElement(t)??t;return{target:r.targets.describe(o),label:r.targets.labelOf(o),tag:o.tagName.toLowerCase()}},try:async e=>{const t=r.targets.list({limit:600}),o=await r.check({id:"try",title:"Try",steps:[{say:{},actions:[{...e,wait:0}]}]},{speed:2});await new Promise(e=>setTimeout(e,400));const i=r.targets.list({limit:600}),a=e=>JSON.stringify(e.target),s=new Set(t.map(a)),n=new Set(i.map(a));return{ok:o.ok,...o.ok?{}:{error:o.failures[0]?.error??o.error??o.problems.map(e=>`${e.path} ${e.message}`).join("; ")},appeared:i.filter(e=>!s.has(a(e))).slice(0,60),gone:t.filter(e=>!n.has(a(e))).map(e=>e.label).slice(0,60)}},preview:async(e,t=3e3)=>{const o=await r.check({id:"preview",title:"Preview",steps:[{say:{},actions:[{...e,wait:0}],hold:t}]},{speed:1});return{ok:o.ok,...o.ok?{}:{error:o.failures[0]?.error??o.error}}},demos:async()=>(await r.entries()).map(({demo:e,origin:t,video:i})=>({id:e.id,title:e.title,description:e.description??"",steps:e.steps.length,origin:t,languages:r.languagesOf(e),duration:o(r.timing(e).duration),video:Boolean(i)})),get:async t=>e(await s(t)),validate:e=>i(e,r.pluginKinds()),estimate:async e=>{const t=r.timing(await s(e));return{duration:o(t.duration),steps:t.steps.map(e=>({step:e.step,seconds:Math.round((e.end-e.start)/100)/10}))}},check:async(e,t={})=>r.check(await s(e),t),save:async e=>{const t=i(e,r.pluginKinds());return t.length?{ok:!1,problems:t}:(await r.save(e),{ok:!0,id:e.id})},remove:async e=>(await r.remove(e),{ok:!0}),open:async e=>(r.openStudio(await s(e)),{ok:!0}),play:async(e,t={})=>{r.play(await s(e),t);const o=r.getState().session;return{ok:!0,state:o.mode,..."ready"===o.mode?{note:'Waiting for the person to click "Play" on the page.'}:{}}},guide:async(e,t={})=>(r.guide(await s(e),t),{ok:!0,state:r.getState().session.mode}),loop:async e=>(r.loop(await Promise.all(e.map(s))),{ok:!0}),stopLoop:()=>(r.stopLoop(),{ok:!0}),stop:()=>(r.stop(),{ok:!0}),state:()=>{const{session:e,message:t}=r.getState(),{player:o,demo:i,...a}=e;return{...a,message:t?.text}},link:async e=>r.link(await s(e))}}
1
+ import{copyOf as e,isTarget as t}from"../model/Demo.js";import{clock as o}from"../model/Timing.js";import{validate as i}from"../model/Validate.js";import{demoIn as a}from"../store/Share.js";import{GUIDE as r}from"./Guide.js";export function agentTools(n){const s=async e=>{if("string"!=typeof e)return e;const t=(await n.entries()).find(t=>t.demo.id===e);if(!t)throw new Error(`No demo "${e}": demoEngine.demos() lists them`);return t.demo},l=e=>e.getClientRects().length>0&&!e.closest("[data-demo-ignore]"),d=e=>e.innerText?.trim().replace(/\s+/g," ").slice(0,100)??"",g=()=>Array.from(document.querySelectorAll('dialog[open], [role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]')).filter(l).slice(0,10).map(e=>({target:n.targets.describe(e),text:d(e)}));return{help:()=>r,languages:()=>({write:n.languages(),plays:n.language()}),start:()=>n.options.start?.current()??null,page:({within:e,query:t,limit:o}={})=>{return{url:window.location.href,title:document.title,viewport:{width:innerWidth,height:innerHeight},headings:(i='h1, h2, h3, h4, h5, h6, [role="heading"]',Array.from(document.querySelectorAll(i)).filter(l).map(d).filter(Boolean)).slice(0,60),dialogs:g(),targets:n.targets.list({within:e,query:t,limit:o??250})};var i},find:e=>{if(!t(e))throw new Error("A target is { css, text?, key?, index? }");const o=n.targets.matches(e),i=o[e.index??0],a=i?.getBoundingClientRect();return{matches:o.length,shown:Boolean(i&&i.getClientRects().length>0),...i?{label:n.targets.labelOf(i),box:{x:Math.round(a.x),y:Math.round(a.y),width:Math.round(a.width),height:Math.round(a.height)}}:{}}},describe:e=>{const t="string"==typeof e?document.querySelector(e):n.targets.targetElement(document.elementsFromPoint(e[0],e[1]).find(e=>!e.closest("[data-demo-ignore]"))??null);if(!t)throw new Error(`Nothing at ${JSON.stringify(e)}`);const o=n.targets.targetElement(t)??t;return{target:n.targets.describe(o),label:n.targets.labelOf(o),tag:o.tagName.toLowerCase()}},try:async e=>{const t=n.targets.list({limit:600}),o=new Set(g().map(e=>e.text)),i=await n.check({id:"try",title:"Try",steps:[{say:{},actions:[{...e,wait:0}]}]},{speed:2});await new Promise(e=>setTimeout(e,400));const a=n.targets.list({limit:600}),r=e=>JSON.stringify(e.target),s=new Set(t.map(r)),l=new Set(a.map(r));return{ok:i.ok,...i.ok?{}:{error:i.failures[0]?.error??i.error??i.problems.map(e=>`${e.path} ${e.message}`).join("; ")},appeared:a.filter(e=>!s.has(r(e))).slice(0,60),gone:t.filter(e=>!l.has(r(e))).map(e=>e.label).slice(0,60),opened:g().filter(e=>!o.has(e.text))}},preview:async(e,t=3e3)=>{const o=await n.check({id:"preview",title:"Preview",steps:[{say:{},actions:[{...e,wait:0}],hold:t}]},{speed:1});return{ok:o.ok,...o.ok?{}:{error:o.failures[0]?.error??o.error}}},demos:async()=>(await n.entries()).map(({demo:e,origin:t,video:i})=>({id:e.id,title:e.title,description:e.description??"",steps:e.steps.length,origin:t,languages:n.languagesOf(e),duration:o(n.timing(e).duration),video:Boolean(i)})),get:async t=>e(await s(t)),validate:e=>i(e,n.pluginKinds()),estimate:async e=>{const t=n.timing(await s(e));return{duration:o(t.duration),steps:t.steps.map(e=>({step:e.step,seconds:Math.round((e.end-e.start)/100)/10}))}},check:async(e,t={})=>n.check(await s(e),t),save:async e=>{const t="string"==typeof e?await a(e):e;if(!t)return{ok:!1,problems:[{path:"",message:"No demo in that link: link(id) makes one"}]};const o=i(t,n.pluginKinds());return o.length?{ok:!1,problems:o}:(await n.save(t),{ok:!0,id:t.id})},remove:async e=>(await n.remove(e),{ok:!0}),open:async e=>(n.openStudio(await s(e)),{ok:!0}),play:async(e,t={})=>{n.play(await s(e),t);const o=n.getState().session;return{ok:!0,state:o.mode,..."ready"===o.mode?{note:'Waiting for the person to click "Play" on the page.'}:{}}},guide:async(e,t={})=>(n.guide(await s(e),t),{ok:!0,state:n.getState().session.mode}),loop:async e=>(n.loop(await Promise.all(e.map(s))),{ok:!0}),stopLoop:()=>(n.stopLoop(),{ok:!0}),stop:()=>(n.stop(),{ok:!0}),state:()=>{const{session:e,message:t}=n.getState(),{player:o,demo:i,...a}=e;return{...a,message:t?.text}},link:async e=>n.link(await s(e))}}export function promptForClaude({url:e,agent:t,demo:o,link:i}){const a="in a browser where you can run JavaScript in the page (Claude in Chrome, or the browser in the Claude app)",r=["If the app asks for a sign-in, ask me to sign in there.",`The page has tools for demos on window.${t}: run ${t}.help() in the page first and follow it.`],n=`When it is checked and saved, give me the link from \`await ${t}.link(id)\`: it opens the demo in my own browser. If you can write files, also save \`await ${t}.get(id)\` as <id>.demo.json.`;return o&&i?[`Change the demo "${o.title}" (id "${o.id}") of the web app at ${e}`,`Open this link ${a}: it brings the demo into the app.`,i,...r,"A copy of it gets an id of its own.",n,"","What to change: "].join("\n"):[`Make a demo of the web app at ${e}`,`Work ${a}.`,...r,n,"","The demo should show: "].join("\n")}
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). The page's CSS transitions\n and animations are off while it runs, so it works in a background tab too.\n6. `await demoEngine.save(demo)`, then `demoEngine.open(demo.id)` - the person sees it in the\n studio, can play, tune, film and share it. `demoEngine.play(id)` plays it with sound once the\n person clicks. `demoEngine.estimate(demo)` gives its length.\n\n## Length\n\n- Short (a teaser, one feature): 4-7 steps, 30-60 s, one or two sentences a step.\n- Normal (a tour): 8-12 steps, 1-3 min.\n- Detailed (a deep dive): 12-25 steps, 3-6 min; still one idea per step.\n\n## What it is for\n\n- Marketing video: short, benefit first, a `card` to open and close, zooms on what impresses; no\n setup steps on screen. The person films it (film button); music can play under it.\n- Sales pitch: one step per point the presenter makes; `pause: true` on steps where they talk\n freely. They advance with a clicker (PageDown) and repeat with PageUp.\n- Expo booth: 30-90 s, readable without sound (subtitles carry it), ends where it started so it can\n loop. `demoEngine.loop([ids])` plays them unattended; a visitor's touch hands the app over.\n- Tutorial or training: `demoEngine.guide(id)` lets the viewer do each click and entry themselves,\n ringed with what to do. Narrate why, not only what; small steps; one new thing each.\n\n## Narration\n\n- For the viewer, about what matters to them: \"Which pipes need work first?\" before \"Click Risk\".\n- Present tense, plain words, at most ~20 words a sentence; a step ~1-3 sentences.\n- Say what to look at as it happens; name things as the app names them.\n- Every language of `languages().write`: `say: { en: '\u2026', de: '\u2026' }`. Same meaning, natural in each.\n- No \"In this demo\u2026\" filler; open with the question or the benefit, close with what was shown.\n\n## Format\n\n```json\n{\n \"id\": \"orders-tour\",\n \"title\": \"Orders, from list to invoice\",\n \"description\": \"One sentence: who it is for and what it shows.\",\n \"start\": { \"\u2026\": \"as demoEngine.start() gives it, or leave out\" },\n \"steps\": [\n {\n \"title\": \"Find an order\",\n \"say\": { \"en\": \"Every order lands here, newest first. Let's find one from Berlin.\" },\n \"actions\": [\n { \"do\": \"spotlight\", \"target\": { \"css\": \"table\", \"text\": \"orders\" }, \"for\": 2500 },\n { \"do\": \"type\", \"target\": { \"css\": \"input[type=\\\"search\\\"]\" }, \"text\": \"Berlin\", \"cue\": 1 },\n { \"do\": \"click\", \"target\": { \"css\": \"tr\", \"text\": \"berlin #\" }, \"wait\": 1200 }\n ]\n }\n ]\n}\n```\n\nA target: `{ css, text?, key?, index? }` - the `index`th (0-based) element matching `css` whose label\nis `text` (or the app's locale `key`'s text: works in every language). Labels compare without case,\nspacing, and with every number as \"#\": a row \"Berlin 42\" is \"berlin #\". Use the targets `page()` and\n`describe()` give: they prefer locale keys and named regions. Avoid `index` where a scope does it:\n`{ css: '[data-demo=\"filters\"] button', text: 'apply' }`.\n\nEvery action has `wait` (ms before it, default 800) and `cue` (start with the step's sentence of that\nindex, 0-based: syncs a click with the words about it, in every language and voice).\n\nInteractions:\n- `click` { target, at?: [x, y] fractions of the box, double?, right?, shift?, ctrl?, alt?, meta? }\n- `hover` { target, at? } - shows tooltips and hover cards (not CSS :hover looks)\n- `type` { target, text } - replaces the field's text, a letter at a time\n- `key` { key, target? } - 'Escape', 'Enter', 'ArrowDown', 'Control+K'; shown as keycaps\n- `select` { target, option } - a native <select>'s option by text or value\n- `drag` { target, at?, to: { target?, at? } } - sliders, drag and drop, panning\n- `scroll` { target?, by?: [x, y] } - into view, or by pixels\n- `waitFor` { target, gone?, timeout? } - until it shows (or goes): after what loads\n\nPresentation (shown until the step ends, or `for` ms; `clear` takes all down):\n- `spotlight` { target, text?, padding? } - dims everything else: the one thing to look at\n- `ring` { target, text?, color?, shape?: 'box' | 'circle' } - a pulsing outline\n- `arrow` { target, text?, from?: 'top' | 'right' | 'bottom' | 'left' } - points at it\n- `callout` { text, target?, side?, corner? } - a note by the target, or in a corner\n- `blur` { target } - hides names, addresses, anything private\n- `card` { title, text? } - full screen: an opening title, a chapter, the end\n- `zoom` { target, scale? } - magnifies the page around it (1.8 by default)\n- `clear`\n\nThe app may add its own actions (a map's `view`, `mapClick`): `validate` lists every kind it knows\nwhen one is wrong; read the app's demos (`demoEngine.get(id)`) for examples.\n\nStep options: `title` (for the editor), `hold` (ms after), `pause: true` (waits for the presenter),\n`notes` (on the presenter's screen only: what to add live, figures to mention, questions to expect).\n\n`cleanup`: actions done after the demo - when it ends or is stopped - quickly and unseen, so the app\nis as it found it and the demo plays again: clear filters and searches, close what was opened, go\nback to the first tab. What the app cannot undo through its UI, its start resets. A cleanup target\nnot there within half a second is skipped, so list every reset that might be needed.\n\n## Good demos\n\n- Open with a `card` (title, one line of promise), close with one (what was shown, what next).\n- Direct the eye: a spotlight or ring on what the sentence is about, an arrow for small things.\n- Let the viewer see results: a `wait` of 1500-3000 ms after what changes a lot; `waitFor` what loads.\n- Keep the pointer purposeful: no clicks that do not move the story.\n- Blur personal data.\n- Leave the app as it started: a `cleanup` list undoes what the steps changed, so demos run one\n after another and again. Check that too: `check` runs the cleanup, then `check` again.\n\n## Tools\n\nhelp() \u00B7 languages() \u00B7 start() \u00B7 page({ within?, query?, limit? }) \u00B7 find(target) \u00B7\ndescribe(css | [x, y]) \u00B7 try(action) \u00B7 preview(presentationAction, ms?) \u00B7 demos() \u00B7 get(id) \u00B7\nvalidate(demo) \u00B7 estimate(demoOrId) \u00B7 check(demoOrId, { from?, to?, animations? }) \u00B7 save(demo) \u00B7 remove(id) \u00B7\nopen(demoOrId) \u00B7 play(demoOrId, { from? }) \u00B7 guide(demoOrId, { from? }) \u00B7 loop([demoOrId]) \u00B7\nstopLoop() \u00B7 stop() \u00B7 state() \u00B7 link(demoOrId)\n";
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: `await`\neach call (most return a Promise); every result is plain data. A demo is steps; each step's narration is spoken (and subtitled) a sentence at\na time while its actions play one after the other. Actions point at elements as a person would: by\nwhat they show, not where they are.\n\n## Workflow\n\n1. `demoEngine.languages()` - which languages to write narration in.\n `demoEngine.start()` - where the app is; a demo starts there. `demoEngine.demos()` - what exists.\n2. Explore. `demoEngine.page()` lists what can be acted on, each with a ready `target`, its label,\n state and box; `page({ query: 'save' })` or `page({ within: '[data-demo=\"filters\"]' })` narrows it.\n Look with screenshots too. `demoEngine.try({ do: 'click', target })` does one action now and says\n what appeared and went: walk the app this way to learn the path the demo will take.\n3. Plan the story before the actions: what should the viewer understand at the end? One idea per step.\n4. Write the demo (format below). Narration first, then the actions that show it.\n5. `demoEngine.validate(demo)` - its shape. Then `await demoEngine.check(demo)` - from the demo's\n start, fast and silent, going past what fails, its cleanup after; fix every failure and check\n again until `ok` twice in a row (the second run proves the cleanup). The page's CSS transitions\n and animations are off while it runs, so it works in a background tab too. After a failure, what\n follows is waited for 2 s only (it mostly failed with it): fix the first failure first.\n6. `await demoEngine.save(demo)`, then `demoEngine.open(demo.id)` where the person watches your\n browser - they see it in the studio, can play, tune, film and share it (else see below). `demoEngine.play(id)` plays it with sound once the\n person clicks. `demoEngine.estimate(demo)` gives its length.\n\n## Your browser and the person's\n\nWhat `save` keeps stays in the browser you work in. Not the person's own (a browser of yours,\nanother profile)? Give them `await demoEngine.link(id)`: opened in their browser, the demo is kept\nthere and opens in their studio. Where you can write files, `await demoEngine.get(id)` is its\n`.demo.json` as well (the library's New \u2192 Import takes it). A demo of theirs comes to you the same\nway: open its link, or `save(link)`, and it is kept in yours. Signing in to the app is theirs: ask.\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\": \"[data-demo=\\\"orders\\\"]\" }, \"text\": { \"en\": \"Orders\", \"de\": \"Auftr\u00E4ge\" }, \"for\": 2500 },\n { \"do\": \"type\", \"target\": { \"css\": \"input[type=\\\"search\\\"]\" }, \"text\": \"Berlin\", \"cue\": 1 },\n { \"do\": \"click\", \"target\": { \"css\": \"td\", \"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' }`. A label is the element's whole text, or its\n`data-demo` name, or its `aria-label` - never a part: a table row's is all its cells, which change\nwith the data and the language (\"open\", \"offen\"). Target what stays: a cell, a `key`, a named region.\n\nEvery action has `wait` (ms before it, default 800) and `cue` (start with the step's sentence of that\nindex, 0-based: sentences end with . ? or !; syncs a click with the words about it, in every\nlanguage 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). Their text on the\nscreen - a card's title and text, a note, a label - is one for every language, or one per language\nas `say` is: `{ \"en\": \"Orders\", \"de\": \"Auftr\u00E4ge\" }`.\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; for its step only: blur again first\n thing in each step it shows in (`wait: 0`)\n- `card` { title, text? } - full screen: an opening title, a chapter, the end\n- `zoom` { target, scale? } - magnifies the page around it (1.8 by default)\n- `clear`\n\nThe app may add its own actions (a map's `view`, `mapClick`): `validate` lists every kind it knows\nwhen one is wrong; read the app's demos (`demoEngine.get(id)`) for examples.\n\nStep options: `title` (for the editor), `hold` (ms after), `pause: true` (waits for the presenter),\n`notes` (on the presenter's screen only: what to add live, figures to mention, questions to expect).\n\n`cleanup`: actions done after the demo - when it ends or is stopped - quickly and unseen, so the app\nis as it found it and the demo plays again: clear filters and searches, close what was opened, go\nback to the first tab. What the app cannot undo through its UI, its start resets. A cleanup target\nnot there within half a second is skipped, so list every reset that might be needed.\n\n## Good demos\n\n- Open with a `card` (title, one line of promise), close with one (what was shown, what next).\n- Direct the eye: a spotlight or ring on what the sentence is about, an arrow for small things.\n- Let the viewer see results: a `wait` of 1500-3000 ms after what changes a lot; `waitFor` what loads.\n- Keep the pointer purposeful: no clicks that do not move the story.\n- Blur personal data.\n- Leave the app as it started: a `cleanup` list undoes what the steps changed, so demos run one\n after another and again. Check that too: `check` runs the cleanup, then `check` again.\n\n## Tools\n\nhelp() \u00B7 languages() \u00B7 start() \u00B7 page({ within?, query?, limit? }) \u00B7 find(target) \u00B7\ndescribe(css | [x, y]) \u00B7 try(action) \u00B7 preview(presentationAction, ms?) \u00B7 demos() \u00B7 get(id) \u00B7\nvalidate(demo) \u00B7 estimate(demoOrId) \u00B7 check(demoOrId, { from?, to?, animations? }) \u00B7 save(demo | link) \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). The page\'s CSS transitions\n and animations are off while it runs, so it works in a background tab too.\n6. `await demoEngine.save(demo)`, then `demoEngine.open(demo.id)` - the person sees it in the\n studio, can play, tune, film and share it. `demoEngine.play(id)` plays it with sound once the\n person clicks. `demoEngine.estimate(demo)` gives its length.\n\n## Length\n\n- Short (a teaser, one feature): 4-7 steps, 30-60 s, one or two sentences a step.\n- Normal (a tour): 8-12 steps, 1-3 min.\n- Detailed (a deep dive): 12-25 steps, 3-6 min; still one idea per step.\n\n## What it is for\n\n- Marketing video: short, benefit first, a `card` to open and close, zooms on what impresses; no\n setup steps on screen. The person films it (film button); music can play under it.\n- Sales pitch: one step per point the presenter makes; `pause: true` on steps where they talk\n freely. They advance with a clicker (PageDown) and repeat with PageUp.\n- Expo booth: 30-90 s, readable without sound (subtitles carry it), ends where it started so it can\n loop. `demoEngine.loop([ids])` plays them unattended; a visitor\'s touch hands the app over.\n- Tutorial or training: `demoEngine.guide(id)` lets the viewer do each click and entry themselves,\n ringed with what to do. Narrate why, not only what; small steps; one new thing each.\n\n## Narration\n\n- For the viewer, about what matters to them: "Which pipes need work first?" before "Click Risk".\n- Present tense, plain words, at most ~20 words a sentence; a step ~1-3 sentences.\n- Say what to look at as it happens; name things as the app names them.\n- Every language of `languages().write`: `say: { en: \'…\', de: \'…\' }`. Same meaning, natural in each.\n- No "In this demo…" filler; open with the question or the benefit, close with what was shown.\n\n## Format\n\n```json\n{\n "id": "orders-tour",\n "title": "Orders, from list to invoice",\n "description": "One sentence: who it is for and what it shows.",\n "start": { "…": "as demoEngine.start() gives it, or leave out" },\n "steps": [\n {\n "title": "Find an order",\n "say": { "en": "Every order lands here, newest first. Let\'s find one from Berlin." },\n "actions": [\n { "do": "spotlight", "target": { "css": "table", "text": "orders" }, "for": 2500 },\n { "do": "type", "target": { "css": "input[type=\\"search\\"]" }, "text": "Berlin", "cue": 1 },\n { "do": "click", "target": { "css": "tr", "text": "berlin #" }, "wait": 1200 }\n ]\n }\n ]\n}\n```\n\nA target: `{ css, text?, key?, index? }` - the `index`th (0-based) element matching `css` whose label\nis `text` (or the app\'s locale `key`\'s text: works in every language). Labels compare without case,\nspacing, and with every number as "#": a row "Berlin 42" is "berlin #". Use the targets `page()` and\n`describe()` give: they prefer locale keys and named regions. Avoid `index` where a scope does it:\n`{ css: \'[data-demo="filters"] button\', text: \'apply\' }`.\n\nEvery action has `wait` (ms before it, default 800) and `cue` (start with the step\'s sentence of that\nindex, 0-based: syncs a click with the words about it, in every language and voice).\n\nInteractions:\n- `click` { target, at?: [x, y] fractions of the box, double?, right?, shift?, ctrl?, alt?, meta? }\n- `hover` { target, at? } - shows tooltips and hover cards (not CSS :hover looks)\n- `type` { target, text } - replaces the field\'s text, a letter at a time\n- `key` { key, target? } - \'Escape\', \'Enter\', \'ArrowDown\', \'Control+K\'; shown as keycaps\n- `select` { target, option } - a native <select>\'s option by text or value\n- `drag` { target, at?, to: { target?, at? } } - sliders, drag and drop, panning\n- `scroll` { target?, by?: [x, y] } - into view, or by pixels\n- `waitFor` { target, gone?, timeout? } - until it shows (or goes): after what loads\n\nPresentation (shown until the step ends, or `for` ms; `clear` takes all down):\n- `spotlight` { target, text?, padding? } - dims everything else: the one thing to look at\n- `ring` { target, text?, color?, shape?: \'box\' | \'circle\' } - a pulsing outline\n- `arrow` { target, text?, from?: \'top\' | \'right\' | \'bottom\' | \'left\' } - points at it\n- `callout` { text, target?, side?, corner? } - a note by the target, or in a corner\n- `blur` { target } - hides names, addresses, anything private\n- `card` { title, text? } - full screen: an opening title, a chapter, the end\n- `zoom` { target, scale? } - magnifies the page around it (1.8 by default)\n- `clear`\n\nThe app may add its own actions (a map\'s `view`, `mapClick`): `validate` lists every kind it knows\nwhen one is wrong; read the app\'s demos (`demoEngine.get(id)`) for examples.\n\nStep options: `title` (for the editor), `hold` (ms after), `pause: true` (waits for the presenter),\n`notes` (on the presenter\'s screen only: what to add live, figures to mention, questions to expect).\n\n`cleanup`: actions done after the demo - when it ends or is stopped - quickly and unseen, so the app\nis as it found it and the demo plays again: clear filters and searches, close what was opened, go\nback to the first tab. What the app cannot undo through its UI, its start resets. A cleanup target\nnot there within half a second is skipped, so list every reset that might be needed.\n\n## Good demos\n\n- Open with a `card` (title, one line of promise), close with one (what was shown, what next).\n- Direct the eye: a spotlight or ring on what the sentence is about, an arrow for small things.\n- Let the viewer see results: a `wait` of 1500-3000 ms after what changes a lot; `waitFor` what loads.\n- Keep the pointer purposeful: no clicks that do not move the story.\n- Blur personal data.\n- Leave the app as it started: a `cleanup` list undoes what the steps changed, so demos run one\n after another and again. Check that too: `check` runs the cleanup, then `check` again.\n\n## Tools\n\nhelp() · languages() · start() · page({ within?, query?, limit? }) · find(target) ·\ndescribe(css | [x, y]) · try(action) · preview(presentationAction, ms?) · demos() · get(id) ·\nvalidate(demo) · estimate(demoOrId) · check(demoOrId, { from?, to?, animations? }) · save(demo) · remove(id) ·\nopen(demoOrId) · play(demoOrId, { from? }) · guide(demoOrId, { from? }) · loop([demoOrId]) ·\nstopLoop() · stop() · state() · link(demoOrId)\n';
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: `await`\neach call (most return a Promise); every result is plain data. A demo is steps; each step\'s narration is spoken (and subtitled) a sentence at\na time while its actions play one after the other. Actions point at elements as a person would: by\nwhat they show, not where they are.\n\n## Workflow\n\n1. `demoEngine.languages()` - which languages to write narration in.\n `demoEngine.start()` - where the app is; a demo starts there. `demoEngine.demos()` - what exists.\n2. Explore. `demoEngine.page()` lists what can be acted on, each with a ready `target`, its label,\n state and box; `page({ query: \'save\' })` or `page({ within: \'[data-demo="filters"]\' })` narrows it.\n Look with screenshots too. `demoEngine.try({ do: \'click\', target })` does one action now and says\n what appeared and went: walk the app this way to learn the path the demo will take.\n3. Plan the story before the actions: what should the viewer understand at the end? One idea per step.\n4. Write the demo (format below). Narration first, then the actions that show it.\n5. `demoEngine.validate(demo)` - its shape. Then `await demoEngine.check(demo)` - from the demo\'s\n start, fast and silent, going past what fails, its cleanup after; fix every failure and check\n again until `ok` twice in a row (the second run proves the cleanup). The page\'s CSS transitions\n and animations are off while it runs, so it works in a background tab too. After a failure, what\n follows is waited for 2 s only (it mostly failed with it): fix the first failure first.\n6. `await demoEngine.save(demo)`, then `demoEngine.open(demo.id)` where the person watches your\n browser - they see it in the studio, can play, tune, film and share it (else see below). `demoEngine.play(id)` plays it with sound once the\n person clicks. `demoEngine.estimate(demo)` gives its length.\n\n## Your browser and the person\'s\n\nWhat `save` keeps stays in the browser you work in. Not the person\'s own (a browser of yours,\nanother profile)? Give them `await demoEngine.link(id)`: opened in their browser, the demo is kept\nthere and opens in their studio. Where you can write files, `await demoEngine.get(id)` is its\n`.demo.json` as well (the library\'s New → Import takes it). A demo of theirs comes to you the same\nway: open its link, or `save(link)`, and it is kept in yours. Signing in to the app is theirs: ask.\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": "[data-demo=\\"orders\\"]" }, "text": { "en": "Orders", "de": "Aufträge" }, "for": 2500 },\n { "do": "type", "target": { "css": "input[type=\\"search\\"]" }, "text": "Berlin", "cue": 1 },\n { "do": "click", "target": { "css": "td", "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\' }`. A label is the element\'s whole text, or its\n`data-demo` name, or its `aria-label` - never a part: a table row\'s is all its cells, which change\nwith the data and the language ("open", "offen"). Target what stays: a cell, a `key`, a named region.\n\nEvery action has `wait` (ms before it, default 800) and `cue` (start with the step\'s sentence of that\nindex, 0-based: sentences end with . ? or !; syncs a click with the words about it, in every\nlanguage 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). Their text on the\nscreen - a card\'s title and text, a note, a label - is one for every language, or one per language\nas `say` is: `{ "en": "Orders", "de": "Aufträge" }`.\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; for its step only: blur again first\n thing in each step it shows in (`wait: 0`)\n- `card` { title, text? } - full screen: an opening title, a chapter, the end\n- `zoom` { target, scale? } - magnifies the page around it (1.8 by default)\n- `clear`\n\nThe app may add its own actions (a map\'s `view`, `mapClick`): `validate` lists every kind it knows\nwhen one is wrong; read the app\'s demos (`demoEngine.get(id)`) for examples.\n\nStep options: `title` (for the editor), `hold` (ms after), `pause: true` (waits for the presenter),\n`notes` (on the presenter\'s screen only: what to add live, figures to mention, questions to expect).\n\n`cleanup`: actions done after the demo - when it ends or is stopped - quickly and unseen, so the app\nis as it found it and the demo plays again: clear filters and searches, close what was opened, go\nback to the first tab. What the app cannot undo through its UI, its start resets. A cleanup target\nnot there within half a second is skipped, so list every reset that might be needed.\n\n## Good demos\n\n- Open with a `card` (title, one line of promise), close with one (what was shown, what next).\n- Direct the eye: a spotlight or ring on what the sentence is about, an arrow for small things.\n- Let the viewer see results: a `wait` of 1500-3000 ms after what changes a lot; `waitFor` what loads.\n- Keep the pointer purposeful: no clicks that do not move the story.\n- Blur personal data.\n- Leave the app as it started: a `cleanup` list undoes what the steps changed, so demos run one\n after another and again. Check that too: `check` runs the cleanup, then `check` again.\n\n## Tools\n\nhelp() · languages() · start() · page({ within?, query?, limit? }) · find(target) ·\ndescribe(css | [x, y]) · try(action) · preview(presentationAction, ms?) · demos() · get(id) ·\nvalidate(demo) · estimate(demoOrId) · check(demoOrId, { from?, to?, animations? }) · save(demo | link) · remove(id) ·\nopen(demoOrId) · play(demoOrId, { from? }) · guide(demoOrId, { from? }) · loop([demoOrId]) ·\nstopLoop() · stop() · state() · link(demoOrId)\n';
@@ -47,11 +47,16 @@ export type DemoEngineOptions = {
47
47
  overlay?: OverlayOptions;
48
48
  /** The engine's UI: 'auto' follows the system. */
49
49
  theme?: 'light' | 'dark' | 'auto';
50
- /** Tools for an AI on `window[agent]`: 'demoEngine' by default; false for none. */
51
- agent?: string | false;
52
50
  /**
53
- * "Ask Claude": people make, clone and change demos in words, in the app, with their own
54
- * Anthropic API key (kept in their browser; the app needs no backend). On by default; false for none.
51
+ * Tools for an AI on `window[agent]`: 'demoEngine' by default; false for none. A function
52
+ * decides as the engine mounts, where the app knows more (its environment, who is signed in).
53
+ * With them, anyone with the app's URL and a Claude that runs JavaScript in a browser makes,
54
+ * clones and changes demos; the library copies them a prompt to start with.
55
+ */
56
+ agent?: string | false | (() => string | false);
57
+ /**
58
+ * Experimental, off: an "Ask Claude" panel in the library, where people make and change demos
59
+ * in words with their own Anthropic API key. True to show it.
55
60
  */
56
61
  assistant?: boolean;
57
62
  /** A "Demos" button on the page opening the library: for apps without a panel of their own. */
@@ -251,6 +256,16 @@ export declare class DemoEngine {
251
256
  destroy(): void;
252
257
  /** A demo a link brought, one asked for by `?demo=`, or one to play once back from its start's reload. */
253
258
  private arrived;
259
+ /** The demo in the address's `#demo=`, kept here and opened in the studio. False without one. */
260
+ private takeLink;
261
+ /** Where an AI finds the engine's tools, `window[name]`; undefined where the app keeps them off. */
262
+ agentName(): string | undefined;
263
+ /**
264
+ * What to tell one's own Claude - in a browser where it runs JavaScript - to make a demo of the
265
+ * app, or change `demo`: the app's address, where the tools are, how to hand the demo back.
266
+ * Undefined where the app keeps the tools off.
267
+ */
268
+ claudePrompt(demo?: Demo): Promise<string | undefined>;
254
269
  /**
255
270
  * While a demo plays, the viewer's own input does not reach the app: a click or a key of theirs
256
271
  * would take the demo off its path. Not the engine's controls, not a presenter's keys; not while
@@ -1 +1 @@
1
- import{copyOf as t,languagesOf as e,newDemo as s,sayOf as i,scenarioOf as o,sentences as n}from"../model/Demo.js";import{parseSubtitles as a,toSrt as r,toVtt as h}from"../model/Subtitles.js";import{actionTime as p,estimate as l}from"../model/Timing.js";import{parseDemo as d,validate as c}from"../model/Validate.js";import{Hand as m}from"../page/Input.js";import{Overlay as g}from"../page/Overlay.js";import{stillPage as u}from"../page/Still.js";import{Targets as y}from"../page/Targets.js";import{Speech as f}from"../speech/Speech.js";import{narrationFor as w,transcribe as v}from"../speech/Transcribe.js";import{Store as k}from"../store/Store.js";import{demoFromLink as S,download as b,fileName as P,linkTo as T,shareFiles as x}from"../store/Share.js";import{extensionOf as E,recordMicrophone as R,startFilming as j,videoSize as $}from"../video/Film.js";import{renderMusic as M}from"../speech/Music.js";import{readPack as L,writePack as K}from"../speech/Pack.js";import{Player as N}from"./Player.js";import{Recorder as B}from"./Recorder.js";import{readAction as D}from"./Read.js";import{mountUI as A}from"../ui/EngineUI.js";import{agentTools as I}from"../agent/Agent.js";import{Assistant as O,EMPTY_ASSISTANT as F}from"../agent/Assistant.js";import{openPresenter as C}from"../ui/Presenter.js";import{DEFAULT_RELAY as J,qrSvg as U,RemoteLink as z}from"../remote/Remote.js";import{DEFAULT_SETTINGS as V,loadSettings as Q,saveSettings as H}from"./Settings.js";const G=["pointerdown","pointerup","pointermove","pointerover","pointerout","mousedown","mouseup","mousemove","mouseover","mouseout","click","dblclick","contextmenu","wheel","touchstart","touchmove","touchend","keydown","keyup","keypress"];export class DemoEngine{constructor(t){this.options=t,this.listeners=new Set,this.packs=new Map,this.remoteSent="",this.remoteTimer=0,this.getState=()=>this.state,this.subscribe=t=>(this.listeners.add(t),()=>this.listeners.delete(t)),this.hintTimer=0,this.targets=new y({...t.targets,labels:t.labels}),this.overlay=new g(t.overlay),this.hand=new m(this.overlay.cursor,()=>this.player?.speedNow??1),this.settingsKey=`protomaze-demo-engine:${t.app}:settings`,this.state={session:{mode:"idle"},settings:Q(this.settingsKey),speech:{},assistant:F},this.assistant=new O(this,()=>this.state.settings.claude,t=>this.set({assistant:t})),this.speech=new f(()=>this.state.settings.speech,()=>this.set({speech:{...this.speech.state}})),this.store=new k(`protomaze-demo-engine:${t.app}`),this.store.subscribe(()=>this.emit()),this.plugins=t.plugins??[]}emit(){this.state={...this.state},this.listeners.forEach(t=>t()),this.toRemote()}set(t){this.state={...this.state,...t},this.listeners.forEach(t=>t()),this.toRemote()}setSession(t){this.set({session:t})}updateSession(t,e){this.state.session.mode===t&&this.setSession({...this.state.session,...e})}say(t,e=!1){this.set({message:t?{text:t,error:e}:void 0})}changeSettings(t){const e={...this.state.settings,...t};H(this.settingsKey,e),this.set({settings:e}),t.music?.on&&this.loadMusic().catch(()=>{})}language(){const t=this.state.settings.language;return"page"!==t?t:this.options.language?.()??this.options.languages?.[0]??(navigator.language.split("-")[0]||"en")}languages(){return this.options.languages??[this.language()]}pluginKinds(){return this.plugins.flatMap(t=>Object.keys(t.actions??{}))}pluginAction(t){return this.plugins.map(e=>e.actions?.[t]).find(Boolean)}read(t,e){return D(t,this.options.labels,this.plugins,e)}async mount(){if(this.unmount)return;this.overlay.mount();const t=A(this),e=t=>this.key(t);window.addEventListener("keydown",e,!0);const s=t=>this.gate(t);G.forEach(t=>window.addEventListener(t,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=()=>{t(),window.removeEventListener("keydown",e,!0),G.forEach(t=>window.removeEventListener(t,s,{capture:!0})),i&&delete window[i],this.overlay.unmount()},await this.arrived()}destroy(){this.closeRemote(),this.stopLoop(),this.stop(),this.unmount?.(),this.unmount=void 0}async arrived(){const t=sessionStorage.getItem(this.pendingKey());if(sessionStorage.removeItem(this.pendingKey()),t){const{demo:e,verb:s,from:i,loop:o}=JSON.parse(t);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(e.title,"film"===s?"Film":"Play",()=>"film"===s?this.film(e):this.play(e,{from:i}),!0)}const e=await S();if(e){const t=c(e,this.pluginKinds());return t.length?this.say(`The link's demo: ${t[0].path} ${t[0].message}`,!0):(await this.save(e),this.say(`"${e.title}" came with the link: it is kept here.`),this.openStudio(e))}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 t=(await this.entries()).find(t=>t.demo.id===i);t&&this.whenClicked(t.demo.title,"Play",()=>this.play(t.demo),!0)}}gate(t){const e=this.state.session;if(!t.isTrusted||"playing"!==e.mode||e.paused||e.looping)return;const s=t.composedPath();if(s.includes(this.overlay.host))return;if(e.guided&&e.instruction){const i=e.player.viewerTarget();if(i&&(s.includes(i)||t instanceof KeyboardEvent&&i.contains(document.activeElement)))return;if(!i&&t instanceof KeyboardEvent)return}const i=t.defaultPrevented;t.cancelable&&t.preventDefault(),t.stopImmediatePropagation(),i||"pointerdown"!==t.type&&"keydown"!==t.type&&"wheel"!==t.type||this.hint(e.guided?'Only the ringed part now: or "Do it for me"':"Playing: Space pauses, and the app is yours then. Esc stops.")}hint(t){window.clearTimeout(this.hintTimer),this.set({hint:t}),this.hintTimer=window.setTimeout(()=>this.set({hint:void 0}),3e3)}pendingKey(){return`protomaze-demo-engine:${this.options.app}:pending`}key(t){if(!t.isTrusted)return;const e=t.composedPath(),s=e.some(t=>t instanceof HTMLElement&&(t.isContentEditable||t.matches("input, textarea, select"))),i=e.includes(this.overlay.host),o=this.state.session,n=()=>{t.preventDefault(),t.stopPropagation()};if("ready"!==o.mode)if("recording"!==o.mode){if("l"===t.key.toLowerCase()&&t.ctrlKey&&t.shiftKey&&this.looping)return n(),this.stopLoop();if(!("playing"!==o.mode||o.looping||o.checking||s&&(i||o.guided&&o.instruction))){if("Escape"===t.key)this.stop();else if(" "===t.key||"b"===t.key||"."===t.key)this.togglePause();else if("ArrowRight"===t.key||"Enter"===t.key||"PageDown"===t.key)o.player.next();else if("ArrowLeft"===t.key||"PageUp"===t.key)o.player.back();else if("Home"===t.key)o.player.goTo(0);else if("End"===t.key)o.player.goTo(o.steps-1);else{if(!/^[1-9]$/.test(t.key)||t.ctrlKey||t.metaKey||t.altKey)return;o.player.goTo(Number(t.key)-1)}n()}}else"Escape"!==t.key||s||(n(),this.stopRecording?.());else"Escape"===t.key&&(n(),o.cancel())}async entries(){return await this.store.ready(),this.entriesNow()}entriesNow(){const{demos:t,videos:e}=this.store.get(),s=new Map(t.map(t=>[t.id,t])),i=this.language(),n=(this.options.demos??[]).map(t=>"demo"in t?t:{demo:t,scenario:void 0});return[...n.map(({demo:t,scenario:n})=>{const a=s.get(t.id);return a?{demo:a,scenario:a.scenario??n??o(a,i),origin:"edited",video:e.get(t.id)}:{demo:t,scenario:n??o(t,i),origin:"app",video:e.get(t.id)}}),...t.filter(t=>!n.some(e=>e.demo.id===t.id)).map(t=>({demo:t,scenario:t.scenario??o(t,i),origin:"here",video:e.get(t.id)}))]}async save(e){const s=c(e,this.pluginKinds());if(s.length)throw new Error(`Not a demo: ${s.map(t=>`${t.path} ${t.message}`).join("; ")}`);await this.store.saveDemo(t(e))}async remove(t){await this.store.deleteDemo(t),this.state.studio?.demo.id===t&&this.closeStudio()}parse(t){return d(t,this.pluginKinds())}create(t){return s(t,this.options.start?.current())}openStudio(e){this.set({studio:{demo:t(e),opened:Date.now()}})}closeStudio(){this.set({studio:void 0})}activated(){const t=navigator.userActivation;return!t||t.isActive}whenClicked(t,e,s,i=!1){const o=()=>{this.setSession({mode:"idle"}),this.speech.wake(),s().catch(t=>this.say(t.message,!0))};if(!i&&this.activated())return o();this.setSession({mode:"ready",title:t,verb:e,go:o,cancel:()=>this.setSession({mode:"idle"})})}async goToStart(t,e,s,i){if(!t.start||!this.options.start)return!0;sessionStorage.setItem(this.pendingKey(),JSON.stringify({demo:t,verb:e,from:s,loop:i}));return"reload"!==await this.options.start.go(t.start)&&(sessionStorage.removeItem(this.pendingKey()),!0)}busy(){return"idle"!==this.state.session.mode&&"ready"!==this.state.session.mode}play(t,e={}){return new Promise(s=>this.whenClicked(t.title,"Play",async()=>{if(this.busy())return s(void 0);if(this.say(void 0),!await this.goToStart(t,"play",e.from))return s(void 0);const i=await this.run(t,e);s(i)}))}async run(t,e={}){const{settings:s}=this.state,i=e.language??this.language(),o=s.music.on&&!e.checking&&!e.guided&&await Promise.race([this.loadMusic(),new Promise(t=>setTimeout(()=>t(!1),e.filming?6e4:1500))]);this.speech.setPack(s.usePacks?await this.pack(t):void 0);const n=new N(t,{language:i,subtitles:s.subtitles,waitForPresenter:s.waitForPresenter&&!e.looping,catchUp:s.catchUp,music:Boolean(o),...e},{hand:this.hand,targets:this.targets,overlay:this.overlay,speech:this.speech,plugins:this.plugins,ready:this.options.ready,read:(t,e)=>this.read(t,e),reset:async()=>!t.start||!this.options.start||"reload"!==await this.options.start.go(t.start),update:t=>this.updateSession("playing",t)});this.setSession({mode:"playing",title:t.title,demo:t,steps:t.steps.length,filming:Boolean(e.filming),checking:Boolean(e.checking),guided:Boolean(e.guided),looping:Boolean(e.looping),presenting:Boolean(e.presenting),player:n,step:e.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"}),e.checking||a.navigated||(this.set({lastRun:{json:JSON.stringify(t),language:i,timing:a.timing}}),a.error&&"Stopped."!==a.error&&this.say(a.error,!0)),a}stop(){const t=this.state.session;"playing"===t.mode&&t.player.stop(),"recording"===t.mode&&this.stopRecording?.(),"ready"!==t.mode&&"preparing"!==t.mode||this.setSession({mode:"idle"})}togglePause(){const t=this.state.session;"playing"===t.mode&&(t.paused?t.player.resume():t.player.pause())}resume(){const t=this.state.session;"playing"===t.mode&&t.player.resume()}next(){const t=this.state.session;"playing"===t.mode&&t.player.next()}back(){const t=this.state.session;"playing"===t.mode&&t.player.back()}openPresenter(t={}){return C(this,t)}presenterKey(t){this.key(t)}present(t,e={}){this.openDialog({kind:"present",demo:t,from:e.from})}openDialog(t){this.set({dialog:t,...this.state.library&&this.options.launcher?{library:void 0}:{}})}closeDialog(){this.set({dialog:void 0})}openSettings(){this.set({library:"settings"})}showLibrary(t){this.set({library:t})}openAssistant(t){!1!==this.options.assistant&&this.assistant.open(t)}goTo(t){const e=this.state.session;return"playing"===e.mode&&e.player.goTo(t)}guide(t,e={}){return this.play(t,{...e,guided:!0})}doItForMe(){const t=this.state.session;"playing"===t.mode&&t.player.doItForMe()}async openRemote(){if(!1===this.options.remote)throw new Error("No phone remote in this app");if(this.state.remote)return this.state.remote;const t=this.options.remote?.relay??J;this.remoteLink=await z.open(t,{command:t=>this.fromRemote(t),hello:()=>this.remoteSent="",peers:t=>this.state.remote&&this.set({remote:{...this.state.remote,peers:t}})});const e={url:this.remoteLink.url,svg:U(this.remoteLink.url),peers:0};return this.set({remote:e}),this.remoteTimer=window.setInterval(()=>this.toRemote(!0),1e3),e}closeRemote(){window.clearInterval(this.remoteTimer),this.remoteLink?.close(),this.remoteLink=void 0,this.remoteSent="",this.set({remote:void 0})}fromRemote(t){const e=this.state.session;"playing"===e.mode&&("next"===t.do?e.player.next():"back"===t.do?e.player.back():"goto"===t.do&&void 0!==t.step?e.player.goTo(t.step):"stop"===t.do?this.stop():"toggle"===t.do&&(e.waiting?e.player.next():this.togglePause()))}toRemote(t=!1){if(!this.remoteLink)return;const e=this.remoteState(),{at:s,elapsed:i,stepElapsed:o,...n}=e,a=JSON.stringify(n);(a!==this.remoteSent||t&&e.playing)&&(this.remoteSent=a,this.remoteLink.send(e))}remoteState(){const t=this.state.session,e=Date.now();if("playing"!==t.mode||t.checking)return{playing:!1,title:"",steps:[],step:0,caption:"",paused:!1,waiting:!1,filming:!1,elapsed:0,stepElapsed:0,planned:0,at:e};const s=this.language(),o=this.timing(t.demo,s),a=o.steps.find(e=>e.step===t.step),r=t.player.elapsed();return{playing:!0,title:t.demo.title,steps:t.demo.steps.map((t,e)=>({title:t.title??`Step ${e+1}`,script:n(i(t,s)),...t.notes?{notes:t.notes}:{}})),step:t.step,caption:t.caption,paused:t.paused,waiting:t.waiting,filming:t.filming,elapsed:r,stepElapsed:r-t.player.stepStartedAt,planned:o.duration,...a?{plannedStep:a.end-a.start}:{},at:e}}pack(t){let e=this.packs.get(t.id);return e||(e=(async()=>{const e=await this.store.asset(`narration:${t.id}`);if(e)return L(await e.arrayBuffer());const s=this.options.narration?.(t);if(!s)return;const i=await fetch(s);return i.ok?L(await i.arrayBuffer()):void 0})().catch(()=>{}),this.packs.set(t.id,e)),e}async makePack(t,s=()=>{}){const i=await this.pack(t);this.speech.setPack(i);const o=e(t).flatMap(e=>t.steps.flatMap(t=>n(t.say[e]??"").map(t=>({language:e,text:t})))),a=o.filter((t,e)=>o.findIndex(e=>e.language===t.language&&e.text===t.text)===e),r=[];for(const t of a)s(r.length,a.length),r.push({...await this.speech.packable(t.text,t.language),...t});s(r.length,a.length);const h=K(t.id,r);return await this.store.saveAsset(`narration:${t.id}`,h),this.packs.delete(t.id),h}async downloadPack(t){try{const e=await this.makePack(t,(t,e)=>this.say(`Making the narration pack: ${t} / ${e}`));b(e,`${t.id}.narration.zip`),this.say(`Narration pack: ${Math.round(e.size/1e5)/10} MB, kept here too. Check it in beside ${t.id}.demo.json, for every viewer.`)}catch(t){this.say(`Narration pack: ${t.message}`,!0)}}async dropPack(t){await this.store.saveAsset(`narration:${t.id}`,void 0),this.packs.delete(t.id)}async setMusic(t){await this.store.saveAsset("music",t),this.musicLoaded=void 0;const{music:e}=this.state.settings;this.changeSettings({music:t?{...e,on:!0,track:"file",name:t.name??"music"}:{...e,track:"calm",name:void 0}})}async loadMusic(){const{music:t}=this.state.settings,e="file"===t.track?`file:${t.name}`:t.track;if(this.musicLoaded!==e){if("file"===t.track){const e=await this.store.asset("music");if(!e)return!1;await this.speech.setMusic(e,t.volume).catch(()=>{})}else this.speech.setMusicBuffer(await M(t.track),t.volume);this.musicLoaded=e}return this.speech.setMusicVolume(t.volume),this.speech.hasMusic}async listenToMusic(t=20){if(this.speech.wake(),!await this.loadMusic())return()=>{};this.speech.startMusic();const e=setTimeout(()=>this.speech.stopMusic(),1e3*t);return()=>{clearTimeout(e),this.speech.stopMusic(.6)}}async loop(t,e={},s=0){if(0===t.length)return;this.stopLoop();let i=!1,o=0,n=s;const a=e.idle??this.state.settings.loopIdle,r=e.gap??1500,h=t.map(t=>t.title),p=t=>{if(!t.isTrusted||t.composedPath().includes(this.overlay.host))return;o=performance.now();const e=this.state.session;"playing"===e.mode&&e.looping&&e.player.stop(!0)},l=["pointerdown","keydown","wheel","touchstart"];l.forEach(t=>window.addEventListener(t,p,{capture:!0,passive:!0}));this.looping={demos:t,options:e,stop:()=>{i=!0,l.forEach(t=>window.removeEventListener(t,p,{capture:!0}));const t=this.state.session;"playing"===t.mode&&t.looping&&t.player.stop(),this.set({loop:void 0})}};const d=t=>new Promise(e=>setTimeout(e,t));for(;!i;){const s=t[n%t.length];this.set({loop:{titles:h,index:n%t.length,visitor:!1}});if(!await this.goToStart(s,"loop",void 0,{demos:t,index:n%t.length,gap:e.gap,idle:e.idle,reload:"reload"===e.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%t.length,visitor:!0,resumesAt:Date.now()+a-(performance.now()-o)}}),await d(1e3);if(i)break;if("reload"===e.reset)return sessionStorage.setItem(this.pendingKey(),JSON.stringify({demo:s,verb:"loop",loop:{demos:t,index:n%t.length,gap:e.gap,idle:e.idle,reload:!0}})),window.location.reload();await(e.reset?.())}else n++,await d(r)}}stopLoop(){this.looping?.stop(),this.looping=void 0}elapsed(){const t=this.state.session;return"playing"===t.mode?t.player.elapsed():void 0}async check(t,e={}){const s=c(t,this.pluginKinds());if(s.length)return{ok:!1,problems:s,failures:[],duration:0,error:"Not a valid demo"};if(this.busy())return{ok:!1,problems:s,failures:[],duration:0,error:`Busy: ${this.state.session.mode}`};const{animations:i,fromStart:o,...n}=e,a=i?()=>{}:u();try{if(!1!==o&&t.start&&this.options.start){if("reload"===await this.options.start.go(t.start))return{ok:!1,problems:s,failures:[],duration:0,error:"Its start reloads the page: check again once it is back"}}const e=await this.run(t,{...n,speed:n.speed??8,keepGoing:!0,checking:!0,catchUp:!0,subtitles:!1}),i=e.failures.map(e=>({...e,action:t.steps[e.step].actions[e.index]}));return{ok:!e.error&&0===i.length,error:e.error,failures:i,problems:s,duration:e.timing.duration}}finally{a()}}timing(t,e=this.language()){const s=this.state.lastRun;return s&&s.language===e&&s.json===JSON.stringify(t)&&s.timing.steps.length===t.steps.length?s.timing:l(t,{language:e,sayTime:t=>this.speech.duration(t,e),actionTime:t=>{const e=this.pluginAction(t.do);return e?.duration?.(t)??p(t)}})}film(t,e={}){return new Promise(s=>this.whenClicked(t.title,"Film",async()=>this.busy()?s(void 0):(this.say(void 0),await this.goToStart(t,"film")?void s(await this.filmNow(t,e)):s(void 0))))}async filmNow(t,e){const s=e.language??this.language();let o=!1;const a=await j({soundtrack:this.speech.soundtrack(),microphone:e.microphone,crop:this.options.filmElement?.(),...this.filmQuality(),onEnded:()=>{o=!0,this.stop()}});let r;try{const e=t.steps.flatMap(t=>n(i(t,s)));this.setSession({mode:"preparing",title:t.title,text:"Preparing the narration"}),await this.speech.prepare(e,s,(t,e)=>this.updateSession("preparing",{text:`Preparing the narration: ${t} / ${e}`})),o||"preparing"!==this.state.session.mode||(r=await this.run(t,{language:s,filming:a}))}finally{"preparing"===this.state.session.mode&&this.setSession({mode:"idle"})}const{video:p,voice:l}=await a.stop();if(!r||r.error)return void this.say("Stopped."!==r?.error&&r?`Filming failed: ${r.error}`:"Filming stopped: nothing kept.",Boolean(r?.error&&"Stopped."!==r.error));let d=r.timing.cues;l&&"off"===this.state.settings.speech.voice&&(this.setSession({mode:"preparing",title:t.title,text:"Transcribing what was said"}),d=await this.transcribe(l,s).catch(()=>d),this.setSession({mode:"idle"}));const c={id:t.id,blob:p,at:Date.now(),json:JSON.stringify(t),vtt:h(d),timing:r.timing,language:s,look:this.look(s),...l?{voice:l}:{}};return await this.store.saveVideo(c),this.say(`Filmed "${t.title}": ${Math.round(p.size/1e6)} MB, kept here.`),c}filmQuality(){const{frameRate:t,bitrate:e,lines:s,aspect:i,fit:o}=this.state.settings.film;return{frameRate:t,bitrate:e,fit:o,...s?{size:$(s,i)}:{}}}look(t){const{settings:e}=this.state,s=this.options.appTheme?.(),i=this.options.language?.();return{...s?{theme:s}:{},...i?{locale:i}:{},voice:e.speech.voice,language:t,subtitles:e.subtitles}}async transcribe(t,e=this.language()){const{settings:s}=this.state;return v(t,{language:e,with:s.transcriber,model:s.whisperModel,elevenLabsKey:s.speech.elevenlabs.key,progress:t=>this.set({speech:t<1?{loading:t}:{}})})}record(t={}){return new Promise(e=>this.whenClicked(t.into?.title??"New demo","Record",async()=>{if(this.busy())return e();this.say(void 0),await this.recordNow(t,e)}))}async recordNow(e,i){const{settings:o}=this.state,n=this.language();let a,r;try{o.filmRecording?a=await j({soundtrack:this.speech.soundtrack(),microphone:o.microphone,crop:this.options.filmElement?.(),...this.filmQuality(),onEnded:()=>{this.stopRecording?.()}}):o.microphone&&(r=await R())}catch(t){return this.say(`Could not start: ${t.message}`,!0),i()}const p=this.options.start?.current(),l=new B(this.targets,this.plugins,n,t=>this.updateSession("recording",t));a?.resume();const d=performance.now();this.setSession({mode:"recording",filming:Boolean(a),microphone:Boolean(r||a&&o.microphone),step:0,caption:"",actions:0}),this.nextStepRecording=()=>l.nextStep(),this.sayRecording=t=>l.say(t),this.stopRecording=async()=>{this.stopRecording=this.nextStepRecording=this.sayRecording=void 0;const c=Boolean(r||a&&o.microphone),m=l.stop(c),g=performance.now()-d;this.setSession({mode:"preparing",title:"Recording",text:"Keeping what was recorded"});try{const[i,o]=await Promise.all([r?.stop(),a?.stop()]),l=i??o?.voice;let d=[];if(l){this.updateSession("preparing",{text:"Transcribing what was said"});try{d=await this.transcribe(l,n);const t=w(m.stepStarts,d);m.steps.forEach((e,s)=>{!e.say[n]&&t[s]&&(e.say[n]=t[s])})}catch(t){this.say(`Transcribing failed: ${t.message}`,!0)}}const c=m.steps.filter(t=>t.actions.length>0||Object.values(t.say).some(Boolean)),u=e.into?t(e.into):{...s("Recorded demo",p),steps:[]},y=e.after??u.steps.length-1,f={...u,steps:[...u.steps.slice(0,y+1),...c,...u.steps.slice(y+1)]};0===f.steps.length&&f.steps.push({say:{},actions:[]}),o&&await this.store.saveVideo({id:f.id,blob:o.video,at:Date.now(),json:JSON.stringify(f),vtt:h(d),language:n,look:{...this.look(n),voice:"off",subtitles:!1},timing:{duration:g,steps:m.stepStarts.map((t,e)=>({step:e,start:t,end:m.stepStarts[e+1]??g})),cues:d.map(t=>({...t,step:0})),actions:[]},...o.voice?{voice:o.voice}:{}}),this.setSession({mode:"idle"}),this.say(`Recorded ${c.length} step${1===c.length?"":"s"}${o?", and filmed":""}.`),e.into&&this.state.studio?.demo.id===e.into.id?this.set({studio:{...this.state.studio,recorded:{steps:f.steps,at:Date.now()}}}):this.openStudio(f)}catch(t){this.setSession({mode:"idle"}),this.say(t.message,!0)}i()}}nextStep(){this.nextStepRecording?.()}narrate(t){this.sayRecording?.(t)}async finishRecording(){await(this.stopRecording?.())}link(t){return T(t)}downloadDemo(t,e="json"){if("md"===e)return b(t.scenario??o(t,this.language()),P(t.id,"md"),"text/markdown");const{scenario:s,savedAt:i,...n}=t;b(JSON.stringify(n,null,2)+"\n",P(t.id,"demo.json"),"application/json")}downloadVideo(t,e,s=!1){return"vtt"===s?b(t.vtt,P(e,"vtt"),"text/vtt"):"srt"===s?b(r(a(t.vtt)),P(e,"srt"),"application/x-subrip"):void b(t.blob,P(e,E(t.blob)))}shareVideo(t,e){return x([new File([t.blob],P(e,E(t.blob)),{type:t.blob.type}),new File([t.vtt],P(e,"vtt"),{type:"text/vtt"})],e)}languagesOf(t){return e(t)}}export{V as DEFAULT_SETTINGS};
1
+ import{copyOf as t,languagesOf as e,newDemo as s,sayOf as i,scenarioOf as o,sentences as n}from"../model/Demo.js";import{parseSubtitles as a,toSrt as r,toVtt as h}from"../model/Subtitles.js";import{actionTime as p,estimate as l}from"../model/Timing.js";import{parseDemo as d,validate as c}from"../model/Validate.js";import{Hand as m}from"../page/Input.js";import{Overlay as g}from"../page/Overlay.js";import{stillPage as u}from"../page/Still.js";import{Targets as y}from"../page/Targets.js";import{Speech as f}from"../speech/Speech.js";import{narrationFor as w,transcribe as v}from"../speech/Transcribe.js";import{Store as k}from"../store/Store.js";import{demoFromLink as S,download as b,fileName as P,linkTo as E,shareFiles as T}from"../store/Share.js";import{extensionOf as x,recordMicrophone as R,startFilming as j,videoSize as $}from"../video/Film.js";import{renderMusic as L}from"../speech/Music.js";import{readPack as M,writePack as N}from"../speech/Pack.js";import{Player as K}from"./Player.js";import{Recorder as B}from"./Recorder.js";import{readAction as D}from"./Read.js";import{mountUI as A}from"../ui/EngineUI.js";import{agentTools as I,promptForClaude as O}from"../agent/Agent.js";import{Assistant as F,EMPTY_ASSISTANT as C}from"../agent/Assistant.js";import{openPresenter as J}from"../ui/Presenter.js";import{DEFAULT_RELAY as U,qrSvg as z,RemoteLink as V}from"../remote/Remote.js";import{DEFAULT_SETTINGS as Q,loadSettings as H,saveSettings as G}from"./Settings.js";const q=["pointerdown","pointerup","pointermove","pointerover","pointerout","mousedown","mouseup","mousemove","mouseover","mouseout","click","dblclick","contextmenu","wheel","touchstart","touchmove","touchend","keydown","keyup","keypress"];export class DemoEngine{constructor(t){this.options=t,this.listeners=new Set,this.packs=new Map,this.remoteSent="",this.remoteTimer=0,this.getState=()=>this.state,this.subscribe=t=>(this.listeners.add(t),()=>this.listeners.delete(t)),this.hintTimer=0,this.targets=new y({...t.targets,labels:t.labels}),this.overlay=new g(t.overlay),this.hand=new m(this.overlay.cursor,()=>this.player?.speedNow??1),this.settingsKey=`protomaze-demo-engine:${t.app}:settings`,this.state={session:{mode:"idle"},settings:H(this.settingsKey),speech:{},assistant:C},this.assistant=new F(this,()=>this.state.settings.claude,t=>this.set({assistant:t})),this.speech=new f(()=>this.state.settings.speech,()=>this.set({speech:{...this.speech.state}})),this.store=new k(`protomaze-demo-engine:${t.app}`),this.store.subscribe(()=>this.emit()),this.plugins=t.plugins??[]}emit(){this.state={...this.state},this.listeners.forEach(t=>t()),this.toRemote()}set(t){this.state={...this.state,...t},this.listeners.forEach(t=>t()),this.toRemote()}setSession(t){this.set({session:t})}updateSession(t,e){this.state.session.mode===t&&this.setSession({...this.state.session,...e})}say(t,e=!1){this.set({message:t?{text:t,error:e}:void 0})}changeSettings(t){const e={...this.state.settings,...t};G(this.settingsKey,e),this.set({settings:e}),t.music?.on&&this.loadMusic().catch(()=>{})}language(){const t=this.state.settings.language;return"page"!==t?t:this.options.language?.()??this.options.languages?.[0]??(navigator.language.split("-")[0]||"en")}languages(){return this.options.languages??[this.language()]}pluginKinds(){return this.plugins.flatMap(t=>Object.keys(t.actions??{}))}pluginAction(t){return this.plugins.map(e=>e.actions?.[t]).find(Boolean)}read(t,e){return D(t,this.options.labels,this.plugins,e,this.language())}async mount(){if(this.unmount)return;this.overlay.mount();const t=A(this),e=t=>this.key(t);window.addEventListener("keydown",e,!0);const s=t=>this.gate(t);q.forEach(t=>window.addEventListener(t,s,{capture:!0,passive:!1})),this.state.settings.music.on&&this.loadMusic().catch(()=>{});const i=()=>{this.takeLink()};window.addEventListener("hashchange",i);const o=this.agentName();let n;o&&(window[o]=I(this),n=document.createElement("meta"),n.name="demo-engine",n.content=`window.${o}: tools to make, clone and change demos of this app. ${o}.help() says how.`,document.head.append(n)),this.unmount=()=>{t(),window.removeEventListener("keydown",e,!0),window.removeEventListener("hashchange",i),q.forEach(t=>window.removeEventListener(t,s,{capture:!0})),o&&delete window[o],n?.remove(),this.overlay.unmount()},await this.arrived()}destroy(){this.closeRemote(),this.stopLoop(),this.stop(),this.unmount?.(),this.unmount=void 0}async arrived(){const t=sessionStorage.getItem(this.pendingKey());if(sessionStorage.removeItem(this.pendingKey()),t){const{demo:e,verb:s,from:i,loop:o}=JSON.parse(t);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(e.title,"film"===s?"Film":"Play",()=>"film"===s?this.film(e):this.play(e,{from:i}),!0)}if(await this.takeLink())return;const e=new URL(window.location.href),s=e.searchParams.get("demo");if(s){e.searchParams.delete("demo"),window.history.replaceState(window.history.state,"",e.toString());const t=(await this.entries()).find(t=>t.demo.id===s);t&&this.whenClicked(t.demo.title,"Play",()=>this.play(t.demo),!0)}}async takeLink(){const t=await S();if(!t)return!1;const e=c(t,this.pluginKinds());return e.length?(this.say(`The link's demo: ${e[0].path} ${e[0].message}`,!0),!0):(await this.save(t),this.say(`"${t.title}" came with the link: it is kept here.`),"idle"===this.state.session.mode&&this.openStudio(t),!0)}agentName(){const t="function"==typeof this.options.agent?this.options.agent():this.options.agent;return!1===t?void 0:t??"demoEngine"}async claudePrompt(t){const e=this.agentName();if(e)return O({url:window.location.href.replace(/#.*$/,""),agent:e,demo:t,link:t&&await this.link(t)})}gate(t){const e=this.state.session;if(!t.isTrusted||"playing"!==e.mode||e.paused||e.looping)return;const s=t.composedPath();if(s.includes(this.overlay.host))return;if(e.guided&&e.instruction){const i=e.player.viewerTarget();if(i&&(s.includes(i)||t instanceof KeyboardEvent&&i.contains(document.activeElement)))return;if(!i&&t instanceof KeyboardEvent)return}const i=t.defaultPrevented;t.cancelable&&t.preventDefault(),t.stopImmediatePropagation(),i||"pointerdown"!==t.type&&"keydown"!==t.type&&"wheel"!==t.type||this.hint(e.guided?'Only the ringed part now: or "Do it for me"':"Playing: Space pauses, and the app is yours then. Esc stops.")}hint(t){window.clearTimeout(this.hintTimer),this.set({hint:t}),this.hintTimer=window.setTimeout(()=>this.set({hint:void 0}),3e3)}pendingKey(){return`protomaze-demo-engine:${this.options.app}:pending`}key(t){if(!t.isTrusted)return;const e=t.composedPath(),s=e.some(t=>t instanceof HTMLElement&&(t.isContentEditable||t.matches("input, textarea, select"))),i=e.includes(this.overlay.host),o=this.state.session,n=()=>{t.preventDefault(),t.stopPropagation()};if("ready"!==o.mode)if("recording"!==o.mode){if("l"===t.key.toLowerCase()&&t.ctrlKey&&t.shiftKey&&this.looping)return n(),this.stopLoop();if(!("playing"!==o.mode||o.looping||o.checking||s&&(i||o.guided&&o.instruction))){if("Escape"===t.key)this.stop();else if(" "===t.key||"b"===t.key||"."===t.key)this.togglePause();else if("ArrowRight"===t.key||"Enter"===t.key||"PageDown"===t.key)o.player.next();else if("ArrowLeft"===t.key||"PageUp"===t.key)o.player.back();else if("Home"===t.key)o.player.goTo(0);else if("End"===t.key)o.player.goTo(o.steps-1);else{if(!/^[1-9]$/.test(t.key)||t.ctrlKey||t.metaKey||t.altKey)return;o.player.goTo(Number(t.key)-1)}n()}}else"Escape"!==t.key||s||(n(),this.stopRecording?.());else"Escape"===t.key&&(n(),o.cancel())}async entries(){return await this.store.ready(),this.entriesNow()}entriesNow(){const{demos:t,videos:e}=this.store.get(),s=new Map(t.map(t=>[t.id,t])),i=this.language(),n=(this.options.demos??[]).map(t=>"demo"in t?t:{demo:t,scenario:void 0});return[...n.map(({demo:t,scenario:n})=>{const a=s.get(t.id);return a?{demo:a,scenario:a.scenario??n??o(a,i),origin:"edited",video:e.get(t.id)}:{demo:t,scenario:n??o(t,i),origin:"app",video:e.get(t.id)}}),...t.filter(t=>!n.some(e=>e.demo.id===t.id)).map(t=>({demo:t,scenario:t.scenario??o(t,i),origin:"here",video:e.get(t.id)}))]}async save(e){const s=c(e,this.pluginKinds());if(s.length)throw new Error(`Not a demo: ${s.map(t=>`${t.path} ${t.message}`).join("; ")}`);await this.store.saveDemo(t(e))}async remove(t){await this.store.deleteDemo(t),this.state.studio?.demo.id===t&&this.closeStudio()}parse(t){return d(t,this.pluginKinds())}create(t){return s(t,this.options.start?.current())}openStudio(e){this.set({studio:{demo:t(e),opened:Date.now()}})}closeStudio(){this.set({studio:void 0})}activated(){const t=navigator.userActivation;return!t||t.isActive}whenClicked(t,e,s,i=!1){const o=()=>{this.setSession({mode:"idle"}),this.speech.wake(),s().catch(t=>this.say(t.message,!0))};if(!i&&this.activated())return o();this.setSession({mode:"ready",title:t,verb:e,go:o,cancel:()=>this.setSession({mode:"idle"})})}async goToStart(t,e,s,i){if(!t.start||!this.options.start)return!0;sessionStorage.setItem(this.pendingKey(),JSON.stringify({demo:t,verb:e,from:s,loop:i}));return"reload"!==await this.options.start.go(t.start)&&(sessionStorage.removeItem(this.pendingKey()),!0)}busy(){return"idle"!==this.state.session.mode&&"ready"!==this.state.session.mode}play(t,e={}){return new Promise(s=>this.whenClicked(t.title,"Play",async()=>{if(this.busy())return s(void 0);if(this.say(void 0),!await this.goToStart(t,"play",e.from))return s(void 0);const i=await this.run(t,e);s(i)}))}async run(t,e={}){const{settings:s}=this.state,i=e.language??this.language(),o=s.music.on&&!e.checking&&!e.guided&&await Promise.race([this.loadMusic(),new Promise(t=>setTimeout(()=>t(!1),e.filming?6e4:1500))]);this.speech.setPack(s.usePacks?await this.pack(t):void 0);const n=new K(t,{language:i,subtitles:s.subtitles,waitForPresenter:s.waitForPresenter&&!e.looping,catchUp:s.catchUp,music:Boolean(o),...e},{hand:this.hand,targets:this.targets,overlay:this.overlay,speech:this.speech,plugins:this.plugins,ready:this.options.ready,read:(t,e)=>this.read(t,e),reset:async()=>!t.start||!this.options.start||"reload"!==await this.options.start.go(t.start),update:t=>this.updateSession("playing",t)});this.setSession({mode:"playing",title:t.title,demo:t,steps:t.steps.length,filming:Boolean(e.filming),checking:Boolean(e.checking),guided:Boolean(e.guided),looping:Boolean(e.looping),presenting:Boolean(e.presenting),player:n,step:e.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"}),e.checking||a.navigated||(this.set({lastRun:{json:JSON.stringify(t),language:i,timing:a.timing}}),a.error&&"Stopped."!==a.error&&this.say(a.error,!0)),a}stop(){const t=this.state.session;"playing"===t.mode&&t.player.stop(),"recording"===t.mode&&this.stopRecording?.(),"ready"!==t.mode&&"preparing"!==t.mode||this.setSession({mode:"idle"})}togglePause(){const t=this.state.session;"playing"===t.mode&&(t.paused?t.player.resume():t.player.pause())}resume(){const t=this.state.session;"playing"===t.mode&&t.player.resume()}next(){const t=this.state.session;"playing"===t.mode&&t.player.next()}back(){const t=this.state.session;"playing"===t.mode&&t.player.back()}openPresenter(t={}){return J(this,t)}presenterKey(t){this.key(t)}present(t,e={}){this.openDialog({kind:"present",demo:t,from:e.from})}openDialog(t){this.set({dialog:t,...this.state.library&&this.options.launcher?{library:void 0}:{}})}closeDialog(){this.set({dialog:void 0})}openSettings(){this.set({library:"settings"})}showLibrary(t){this.set({library:t})}openAssistant(t){!0===this.options.assistant&&this.assistant.open(t)}goTo(t){const e=this.state.session;return"playing"===e.mode&&e.player.goTo(t)}guide(t,e={}){return this.play(t,{...e,guided:!0})}doItForMe(){const t=this.state.session;"playing"===t.mode&&t.player.doItForMe()}async openRemote(){if(!1===this.options.remote)throw new Error("No phone remote in this app");if(this.state.remote)return this.state.remote;const t=this.options.remote?.relay??U;this.remoteLink=await V.open(t,{command:t=>this.fromRemote(t),hello:()=>this.remoteSent="",peers:t=>this.state.remote&&this.set({remote:{...this.state.remote,peers:t}})});const e={url:this.remoteLink.url,svg:z(this.remoteLink.url),peers:0};return this.set({remote:e}),this.remoteTimer=window.setInterval(()=>this.toRemote(!0),1e3),e}closeRemote(){window.clearInterval(this.remoteTimer),this.remoteLink?.close(),this.remoteLink=void 0,this.remoteSent="",this.set({remote:void 0})}fromRemote(t){const e=this.state.session;"playing"===e.mode&&("next"===t.do?e.player.next():"back"===t.do?e.player.back():"goto"===t.do&&void 0!==t.step?e.player.goTo(t.step):"stop"===t.do?this.stop():"toggle"===t.do&&(e.waiting?e.player.next():this.togglePause()))}toRemote(t=!1){if(!this.remoteLink)return;const e=this.remoteState(),{at:s,elapsed:i,stepElapsed:o,...n}=e,a=JSON.stringify(n);(a!==this.remoteSent||t&&e.playing)&&(this.remoteSent=a,this.remoteLink.send(e))}remoteState(){const t=this.state.session,e=Date.now();if("playing"!==t.mode||t.checking)return{playing:!1,title:"",steps:[],step:0,caption:"",paused:!1,waiting:!1,filming:!1,elapsed:0,stepElapsed:0,planned:0,at:e};const s=this.language(),o=this.timing(t.demo,s),a=o.steps.find(e=>e.step===t.step),r=t.player.elapsed();return{playing:!0,title:t.demo.title,steps:t.demo.steps.map((t,e)=>({title:t.title??`Step ${e+1}`,script:n(i(t,s)),...t.notes?{notes:t.notes}:{}})),step:t.step,caption:t.caption,paused:t.paused,waiting:t.waiting,filming:t.filming,elapsed:r,stepElapsed:r-t.player.stepStartedAt,planned:o.duration,...a?{plannedStep:a.end-a.start}:{},at:e}}pack(t){let e=this.packs.get(t.id);return e||(e=(async()=>{const e=await this.store.asset(`narration:${t.id}`);if(e)return M(await e.arrayBuffer());const s=this.options.narration?.(t);if(!s)return;const i=await fetch(s);return i.ok?M(await i.arrayBuffer()):void 0})().catch(()=>{}),this.packs.set(t.id,e)),e}async makePack(t,s=()=>{}){const i=await this.pack(t);this.speech.setPack(i);const o=e(t).flatMap(e=>t.steps.flatMap(t=>n(t.say[e]??"").map(t=>({language:e,text:t})))),a=o.filter((t,e)=>o.findIndex(e=>e.language===t.language&&e.text===t.text)===e),r=[];for(const t of a)s(r.length,a.length),r.push({...await this.speech.packable(t.text,t.language),...t});s(r.length,a.length);const h=N(t.id,r);return await this.store.saveAsset(`narration:${t.id}`,h),this.packs.delete(t.id),h}async downloadPack(t){try{const e=await this.makePack(t,(t,e)=>this.say(`Making the narration pack: ${t} / ${e}`));b(e,`${t.id}.narration.zip`),this.say(`Narration pack: ${Math.round(e.size/1e5)/10} MB, kept here too. Check it in beside ${t.id}.demo.json, for every viewer.`)}catch(t){this.say(`Narration pack: ${t.message}`,!0)}}async dropPack(t){await this.store.saveAsset(`narration:${t.id}`,void 0),this.packs.delete(t.id)}async setMusic(t){await this.store.saveAsset("music",t),this.musicLoaded=void 0;const{music:e}=this.state.settings;this.changeSettings({music:t?{...e,on:!0,track:"file",name:t.name??"music"}:{...e,track:"calm",name:void 0}})}async loadMusic(){const{music:t}=this.state.settings,e="file"===t.track?`file:${t.name}`:t.track;if(this.musicLoaded!==e){if("file"===t.track){const e=await this.store.asset("music");if(!e)return!1;await this.speech.setMusic(e,t.volume).catch(()=>{})}else this.speech.setMusicBuffer(await L(t.track),t.volume);this.musicLoaded=e}return this.speech.setMusicVolume(t.volume),this.speech.hasMusic}async listenToMusic(t=20){if(this.speech.wake(),!await this.loadMusic())return()=>{};this.speech.startMusic();const e=setTimeout(()=>this.speech.stopMusic(),1e3*t);return()=>{clearTimeout(e),this.speech.stopMusic(.6)}}async loop(t,e={},s=0){if(0===t.length)return;this.stopLoop();let i=!1,o=0,n=s;const a=e.idle??this.state.settings.loopIdle,r=e.gap??1500,h=t.map(t=>t.title),p=t=>{if(!t.isTrusted||t.composedPath().includes(this.overlay.host))return;o=performance.now();const e=this.state.session;"playing"===e.mode&&e.looping&&e.player.stop(!0)},l=["pointerdown","keydown","wheel","touchstart"];l.forEach(t=>window.addEventListener(t,p,{capture:!0,passive:!0}));this.looping={demos:t,options:e,stop:()=>{i=!0,l.forEach(t=>window.removeEventListener(t,p,{capture:!0}));const t=this.state.session;"playing"===t.mode&&t.looping&&t.player.stop(),this.set({loop:void 0})}};const d=t=>new Promise(e=>setTimeout(e,t));for(;!i;){const s=t[n%t.length];this.set({loop:{titles:h,index:n%t.length,visitor:!1}});if(!await this.goToStart(s,"loop",void 0,{demos:t,index:n%t.length,gap:e.gap,idle:e.idle,reload:"reload"===e.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%t.length,visitor:!0,resumesAt:Date.now()+a-(performance.now()-o)}}),await d(1e3);if(i)break;if("reload"===e.reset)return sessionStorage.setItem(this.pendingKey(),JSON.stringify({demo:s,verb:"loop",loop:{demos:t,index:n%t.length,gap:e.gap,idle:e.idle,reload:!0}})),window.location.reload();await(e.reset?.())}else n++,await d(r)}}stopLoop(){this.looping?.stop(),this.looping=void 0}elapsed(){const t=this.state.session;return"playing"===t.mode?t.player.elapsed():void 0}async check(t,e={}){const s=c(t,this.pluginKinds());if(s.length)return{ok:!1,problems:s,failures:[],duration:0,error:"Not a valid demo"};if(this.busy())return{ok:!1,problems:s,failures:[],duration:0,error:`Busy: ${this.state.session.mode}`};const{animations:i,fromStart:o,...n}=e,a=i?()=>{}:u(document,[this.overlay.root]);try{if(!1!==o&&t.start&&this.options.start){if("reload"===await this.options.start.go(t.start))return{ok:!1,problems:s,failures:[],duration:0,error:"Its start reloads the page: check again once it is back"}}const e=await this.run(t,{...n,speed:n.speed??8,keepGoing:!0,checking:!0,catchUp:!0,subtitles:!1}),i=e.failures.map(e=>({...e,action:t.steps[e.step].actions[e.index]}));return{ok:!e.error&&0===i.length,error:e.error,failures:i,problems:s,duration:e.timing.duration}}finally{a()}}timing(t,e=this.language()){const s=this.state.lastRun;return s&&s.language===e&&s.json===JSON.stringify(t)&&s.timing.steps.length===t.steps.length?s.timing:l(t,{language:e,sayTime:t=>this.speech.duration(t,e),actionTime:t=>{const e=this.pluginAction(t.do);return e?.duration?.(t)??p(t)}})}film(t,e={}){return new Promise(s=>this.whenClicked(t.title,"Film",async()=>this.busy()?s(void 0):(this.say(void 0),await this.goToStart(t,"film")?void s(await this.filmNow(t,e)):s(void 0))))}async filmNow(t,e){const s=e.language??this.language();let o=!1;const a=await j({soundtrack:this.speech.soundtrack(),microphone:e.microphone,crop:this.options.filmElement?.(),...this.filmQuality(),onEnded:()=>{o=!0,this.stop()}});let r;try{const e=t.steps.flatMap(t=>n(i(t,s)));this.setSession({mode:"preparing",title:t.title,text:"Preparing the narration"}),await this.speech.prepare(e,s,(t,e)=>this.updateSession("preparing",{text:`Preparing the narration: ${t} / ${e}`})),o||"preparing"!==this.state.session.mode||(r=await this.run(t,{language:s,filming:a}))}finally{"preparing"===this.state.session.mode&&this.setSession({mode:"idle"})}const{video:p,voice:l}=await a.stop();if(!r||r.error)return void this.say("Stopped."!==r?.error&&r?`Filming failed: ${r.error}`:"Filming stopped: nothing kept.",Boolean(r?.error&&"Stopped."!==r.error));let d=r.timing.cues;l&&"off"===this.state.settings.speech.voice&&(this.setSession({mode:"preparing",title:t.title,text:"Transcribing what was said"}),d=await this.transcribe(l,s).catch(()=>d),this.setSession({mode:"idle"}));const c={id:t.id,blob:p,at:Date.now(),json:JSON.stringify(t),vtt:h(d),timing:r.timing,language:s,look:this.look(s),...l?{voice:l}:{}};return await this.store.saveVideo(c),this.say(`Filmed "${t.title}": ${Math.round(p.size/1e6)} MB, kept here.`),c}filmQuality(){const{frameRate:t,bitrate:e,lines:s,aspect:i,fit:o}=this.state.settings.film;return{frameRate:t,bitrate:e,fit:o,...s?{size:$(s,i)}:{}}}look(t){const{settings:e}=this.state,s=this.options.appTheme?.(),i=this.options.language?.();return{...s?{theme:s}:{},...i?{locale:i}:{},voice:e.speech.voice,language:t,subtitles:e.subtitles}}async transcribe(t,e=this.language()){const{settings:s}=this.state;return v(t,{language:e,with:s.transcriber,model:s.whisperModel,elevenLabsKey:s.speech.elevenlabs.key,progress:t=>this.set({speech:t<1?{loading:t}:{}})})}record(t={}){return new Promise(e=>this.whenClicked(t.into?.title??"New demo","Record",async()=>{if(this.busy())return e();this.say(void 0),await this.recordNow(t,e)}))}async recordNow(e,i){const{settings:o}=this.state,n=this.language();let a,r;try{o.filmRecording?a=await j({soundtrack:this.speech.soundtrack(),microphone:o.microphone,crop:this.options.filmElement?.(),...this.filmQuality(),onEnded:()=>{this.stopRecording?.()}}):o.microphone&&(r=await R())}catch(t){return this.say(`Could not start: ${t.message}`,!0),i()}const p=this.options.start?.current(),l=new B(this.targets,this.plugins,n,t=>this.updateSession("recording",t));a?.resume();const d=performance.now();this.setSession({mode:"recording",filming:Boolean(a),microphone:Boolean(r||a&&o.microphone),step:0,caption:"",actions:0}),this.nextStepRecording=()=>l.nextStep(),this.sayRecording=t=>l.say(t),this.stopRecording=async()=>{this.stopRecording=this.nextStepRecording=this.sayRecording=void 0;const c=Boolean(r||a&&o.microphone),m=l.stop(c),g=performance.now()-d;this.setSession({mode:"preparing",title:"Recording",text:"Keeping what was recorded"});try{const[i,o]=await Promise.all([r?.stop(),a?.stop()]),l=i??o?.voice;let d=[];if(l){this.updateSession("preparing",{text:"Transcribing what was said"});try{d=await this.transcribe(l,n);const t=w(m.stepStarts,d);m.steps.forEach((e,s)=>{!e.say[n]&&t[s]&&(e.say[n]=t[s])})}catch(t){this.say(`Transcribing failed: ${t.message}`,!0)}}const c=m.steps.filter(t=>t.actions.length>0||Object.values(t.say).some(Boolean)),u=e.into?t(e.into):{...s("Recorded demo",p),steps:[]},y=e.after??u.steps.length-1,f={...u,steps:[...u.steps.slice(0,y+1),...c,...u.steps.slice(y+1)]};0===f.steps.length&&f.steps.push({say:{},actions:[]}),o&&await this.store.saveVideo({id:f.id,blob:o.video,at:Date.now(),json:JSON.stringify(f),vtt:h(d),language:n,look:{...this.look(n),voice:"off",subtitles:!1},timing:{duration:g,steps:m.stepStarts.map((t,e)=>({step:e,start:t,end:m.stepStarts[e+1]??g})),cues:d.map(t=>({...t,step:0})),actions:[]},...o.voice?{voice:o.voice}:{}}),this.setSession({mode:"idle"}),this.say(`Recorded ${c.length} step${1===c.length?"":"s"}${o?", and filmed":""}.`),e.into&&this.state.studio?.demo.id===e.into.id?this.set({studio:{...this.state.studio,recorded:{steps:f.steps,at:Date.now()}}}):this.openStudio(f)}catch(t){this.setSession({mode:"idle"}),this.say(t.message,!0)}i()}}nextStep(){this.nextStepRecording?.()}narrate(t){this.sayRecording?.(t)}async finishRecording(){await(this.stopRecording?.())}link(t){return E(t)}downloadDemo(t,e="json"){if("md"===e)return b(t.scenario??o(t,this.language()),P(t.id,"md"),"text/markdown");const{scenario:s,savedAt:i,...n}=t;b(JSON.stringify(n,null,2)+"\n",P(t.id,"demo.json"),"application/json")}downloadVideo(t,e,s=!1){return"vtt"===s?b(t.vtt,P(e,"vtt"),"text/vtt"):"srt"===s?b(r(a(t.vtt)),P(e,"srt"),"application/x-subrip"):void b(t.blob,P(e,x(t.blob)))}shareVideo(t,e){return T([new File([t.blob],P(e,x(t.blob)),{type:t.blob.type}),new File([t.vtt],P(e,"vtt"),{type:"text/vtt"})],e)}languagesOf(t){return e(t)}}export{Q as DEFAULT_SETTINGS};
@@ -80,7 +80,7 @@ export declare class Player {
80
80
  private t0;
81
81
  private silence;
82
82
  private speed;
83
- /** How long a target may take to show: shorter in the cleanup, where what is absent is skipped. */
83
+ /** How long a target may take to show: shorter in the cleanup, where what is absent is skipped, and after a failure. */
84
84
  private findTimeout;
85
85
  /** On to the next step: what is left of this one quickly, silently. */
86
86
  private hurrying;
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.findTimeout=1e4,this.hurrying=!1,this.dropping=!1,this.navigated=!1,this.stepNow=0,this.stepStart=0,this.last=0,this.skipViewer=()=>{},this.viewerDid=!1,this.keepApp=!1,this.waitingNow=!1,this.sleep=async t=>{let e=t/this.speed;for(;e>0&&!this.stopped&&!this.hurrying&&!this.dropping;){if(void 0!==this.pausedAt){await c(50);continue}const t=Math.min(e,50),s=performance.now();await c(t),e-=performance.now()-s}},this.speed=e.speed??1}elapsed(){return(this.pausedAt??performance.now())-this.t0-this.held}get paused(){return void 0!==this.pausedAt}pause(t=!1){void 0===this.pausedAt&&(this.pausedAt=performance.now(),this.waitingNow=t,this.context.speech.pause(),this.options.filming?.pause(),this.context.update({paused:!0,waiting:t}))}resume(){void 0!==this.pausedAt&&(this.held+=performance.now()-this.pausedAt,this.pausedAt=void 0,this.context.speech.resume(),this.options.filming?.resume(),this.context.update({paused:!1,waiting:!1}))}stop(t=!1){this.stopped=!0,this.keepApp=t,this.silence(),this.skipViewer(),this.resume()}viewerTarget(){return this.target?.()}get speedNow(){return this.hurrying?20:this.speed}next(){if(this.waiting)return this.resume();this.goTo(this.stepNow+1)}back(){const t=!this.waiting&&this.elapsed()-this.stepStart<3e3;this.goTo(t?this.stepNow-1:this.stepNow)}goTo(t){if(this.options.filming||this.stopped)return!1;const e=Math.max(0,Math.min(t,this.last));return!(e>this.stepNow&&this.stepNow===this.last)&&(this.jump=e,this.navigated=!0,e>this.stepNow?this.hurrying=!0:this.dropping=!0,this.silence(),this.skipViewer(),this.resume(),!0)}get step(){return this.stepNow}get stepStartedAt(){return this.stepStart}get waiting(){return void 0!==this.pausedAt&&this.waitingNow}doItForMe(){this.skipViewer()}async whilePaused(){for(;void 0!==this.pausedAt&&!this.stopped;)await c(50)}async find(t){const e=await this.context.targets.find(t,this.findTimeout,()=>this.stopped);if(!e)throw new Error(this.stopped?"Stopped.":`Not found: ${describeTarget(t)}`);return e}follow(t,e){let s=e;return()=>(s?.isConnected||(s=this.context.targets.matches(t)[t.index??0]),s)}async play(){const{demo:e,options:n,context:r}=this,p=n.language,d=Math.max(0,Math.min(n.from??0,e.steps.length-1)),l=Math.min(n.to??e.steps.length-1,e.steps.length-1),u=this.speed>1,w={duration:0,steps:[],cues:[],actions:[]},g=[];let f;const m=new Set;try{this.last=l,d>0&&!1!==n.catchUp&&await this.catchUp(0,d);const f=e.steps.map(t=>u?[]:o(i(t,p))),y=[...f.slice(d),...f.slice(0,d)].flat();y.forEach(t=>r.speech.make(t,p)?.catch(()=>{}));const v=y.map(t=>r.speech.make(t,p))[0]?.catch(()=>{});v&&await Promise.race([v,c(n.filming?6e5:3e3)]),await(r.ready?.()),this.t0=performance.now(),this.held=0,n.filming?.resume(),n.music&&!u&&r.speech.startMusic();let x=d;for(;x<=l&&!this.stopped;){const i=e.steps[x];this.stepNow=x,r.update({step:x,caption:""}),r.overlay.raise();const o=this.elapsed();this.stepStart=o;const c=[],y=f[x].map((t,e)=>new Promise(t=>c[e]=t));let v=!1,k=()=>{};const b=new Promise(t=>k=t),$=async()=>{for(const[t,e]of f[x].entries()){if(await this.whilePaused(),this.stopped||this.hurrying||this.dropping)break;const s=await r.speech.say(e,p,n.filming?1/0:0===t&&x===d?0:1500);await this.whilePaused();const i=this.elapsed();c[t](),!1!==n.subtitles&&r.overlay.subtitle(e),r.update({caption:e}),s?(this.silence=s.stop,this.hurrying&&s.stop(),await s.done):await this.sleep(a(e)),w.cues.push({step:x,start:i,end:this.elapsed(),text:e})}v=!0,c.forEach(t=>t()),k(),r.overlay.subtitle(void 0),r.update({caption:""})},N=async()=>{for(const[e,o]of i.actions.entries()){if(this.stopped||this.dropping)break;if(void 0===o.cue||v||u||await(y[o.cue]??b),await this.sleep(o.wait??t),await this.whilePaused(),this.stopped||this.dropping)break;if(this.hurrying&&s(o))continue;const i=this.elapsed(),a={step:x,index:e,start:i,end:i};w.actions.push(a);try{const t=n.guided&&h(o)&&!this.hurrying;t&&await this.viewerDoes(o);const e=t&&this.viewerDid?void 0:await this.perform(o,p);if(a.end=this.elapsed(),e){const t=()=>{m.delete(t)&&(e(),a.end=this.elapsed())};m.add(t);const s=o.for;void 0!==s&&this.sleep(s).then(t)}"clear"===o.do&&[...m].forEach(t=>t())}catch(t){const s=t.message;if(a.end=this.elapsed(),a.error=s,this.stopped)break;if(!n.keepGoing)throw new Error(`Step ${x+1}, action ${e+1} (${o.do}): ${s}`);g.push({step:x,index:e,error:s})}}};if(await Promise.all([$(),N()]),i.hold&&await this.sleep(i.hold),[...m].forEach(t=>t()),w.steps.push({step:x,start:o,end:this.elapsed()}),this.hurrying=!1,void 0===this.jump&&(i.pause||n.waitForPresenter)&&x<l&&!this.stopped&&!u&&(this.pause(!0),await this.whilePaused()),this.stopped)break;if(void 0!==this.jump){const t=this.jump;this.jump=void 0,this.dropping=!1,t<=x?await this.rewind(t):t>x+1&&await this.covered(t,()=>this.catchUp(x+1,t)),x=t;continue}x++}this.stopped||await this.sleep(u?0:1e3)}catch(t){f=t.message}finally{[...m].forEach(t=>t()),r.speech.stopMusic(),this.keepApp||await this.cleanup(),r.update({instruction:void 0}),r.overlay.clear(),r.overlay.subtitle(void 0),r.overlay.hideCursor(),r.hand.reset(),this.stopped&&(f??(f="Stopped."))}return w.duration=this.elapsed(),{timing:w,error:f,failures:g,...this.navigated?{navigated:!0}:{}}}async viewerDoes(t){this.viewerDid=!1;const e=t.target,s=e?await this.find(e):void 0;s?.scrollIntoView({block:"nearest",inline:"nearest"});const i=this.context.read(t,s);this.target=s&&e?this.follow(e,s):void 0;const o=s&&e?[this.context.overlay.show({kind:"ring",element:this.follow(e,s)}),this.context.overlay.show({kind:"callout",text:i,element:this.follow(e,s)})]:[this.context.overlay.show({kind:"callout",text:i,corner:"top-right"})];this.context.update({instruction:i});const a=p(t,this.context.targets);let n=!1;this.skipViewer=()=>{n=!0,a.cancel()},await a.done,this.target=void 0,this.skipViewer=()=>{},o.forEach(t=>t()),this.context.update({instruction:void 0}),this.viewerDid=!n}async cleanup(){const e=this.demo.cleanup??[];if(0===e.length)return;const[i,o]=[this.stopped,this.speed];this.stopped=!1,this.hurrying=!1,this.speed=Math.max(o,12),this.findTimeout=500,this.context.update({caption:""}),this.context.overlay.quiet=!0;try{for(const i of e)s(i)||(await this.sleep(Math.min(i.wait??t,1e3)),await this.perform(i,this.options.language).catch(()=>{}))}finally{this.context.overlay.quiet=!1,this.findTimeout=1e4,[this.stopped,this.speed]=[i,o]}}async covered(t,e){const s=this.demo.steps[t]?.title,i=this.context.overlay.show({kind:"card",title:`${t+1}${s?` · ${s}`:""}`,text:`${t+1} / ${this.last+1}`});this.context.overlay.quiet=!0,this.context.overlay.subtitle(void 0);try{await e()}finally{this.context.overlay.quiet=!1,this.context.overlay.hideCursor(),await c(250),i()}}async rewind(t){await this.covered(t,async()=>{this.context.overlay.clear(),await this.cleanup(),await(this.context.reset?.()),await this.catchUp(0,t)})}async catchUp(e,i){const o=this.speed;this.speed=Math.max(o,12),this.context.update({catchingUp:!0});try{for(let o=e;o<i&&!this.stopped;o++){this.context.update({step:o});for(const e of this.demo.steps[o].actions){if(this.stopped)return;if(!s(e)){await this.sleep(Math.min(e.wait??t,1500));try{await this.perform(e,this.options.language)}catch(t){throw new Error(`Catching up, step ${o+1}: ${t.message}`)}}}}await this.sleep(1500)}finally{this.speed=o,this.context.update({catchingUp:!1})}}async perform(t,s){const{hand:i,overlay:o}=this.context;if(!e(t)){const e=this.context.plugins.map(e=>e.actions?.[t.do]).find(Boolean);if(!e)throw new Error(`No plugin plays "${t.do}"`);const a={hand:i,overlay:o,targets:this.context.targets,language:s,speed:this.speed,find:t=>this.find(t),sleep:this.sleep,stopped:()=>this.stopped};return void await e.play(t,a)}const a=t=>o.show(t);switch(t.do){case"click":{const e=await this.find(t.target);return e.scrollIntoView({block:"nearest",inline:"nearest"}),i.click(e,n(e,t.at),t)}case"hover":{const e=await this.find(t.target);return e.scrollIntoView({block:"nearest",inline:"nearest"}),i.point(e,n(e,t.at))}case"type":{const e=await this.find(t.target);return e.scrollIntoView({block:"nearest",inline:"nearest"}),await i.point(e,n(e)),i.type(e,t.text)}case"key":{const e=t.target?await this.find(t.target):void 0;return this.speed<=1&&o.keys(t.key),i.key(t.key,e)}case"select":{const e=await this.find(t.target);if(!(e instanceof HTMLSelectElement))throw new Error("Not a <select>: click its options instead");return e.scrollIntoView({block:"nearest",inline:"nearest"}),i.select(e,t.option,n(e))}case"drag":{const e=await this.find(t.target);e.scrollIntoView({block:"nearest",inline:"nearest"});const s=n(e,t.at),o=t.to.target?await this.find(t.to.target):e;return i.drag(e,s,r(o,t.to.at),t)}case"scroll":{const e=t.target?await this.find(t.target):void 0;return i.scroll(e,t.by)}case"waitFor":{const e=performance.now()+(t.timeout??this.findTimeout);for(;!this.stopped;){if(this.context.targets.matches(t.target).some(t=>t.getClientRects().length>0)!==Boolean(t.gone))return;if(performance.now()>e)throw new Error(`${t.gone?"Still there":"Not found"}: ${describeTarget(t.target)}`);await c(100)}return}case"clear":return void o.clear();case"card":return a({kind:"card",title:t.title,text:t.text});case"callout":{const e=t.target?await this.find(t.target):void 0;return a({kind:"callout",text:t.text,side:t.side,corner:t.corner,element:e&&this.follow(t.target,e)})}default:{const e=await this.find(t.target);e.scrollIntoView({block:"nearest",inline:"nearest"});const s=this.follow(t.target,e);switch(t.do){case"spotlight":return a({kind:"spotlight",element:s,text:t.text,padding:t.padding});case"ring":return a({kind:"ring",element:s,text:t.text,color:t.color,shape:t.shape,padding:t.padding});case"arrow":return a({kind:"arrow",element:s,text:t.text,from:t.from,color:t.color});case"blur":return a({kind:"blur",element:s});case"zoom":{const e=a({kind:"zoom",element:s,scale:t.scale});return await this.sleep(700),e}}}}}}export function describeTarget(t){const e=t.key??t.text;return`${e?`"${e}" `:""}${t.css}${t.index?` #${t.index+1}`:""}`}
1
+ import{DEFAULT_WAIT as t,isBuiltIn as e,isPresent as s,sayOf as i,sentences as o,shownIn as a}from"../model/Demo.js";import{readingTime as n}from"../model/Timing.js";import{at as r}from"../page/Input.js";import{pointIn as h}from"../page/Targets.js";import{isGuided as p,waitForViewer as c}from"./Guided.js";const d=t=>new Promise(e=>setTimeout(e,t));export class Player{constructor(t,e,s){this.demo=t,this.options=e,this.context=s,this.stopped=!1,this.held=0,this.t0=performance.now(),this.silence=()=>{},this.findTimeout=1e4,this.hurrying=!1,this.dropping=!1,this.navigated=!1,this.stepNow=0,this.stepStart=0,this.last=0,this.skipViewer=()=>{},this.viewerDid=!1,this.keepApp=!1,this.waitingNow=!1,this.sleep=async t=>{let e=t/this.speed;for(;e>0&&!this.stopped&&!this.hurrying&&!this.dropping;){if(void 0!==this.pausedAt){await d(50);continue}const t=Math.min(e,50),s=performance.now();await d(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 d(50)}async find(t){const e=await this.context.targets.find(t,this.findTimeout,()=>this.stopped);if(!e)throw new Error(this.stopped?"Stopped.":`Not found: ${describeTarget(t)}`);return e}follow(t,e){let s=e;return()=>(s?.isConnected||(s=this.context.targets.matches(t)[t.index??0]),s)}async play(){const{demo:e,options:a,context:r}=this,h=a.language,c=Math.max(0,Math.min(a.from??0,e.steps.length-1)),l=Math.min(a.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,c>0&&!1!==a.catchUp&&await this.catchUp(0,c);const f=e.steps.map(t=>u?[]:o(i(t,h))),y=[...f.slice(c),...f.slice(0,c)].flat();y.forEach(t=>r.speech.make(t,h)?.catch(()=>{}));const v=y.map(t=>r.speech.make(t,h))[0]?.catch(()=>{});v&&await Promise.race([v,d(a.filming?6e5:3e3)]),await(r.ready?.()),this.t0=performance.now(),this.held=0,a.filming?.resume(),a.music&&!u&&r.speech.startMusic();let x=c;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 d=[],y=f[x].map((t,e)=>new Promise(t=>d[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,h,a.filming?1/0:0===t&&x===c?0:1500);await this.whilePaused();const i=this.elapsed();d[t](),!1!==a.subtitles&&r.overlay.subtitle(e),r.update({caption:e}),s?(this.silence=s.stop,this.hurrying&&s.stop(),await s.done):await this.sleep(n(e)),w.cues.push({step:x,start:i,end:this.elapsed(),text:e})}v=!0,d.forEach(t=>t()),k(),r.overlay.subtitle(void 0),r.update({caption:""})},T=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(),n={step:x,index:e,start:i,end:i};w.actions.push(n);try{const t=a.guided&&p(o)&&!this.hurrying;t&&await this.viewerDoes(o);const e=t&&this.viewerDid?void 0:await this.perform(o,h);if(n.end=this.elapsed(),e){const t=()=>{m.delete(t)&&(e(),n.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(n.end=this.elapsed(),n.error=s,this.stopped)break;if(!a.keepGoing)throw new Error(`Step ${x+1}, action ${e+1} (${o.do}): ${s}`);g.push({step:x,index:e,error:s}),this.findTimeout=Math.min(this.findTimeout,2e3)}}};if(await Promise.all([$(),T()]),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||a.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=c(t,this.context.targets);let n=!1;this.skipViewer=()=>{n=!0,a.cancel()},await a.done,this.target=void 0,this.skipViewer=()=>{},o.forEach(t=>t()),this.context.update({instruction:void 0}),this.viewerDid=!n}async cleanup(){const e=this.demo.cleanup??[];if(0===e.length)return;const[i,o]=[this.stopped,this.speed];this.stopped=!1,this.hurrying=!1,this.speed=Math.max(o,12),this.findTimeout=500,this.context.update({caption:""}),this.context.overlay.quiet=!0;try{for(const i of e)s(i)||(await this.sleep(Math.min(i.wait??t,1e3)),await this.perform(i,this.options.language).catch(()=>{}))}finally{this.context.overlay.quiet=!1,this.findTimeout=1e4,[this.stopped,this.speed]=[i,o]}}async covered(t,e){const s=this.demo.steps[t]?.title,i=this.context.overlay.show({kind:"card",title:`${t+1}${s?` · ${s}`:""}`,text:`${t+1} / ${this.last+1}`});this.context.overlay.quiet=!0,this.context.overlay.subtitle(void 0);try{await e()}finally{this.context.overlay.quiet=!1,this.context.overlay.hideCursor(),await d(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 n=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,r(e,t.at),t)}case"hover":{const e=await this.find(t.target);return e.scrollIntoView({block:"nearest",inline:"nearest"}),i.point(e,r(e,t.at))}case"type":{const e=await this.find(t.target);return e.scrollIntoView({block:"nearest",inline:"nearest"}),await i.point(e,r(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,r(e))}case"drag":{const e=await this.find(t.target);e.scrollIntoView({block:"nearest",inline:"nearest"});const s=r(e,t.at),o=t.to.target?await this.find(t.to.target):e;return i.drag(e,s,h(o,t.to.at),t)}case"scroll":{const e=t.target?await this.find(t.target):void 0;return i.scroll(e,t.by)}case"waitFor":{const e=performance.now()+(t.timeout??this.findTimeout);for(;!this.stopped;){if(this.context.targets.matches(t.target).some(t=>t.getClientRects().length>0)!==Boolean(t.gone))return;if(performance.now()>e)throw new Error(`${t.gone?"Still there":"Not found"}: ${describeTarget(t.target)}`);await d(100)}return}case"clear":return void o.clear();case"card":return n({kind:"card",title:a(t.title,s)??"",text:a(t.text,s)});case"callout":{const e=t.target?await this.find(t.target):void 0;return n({kind:"callout",text:a(t.text,s)??"",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 i=this.follow(t.target,e);switch(t.do){case"spotlight":return n({kind:"spotlight",element:i,text:a(t.text,s),padding:t.padding});case"ring":return n({kind:"ring",element:i,text:a(t.text,s),color:t.color,shape:t.shape,padding:t.padding});case"arrow":return n({kind:"arrow",element:i,text:a(t.text,s),from:t.from,color:t.color});case"blur":return n({kind:"blur",element:i});case"zoom":{const e=n({kind:"zoom",element:i,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/engine/Read.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import type { DemoAction } from '../model/Demo';
1
+ import { DemoAction, Language } from '../model/Demo';
2
2
  import type { Labels } from '../page/Targets';
3
3
  import type { DemoPlugin } from './Plugin';
4
4
  /** An action as a sentence; `shown`: its target as the page shows it now, named as it reads there. */
5
- export declare function readAction(action: DemoAction, labels?: Labels, plugins?: DemoPlugin[], shown?: Element): string;
5
+ export declare function readAction(action: DemoAction, labels?: Labels, plugins?: DemoPlugin[], shown?: Element, language?: Language): string;
package/engine/Read.js CHANGED
@@ -1 +1 @@
1
- export function readAction(t,e,r=[],a){const o=a?.innerText?.trim().replace(/\s+/g," "),n=r=>{if(!r)return"";if(r===t.target&&o&&o.length<=40)return`"${o}"`;const a=r.key?e?.textOf(r.key)??r.key:r.text;return a?`"${a}"`:r.css},c=t;switch(t.do){case"click":return`${c.double?"Double-click":c.right?"Right-click":"Click"} ${n(c.target)}`;case"hover":return`Point at ${n(c.target)}`;case"type":return`Type "${c.text}" in ${n(c.target)}`;case"key":return`Press ${c.key}${c.target?` in ${n(c.target)}`:""}`;case"select":return`Choose "${c.option}" in ${n(c.target)}`;case"drag":return`Drag ${n(c.target)}${c.to?.target?` to ${n(c.to.target)}`:""}`;case"scroll":return c.by?`Scroll by ${c.by.join(", ")}`:`Scroll to ${n(c.target)}`;case"waitFor":return`Wait ${c.gone?"till gone":"for"} ${n(c.target)}`;case"spotlight":return`Spotlight ${n(c.target)}`;case"ring":return`Ring ${n(c.target)}`;case"arrow":return`Arrow at ${n(c.target)}${c.text?`: ${c.text}`:""}`;case"callout":return`Note: ${c.text}`;case"blur":return`Blur ${n(c.target)}`;case"card":return`Card: ${c.title}`;case"zoom":return`Zoom to ${n(c.target)}`;case"clear":return"Clear effects";default:return r.map(e=>e.actions?.[t.do]).find(Boolean)?.read?.(t)??t.do}}
1
+ import{shownIn as t}from"../model/Demo.js";export function readAction(e,r,a=[],o,n="en"){const c=o?.innerText?.trim().replace(/\s+/g," "),s=t=>{if(!t)return"";if(t===e.target&&c&&c.length<=40)return`"${c}"`;const a=t.key?r?.textOf(t.key)??t.key:t.text;return a?`"${a}"`:t.css},i=e;switch(e.do){case"click":return`${i.double?"Double-click":i.right?"Right-click":"Click"} ${s(i.target)}`;case"hover":return`Point at ${s(i.target)}`;case"type":return`Type "${i.text}" in ${s(i.target)}`;case"key":return`Press ${i.key}${i.target?` in ${s(i.target)}`:""}`;case"select":return`Choose "${i.option}" in ${s(i.target)}`;case"drag":return`Drag ${s(i.target)}${i.to?.target?` to ${s(i.to.target)}`:""}`;case"scroll":return i.by?`Scroll by ${i.by.join(", ")}`:`Scroll to ${s(i.target)}`;case"waitFor":return`Wait ${i.gone?"till gone":"for"} ${s(i.target)}`;case"spotlight":return`Spotlight ${s(i.target)}`;case"ring":return`Ring ${s(i.target)}`;case"arrow":return`Arrow at ${s(i.target)}${i.text?`: ${t(i.text,n)}`:""}`;case"callout":return`Note: ${t(i.text,n)??""}`;case"blur":return`Blur ${s(i.target)}`;case"card":return`Card: ${t(i.title,n)??""}`;case"zoom":return`Zoom to ${s(i.target)}`;case"clear":return"Clear effects";default:return a.map(t=>t.actions?.[e.do]).find(Boolean)?.read?.(e)??e.do}}
package/model/Demo.d.ts CHANGED
@@ -117,14 +117,14 @@ export type Lasting = {
117
117
  export type SpotlightAction = ActionBase & Lasting & {
118
118
  do: 'spotlight';
119
119
  target: DemoTarget;
120
- text?: string;
120
+ text?: Shown;
121
121
  padding?: number;
122
122
  };
123
123
  /** A ring around the target; `shape` 'circle' for round things. */
124
124
  export type RingAction = ActionBase & Lasting & {
125
125
  do: 'ring';
126
126
  target: DemoTarget;
127
- text?: string;
127
+ text?: Shown;
128
128
  color?: string;
129
129
  shape?: 'box' | 'circle';
130
130
  padding?: number;
@@ -133,14 +133,14 @@ export type RingAction = ActionBase & Lasting & {
133
133
  export type ArrowAction = ActionBase & Lasting & {
134
134
  do: 'arrow';
135
135
  target: DemoTarget;
136
- text?: string;
136
+ text?: Shown;
137
137
  from?: Side;
138
138
  color?: string;
139
139
  };
140
140
  /** A note: at the target, or in a corner of the screen. */
141
141
  export type CalloutAction = ActionBase & Lasting & {
142
142
  do: 'callout';
143
- text: string;
143
+ text: Shown;
144
144
  target?: DemoTarget;
145
145
  side?: Side;
146
146
  corner?: Corner;
@@ -153,8 +153,8 @@ export type BlurAction = ActionBase & Lasting & {
153
153
  /** A full-screen card: a title to open, a chapter, an end. */
154
154
  export type CardAction = ActionBase & Lasting & {
155
155
  do: 'card';
156
- title: string;
157
- text?: string;
156
+ title: Shown;
157
+ text?: Shown;
158
158
  };
159
159
  /** Magnifies the page around the target. */
160
160
  export type ZoomAction = ActionBase & Lasting & {
@@ -187,6 +187,14 @@ export declare const DEFAULT_WAIT = 800;
187
187
  /** The actions that take a target, and their targets; `drag` may have a second. */
188
188
  export declare function targetsOf(action: DemoAction): DemoTarget[];
189
189
  export declare function isTarget(value: unknown): value is DemoTarget;
190
+ /**
191
+ * Text on the screen - a card's, a note's, a label's: one for every language, or one per language
192
+ * as narration is, `{ en: '…', de: '…' }`.
193
+ */
194
+ export type Shown = string | Partial<Record<Language, string>>;
195
+ /** `text` in `language`: its own, else its base language's ("de" for "de-CH"), else the first it has. */
196
+ export declare function shownIn(text: Shown | undefined, language: Language): string | undefined;
197
+ export declare function isShown(value: unknown): value is Shown;
190
198
  /** A step's narration in `language`, else in the first language it has. */
191
199
  export declare function sayOf(step: DemoStep, language: Language): string;
192
200
  /** The languages a demo is narrated in, most used first. */
package/model/Demo.js CHANGED
@@ -1 +1 @@
1
- export const INTERACT_KINDS=["click","hover","type","key","select","drag","scroll","waitFor"];export const PRESENT_KINDS=["spotlight","ring","arrow","callout","blur","card","zoom","clear"];export const BUILT_IN_KINDS=[...INTERACT_KINDS,...PRESENT_KINDS];export function isBuiltIn(t){return BUILT_IN_KINDS.includes(t.do)}export function isPresent(t){return PRESENT_KINDS.includes(t.do)}export const DEFAULT_WAIT=800;export function targetsOf(t){const e=[],r=t.target;isTarget(r)&&e.push(r);const o=t.to?.target;return isTarget(o)&&e.push(o),e}export function isTarget(t){return"object"==typeof t&&null!==t&&"string"==typeof t.css}export function sayOf(t,e){return t.say[e]??Object.values(t.say).find(t=>t)??""}export function languagesOf(t){const e=new Map;return t.steps.forEach(t=>Object.entries(t.say).forEach(([t,r])=>{r&&e.set(t,(e.get(t)??0)+1)})),[...e.entries()].sort((t,e)=>e[1]-t[1]).map(([t])=>t)}export function sentences(t){return t.split(/(?<=[.!?…]["')\]]*)\s+/).map(t=>t.trim()).filter(Boolean)}export function scenarioOf(t,e){return[`# ${t.title}`,"",...t.description?[t.description,""]:[],...t.steps.map((t,r)=>`${r+1}. ${t.title?`**${t.title}.** `:""}${sayOf(t,e)||"…"}`),""].join("\n")}export function newDemo(t="New demo",e){return{id:idFrom(t),title:t,description:"",...e?{start:e}:{},steps:[{say:{},actions:[]}]}}export function idFrom(t){return`${t.toLowerCase().normalize("NFKD").replace(/[^\w\s-]/g,"").trim().replace(/[\s_]+/g,"-").slice(0,40)||"demo"}-${Math.random().toString(36).slice(2,6)}`}export function copyOf(t){return JSON.parse(JSON.stringify(t))}
1
+ export const INTERACT_KINDS=["click","hover","type","key","select","drag","scroll","waitFor"];export const PRESENT_KINDS=["spotlight","ring","arrow","callout","blur","card","zoom","clear"];export const BUILT_IN_KINDS=[...INTERACT_KINDS,...PRESENT_KINDS];export function isBuiltIn(t){return BUILT_IN_KINDS.includes(t.do)}export function isPresent(t){return PRESENT_KINDS.includes(t.do)}export const DEFAULT_WAIT=800;export function targetsOf(t){const e=[],r=t.target;isTarget(r)&&e.push(r);const o=t.to?.target;return isTarget(o)&&e.push(o),e}export function isTarget(t){return"object"==typeof t&&null!==t&&"string"==typeof t.css}export function shownIn(t,e){return void 0===t||"string"==typeof t?t:t[e]??t[e.split("-")[0]]??Object.values(t).find(Boolean)}export function isShown(t){return"string"==typeof t||"object"==typeof t&&null!==t&&!Array.isArray(t)&&Object.values(t).every(t=>"string"==typeof t)}export function sayOf(t,e){return t.say[e]??Object.values(t.say).find(t=>t)??""}export function languagesOf(t){const e=new Map;return t.steps.forEach(t=>Object.entries(t.say).forEach(([t,r])=>{r&&e.set(t,(e.get(t)??0)+1)})),[...e.entries()].sort((t,e)=>e[1]-t[1]).map(([t])=>t)}export function sentences(t){return t.split(/(?<=[.!?…]["')\]]*)\s+/).map(t=>t.trim()).filter(Boolean)}export function scenarioOf(t,e){return[`# ${t.title}`,"",...t.description?[t.description,""]:[],...t.steps.map((t,r)=>`${r+1}. ${t.title?`**${t.title}.** `:""}${sayOf(t,e)||"…"}`),""].join("\n")}export function newDemo(t="New demo",e){return{id:idFrom(t),title:t,description:"",...e?{start:e}:{},steps:[{say:{},actions:[]}]}}export function idFrom(t){return`${t.toLowerCase().normalize("NFKD").replace(/[^\w\s-]/g,"").trim().replace(/[\s_]+/g,"-").slice(0,40)||"demo"}-${Math.random().toString(36).slice(2,6)}`}export function copyOf(t){return JSON.parse(JSON.stringify(t))}
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")}),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}}
1
+ import{BUILT_IN_KINDS as t,isShown as e,isTarget as o}from"./Demo.js";const r={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:[]},n=new Set(["target"]),a=new Set(["spotlight","ring","arrow","callout","card"]),s=["top","right","bottom","left"],i=["top-left","top-right","bottom-left","bottom-right"];export function validate(d,f=[]){const g=[],l=(t,e)=>g.push({path:t,message:e});if("object"!=typeof d||null===d)return[{path:"",message:"not an object"}];const p=d;if("string"==typeof p.id&&p.id||l("id","needs a string"),"string"==typeof p.title&&p.title||l("title","needs a string"),void 0!==p.description&&"string"!=typeof p.description&&l("description","is a string"),void 0===p.start||"object"==typeof p.start&&!Object.values(p.start).some(t=>"string"!=typeof t)||l("start","is an object of strings"),!Array.isArray(p.steps))return l("steps","needs an array"),g;const u=[...t,...f];return p.steps.forEach((t,e)=>{const o=`steps[${e}]`;return"object"!=typeof t||null===t?l(o,"not an object"):("object"!=typeof t.say||null===t.say||Array.isArray(t.say)?l(`${o}.say`,"needs an object: language → narration, {} for none"):Object.entries(t.say).forEach(([t,e])=>{"string"!=typeof e&&l(`${o}.say.${t}`,"is a string")}),void 0!==t.notes&&"string"!=typeof t.notes&&l(`${o}.notes`,"is a string"),Array.isArray(t.actions)?void t.actions.forEach((t,e)=>y(t,`${o}.actions[${e}]`)):l(`${o}.actions`,"needs an array, [] for none"))}),void 0!==p.cleanup&&(Array.isArray(p.cleanup)?p.cleanup.forEach((t,e)=>y(t,`cleanup[${e}]`)):l("cleanup","needs an array of actions")),g;function y(t,d){if("object"!=typeof t||null===t)return l(d,"not an object");if(!u.includes(t.do))return l(`${d}.do`,`unknown action "${t.do}": one of ${u.join(", ")}`);for(const e of r[t.do]??[]){const r=t[e];void 0===r||""===r&&"text"!==e?l(`${d}.${e}`,"is required"):n.has(e)&&!o(r)&&l(`${d}.${e}`,"needs { css, text?, key?, index? }")}if(a.has(t.do))for(const o of["title","text"]){const r=t[o];void 0===r||e(r)||l(`${d}.${o}`,"is a text, or one per language: { en: '…', de: '…' }")}void 0!==t.wait&&("number"!=typeof t.wait||t.wait<0)&&l(`${d}.wait`,"is ms, 0 or more"),void 0!==t.cue&&(!Number.isInteger(t.cue)||t.cue<0)&&l(`${d}.cue`,"is a sentence's index, 0 or more");const f=t;if(void 0===f.at||c(f.at)||l(`${d}.at`,"is [x, y], fractions of the box"),void 0===f.from||s.includes(f.from)||l(`${d}.from`,`one of ${s.join(", ")}`),void 0===f.side||s.includes(f.side)||l(`${d}.side`,`one of ${s.join(", ")}`),void 0===f.corner||i.includes(f.corner)||l(`${d}.corner`,`one of ${i.join(", ")}`),"drag"===t.do){const t=f.to;t&&void 0!==t.target&&!o(t.target)&&l(`${d}.to.target`,"needs { css, text?, key?, index? }"),t&&void 0!==t.at&&!c(t.at)&&l(`${d}.to.at`,"is [x, y], fractions of the box"),t&&void 0===t.target&&void 0===t.at&&l(`${d}.to`,"needs a target, an at, or both")}}}function c(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.10",
3
+ "version": "0.1.11",
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/page/Still.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  /**
2
- * Turns the page's CSS transitions and animations off until the returned function is called. A page
3
- * in a hidden tab never finishes them: what fades in would stay at opacity 0, and not be found.
4
- * The engine's own overlay is in a shadow root, which this does not reach.
2
+ * Turns CSS transitions and animations off until the returned function is called: the page's, and
3
+ * in `roots` - shadow roots such as the engine's overlay, which the page's styles do not reach. A
4
+ * page in a hidden tab never finishes them: what fades in would stay at opacity 0, and not be found
5
+ * or seen.
5
6
  */
6
- export declare function stillPage(document?: Document): () => void;
7
+ export declare function stillPage(document?: Document, roots?: ShadowRoot[]): () => void;
package/page/Still.js CHANGED
@@ -1 +1 @@
1
- export function stillPage(t=window.document){const e=t.createElement("style");return e.setAttribute("data-demo-ignore",""),e.textContent="*, *::before, *::after { transition: none !important; animation: none !important; }",t.head.append(e),()=>e.remove()}
1
+ export function stillPage(t=window.document,e=[]){const n=[t.head,...e].map(e=>{const n=t.createElement("style");return n.setAttribute("data-demo-ignore",""),n.textContent="*, *::before, *::after { transition: none !important; animation: none !important; }",e.append(n),n});return()=>n.forEach(t=>t.remove())}
package/page/Targets.js CHANGED
@@ -1 +1 @@
1
- export const IGNORED="[data-demo-ignore]";const t=["button","a[href]","input","textarea","select","summary","canvas","video",'[contenteditable=""]','[contenteditable="true"]','[role="button"]','[role="link"]','[role="tab"]','[role="option"]','[role="menuitem"]','[role="menuitemcheckbox"]','[role="menuitemradio"]','[role="switch"]','[role="checkbox"]','[role="radio"]','[role="slider"]','[role="combobox"]','[role="treeitem"]','[role="gridcell"]','[role="row"]',"li[role]","[data-demo]"];export function normal(t){return t.replace(/\s+/g," ").replace(/\d[\d.,]*/g,"#").trim().toLowerCase().slice(0,80)}export function dictionaryLabels(t,e){let n;const r=()=>{const e=t();if(n?.from===e)return n;const r=new Map,i=new Map,o=(t,e)=>Object.entries(t).forEach(([t,n])=>{const s=e+t;if("object"==typeof n&&n)o(n,s+".");else if("string"==typeof n&&!n.includes("{{")){const t=normal(n);r.set(t,r.has(t)?null:s),i.set(s,n)}});return o(e,""),n={from:e,keys:r,texts:i}};return{keyOf:t=>r().keys.get(normal(t))??void 0,textOf:t=>e?.(t)??r().texts.get(t)}}export class Targets{constructor(e={}){this.options=e,this.interactive=[...t,...e.interactive??[]].join(","),this.attributes=["aria-label","title",...e.labelAttributes??[]]}labelOf(t){const e=t,n=t.getAttribute("aria-labelledby")?.split(/\s+/).map(e=>t.ownerDocument.getElementById(e)?.textContent??"").join(" "),r=t.matches("input, select, textarea"),i=r?t.closest("label"):null,o=r?"":e.innerText?.trim()??"",s=t.getAttribute("data-demo")||(t instanceof HTMLInputElement&&["button","submit","reset"].includes(t.type)?t.value:"")||(/[\p{L}\p{N}]/u.test(o)?o:"")||n?.trim()||this.attributes.map(e=>t.getAttribute(e)).find(Boolean)||t.placeholder||t.alt||t.id&&t.ownerDocument.querySelector(`label[for="${CSS.escape(t.id)}"]`)?.textContent||i&&Array.from(i.childNodes).filter(t=>t.nodeType===Node.TEXT_NODE).map(t=>t.textContent).join(" ").trim()||t.name||o;if(s.trim())return normal(s);const a=t.querySelector("svg[data-testid], [data-icon]"),l=a?.getAttribute("data-testid")??a?.getAttribute("data-icon");if(l)return normal(l);let c=t.parentElement;for(let t=0;c&&t<4;t++,c=c.parentElement){const t=c.innerText??"";if(t.trim())return normal(t)}return""}cssOf(t){const e=t.tagName.toLowerCase(),n=t.getAttribute("role"),r="input"===e?t.getAttribute("type"):null,i=this.options.stableClass&&Array.from(t.classList).find(t=>this.options.stableClass.test(t));return e+(i?`.${CSS.escape(i)}`:"")+(n?`[role="${n}"]`:"")+(r?`[type="${r}"]`:"")}labelIn(t){if(t.key){const e=this.options.labels?.textOf(t.key);if(void 0!==e)return normal(e)}return void 0===t.text?void 0:normal(t.text)}targetElement(t){return!t||t.closest(IGNORED)?null:t.closest(this.interactive)??t}matches(t){const e=this.labelIn(t);let n;try{n=Array.from(document.querySelectorAll(t.css))}catch{return[]}return n.filter(t=>!t.closest(IGNORED)&&(void 0===e||this.labelOf(t)===e))}describe(t){const r=this.cssOf(t),i=this.labelOf(t),o=i&&!t.getAttribute("data-demo")?this.options.labels?.keyOf(i):void 0,s=t=>({css:t,...o?{key:o}:i?{text:i}:{}}),a=s(r);if(this.matches(a).length<=1)return a;for(let i=t.parentElement;i&&i!==document.body;i=i.parentElement){const o=n(i);if(!o)continue;const a=s(`${o} ${r}`),l=this.matches(a);if(1===l.length)return a;if(l.length>1)return{...a,...e(l,t)}}return{...a,...e(this.matches(a),t)}}async find(t,e=1e4,n=()=>!1){const r=performance.now()+e;do{const e=this.matches(t)[t.index??0];if(e&&shown(e))return e;await new Promise(t=>setTimeout(t,100))}while(performance.now()<r&&!n())}list({within:t,query:e,limit:n=400}={}){const i=t?Array.from(document.querySelectorAll(t)):[document.body],o=new Set,s=[],a=e?normal(e):void 0;for(const t of i)for(const e of Array.from(t.querySelectorAll(this.interactive))){if(s.length>=n)break;if(o.has(e)||e.closest(IGNORED)||!shown(e))continue;const i=e.parentElement?.closest(this.interactive);if(i&&!i.closest(IGNORED)&&t.contains(i)&&this.labelOf(i)===this.labelOf(e)&&!e.matches("input, select, textarea, canvas"))continue;o.add(e);const l=this.labelOf(e);if(a&&!l.includes(a))continue;const c=e.getBoundingClientRect();s.push({target:this.describe(e),label:l,tag:e.tagName.toLowerCase(),...e.getAttribute("role")?{role:e.getAttribute("role")}:{},...r(e),box:{x:Math.round(c.x),y:Math.round(c.y),width:Math.round(c.width),height:Math.round(c.height)}})}return s}}function e(t,e){const n=t.indexOf(e);return n>0?{index:n}:{}}function n(t){const e=t.getAttribute("data-demo");if(e)return`[data-demo="${e.replace(/"/g,'\\"')}"]`;const n=t.id;return n&&/^[a-z][\w-]*$/i.test(n)&&!/\d{3,}|[:]|^(mui|radix|react|headlessui|rc)-?/i.test(n)?`#${CSS.escape(n)}`:void 0}export function shown(t){const e=t.checkVisibility;if(e){if(!e.call(t,{checkVisibilityCSS:!0}))return!1;if(!e.call(t,{checkOpacity:!0,checkVisibilityCSS:!0})){const e=t.parentElement;if(!t.matches("input, select, textarea")||!e||!shown(e))return!1}}return t.getClientRects().length>0}function r(t){const e=[],n=t;t.matches("input[type=checkbox], input[type=radio]")?e.push(n.checked?"checked":"unchecked"):t.matches("input, textarea")?e.push(`value "${n.value.slice(0,60)}"`):t instanceof HTMLSelectElement&&e.push(`value "${t.selectedOptions[0]?.text??""}"`);for(const n of["aria-checked","aria-selected","aria-expanded","aria-pressed","aria-current"]){const r=t.getAttribute(n);r&&"false"!==r&&e.push(`${n.slice(5)}${"true"===r?"":`=${r}`}`)}return(t.disabled||"true"===t.getAttribute("aria-disabled"))&&e.push("disabled"),e.length?{state:e.join(", ")}:{}}export function fractionIn(t,e,n){const r=t.getBoundingClientRect(),i=t=>Math.round(1e3*t)/1e3;return[i((e-r.left)/(r.width||1)),i((n-r.top)/(r.height||1))]}export function pointIn(t,e=[.5,.5]){const n=t.getBoundingClientRect();return{x:n.left+e[0]*n.width,y:n.top+e[1]*n.height}}
1
+ export const IGNORED="[data-demo-ignore]";const t=["button","a[href]","input","textarea","select","summary","canvas","video",'[contenteditable=""]','[contenteditable="true"]','[role="button"]','[role="link"]','[role="tab"]','[role="option"]','[role="menuitem"]','[role="menuitemcheckbox"]','[role="menuitemradio"]','[role="switch"]','[role="checkbox"]','[role="radio"]','[role="slider"]','[role="combobox"]','[role="treeitem"]','[role="gridcell"]','[role="row"]',"li[role]","[data-demo]"];function e(t){const e=t.getAttribute("aria-label");return e?normal(e):""}export function normal(t){return t.replace(/\s+/g," ").replace(/\d[\d.,]*/g,"#").trim().toLowerCase().slice(0,80)}export function dictionaryLabels(t,e){let n;const r=()=>{const e=t();if(n?.from===e)return n;const r=new Map,i=new Map,o=(t,e)=>Object.entries(t).forEach(([t,n])=>{const s=e+t;if("object"==typeof n&&n)o(n,s+".");else if("string"==typeof n&&!n.includes("{{")){const t=normal(n);r.set(t,r.has(t)?null:s),i.set(s,n)}});return o(e,""),n={from:e,keys:r,texts:i}};return{keyOf:t=>r().keys.get(normal(t))??void 0,textOf:t=>e?.(t)??r().texts.get(t)}}export class Targets{constructor(e={}){this.options=e,this.interactive=[...t,...e.interactive??[]].join(","),this.attributes=["aria-label","title",...e.labelAttributes??[]]}labelOf(t){const e=t,n=t.getAttribute("aria-labelledby")?.split(/\s+/).map(e=>t.ownerDocument.getElementById(e)?.textContent??"").join(" "),r=t.matches("input, select, textarea"),i=r?t.closest("label"):null,o=r?"":e.innerText?.trim()??"",s=t.getAttribute("data-demo")||(t instanceof HTMLInputElement&&["button","submit","reset"].includes(t.type)?t.value:"")||(/[\p{L}\p{N}]/u.test(o)?o:"")||n?.trim()||this.attributes.map(e=>t.getAttribute(e)).find(Boolean)||t.placeholder||t.alt||t.id&&t.ownerDocument.querySelector(`label[for="${CSS.escape(t.id)}"]`)?.textContent||i&&Array.from(i.childNodes).filter(t=>t.nodeType===Node.TEXT_NODE).map(t=>t.textContent).join(" ").trim()||t.name||o;if(s.trim())return normal(s);const a=t.querySelector("svg[data-testid], [data-icon]"),l=a?.getAttribute("data-testid")??a?.getAttribute("data-icon");if(l)return normal(l);let c=t.parentElement;for(let t=0;c&&t<4;t++,c=c.parentElement){const t=c.innerText??"";if(t.trim())return normal(t)}return""}cssOf(t){const e=t.tagName.toLowerCase(),n=t.getAttribute("role"),r="input"===e?t.getAttribute("type"):null,i=this.options.stableClass&&Array.from(t.classList).find(t=>this.options.stableClass.test(t));return e+(i?`.${CSS.escape(i)}`:"")+(n?`[role="${n}"]`:"")+(r?`[type="${r}"]`:"")}labelIn(t){if(t.key){const e=this.options.labels?.textOf(t.key);if(void 0!==e)return normal(e)}return void 0===t.text?void 0:normal(t.text)}targetElement(t){return!t||t.closest(IGNORED)?null:t.closest(this.interactive)??t}matches(t){const n=this.labelIn(t);let r;try{r=Array.from(document.querySelectorAll(t.css))}catch{return[]}return r.filter(t=>!t.closest(IGNORED)&&(void 0===n||this.labelOf(t)===n||e(t)===n))}describe(t){const i=this.cssOf(t),o=e(t),s=this.labelOf(t),a=o&&s.length>40?o:s,l=a&&!t.getAttribute("data-demo")?this.options.labels?.keyOf(a):void 0,c=t=>({css:t,...l?{key:l}:a?{text:a}:{}}),u=c(i);if(this.matches(u).length<=1)return u;for(let e=t.parentElement;e&&e!==document.body;e=e.parentElement){const o=r(e);if(!o)continue;const s=c(`${o} ${i}`),a=this.matches(s);if(1===a.length)return s;if(a.length>1)return{...s,...n(a,t)}}return{...u,...n(this.matches(u),t)}}async find(t,e=1e4,n=()=>!1){const r=performance.now()+e;do{const e=this.matches(t)[t.index??0];if(e&&shown(e))return e;await new Promise(t=>setTimeout(t,100))}while(performance.now()<r&&!n())}list({within:t,query:e,limit:n=400}={}){const r=t?Array.from(document.querySelectorAll(t)):[document.body],o=new Set,s=[],a=e?normal(e):void 0;for(const t of r)for(const e of Array.from(t.querySelectorAll(this.interactive))){if(s.length>=n)break;if(o.has(e)||e.closest(IGNORED)||!shown(e))continue;const r=e.parentElement?.closest(this.interactive);if(r&&!r.closest(IGNORED)&&t.contains(r)&&this.labelOf(r)===this.labelOf(e)&&!e.matches("input, select, textarea, canvas"))continue;o.add(e);const l=this.labelOf(e);if(a&&!l.includes(a))continue;const c=e.getBoundingClientRect();s.push({target:this.describe(e),label:l,tag:e.tagName.toLowerCase(),...e.getAttribute("role")?{role:e.getAttribute("role")}:{},...i(e),box:{x:Math.round(c.x),y:Math.round(c.y),width:Math.round(c.width),height:Math.round(c.height)}})}return s}}function n(t,e){const n=t.indexOf(e);return n>0?{index:n}:{}}function r(t){const e=t.getAttribute("data-demo");if(e)return`[data-demo="${e.replace(/"/g,'\\"')}"]`;const n=t.id;return n&&/^[a-z][\w-]*$/i.test(n)&&!/\d{3,}|[:]|^(mui|radix|react|headlessui|rc)-?/i.test(n)?`#${CSS.escape(n)}`:void 0}export function shown(t){const e=t.checkVisibility;if(e){if(!e.call(t,{checkVisibilityCSS:!0}))return!1;if(!e.call(t,{checkOpacity:!0,checkVisibilityCSS:!0})){const e=t.parentElement;if(!t.matches("input, select, textarea")||!e||!shown(e))return!1}}return t.getClientRects().length>0}function i(t){const e=[],n=t;t.matches("input[type=checkbox], input[type=radio]")?e.push(n.checked?"checked":"unchecked"):t.matches("input, textarea")?e.push(`value "${n.value.slice(0,60)}"`):t instanceof HTMLSelectElement&&e.push(`value "${t.selectedOptions[0]?.text??""}"`);for(const n of["aria-checked","aria-selected","aria-expanded","aria-pressed","aria-current"]){const r=t.getAttribute(n);r&&"false"!==r&&e.push(`${n.slice(5)}${"true"===r?"":`=${r}`}`)}return(t.disabled||"true"===t.getAttribute("aria-disabled"))&&e.push("disabled"),e.length?{state:e.join(", ")}:{}}export function fractionIn(t,e,n){const r=t.getBoundingClientRect(),i=t=>Math.round(1e3*t)/1e3;return[i((e-r.left)/(r.width||1)),i((n-r.top)/(r.height||1))]}export function pointIn(t,e=[.5,.5]){const n=t.getBoundingClientRect();return{x:n.left+e[0]*n.width,y:n.top+e[1]*n.height}}
package/store/Share.d.ts CHANGED
@@ -7,6 +7,8 @@ import type { Demo } from '../model/Demo';
7
7
  export declare function linkTo(demo: Demo, base?: string): Promise<string>;
8
8
  /** The demo a link brought, taken out of the address; none without one. */
9
9
  export declare function demoFromLink(): Promise<Demo | undefined>;
10
+ /** The demo in a link `linkTo` made; none in another. */
11
+ export declare function demoIn(link: string): Promise<Demo | undefined>;
10
12
  export declare function pack(value: object): Promise<string>;
11
13
  export declare function unpack(text: string): Promise<unknown>;
12
14
  /** Saved by the browser, as a file. */
package/store/Share.js CHANGED
@@ -1 +1 @@
1
- const e=/^#demo=(.+)$/;export async function linkTo(e,t=window.location.href){const n=new URL(t);return n.hash="demo="+await pack(e),n.toString()}export async function demoFromLink(){const t=window.location.hash.match(e);if(t){window.history.replaceState(window.history.state,"",window.location.pathname+window.location.search);try{return await unpack(t[1])}catch{return}}}export async function pack(e){const t=new Blob([JSON.stringify(e)]).stream().pipeThrough(new CompressionStream("deflate-raw")),n=new Uint8Array(await new Response(t).arrayBuffer());let o="";return n.forEach(e=>o+=String.fromCharCode(e)),btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}export async function unpack(e){const t=atob(e.replace(/-/g,"+").replace(/_/g,"/")),n=Uint8Array.from(t,e=>e.charCodeAt(0)),o=new Blob([n]).stream().pipeThrough(new DecompressionStream("deflate-raw"));return JSON.parse(await new Response(o).text())}export function download(e,t,n="text/plain"){const o="string"==typeof e?new Blob([e],{type:`${n};charset=utf-8`}):e,r=URL.createObjectURL(o),a=document.createElement("a");a.href=r,a.download=t,a.style.display="none",document.body.append(a),a.click(),a.remove(),setTimeout(()=>URL.revokeObjectURL(r),6e4)}export async function shareFiles(e,t,n){const o={files:e,title:t,...n?{text:n}:{}};if(!navigator.canShare?.(o))return!1;try{return await navigator.share(o),!0}catch{return!1}}export function fileName(e,t){return`${e.replace(/[\\/:*?"<>|]+/g,"").replace(/\s+/g," ").trim()||"demo"}.${t}`}export function pickFile(e=".json,application/json"){return new Promise(t=>{const n=document.createElement("input");n.type="file",n.accept=e,n.onchange=()=>t(n.files?.[0]),n.addEventListener("cancel",()=>t(void 0)),n.click()})}
1
+ const e=/^#demo=(.+)$/;export async function linkTo(e,t=window.location.href){const n=new URL(t);return n.hash="demo="+await pack(e),n.toString()}export async function demoFromLink(){if(!e.test(window.location.hash))return;const t=await demoIn(window.location.href);return window.history.replaceState(window.history.state,"",window.location.pathname+window.location.search),t}export async function demoIn(t){const n=t.replace(/^[^#]*/,"").match(e);if(n)try{return await unpack(n[1])}catch{return}}export async function pack(e){const t=new Blob([JSON.stringify(e)]).stream().pipeThrough(new CompressionStream("deflate-raw")),n=new Uint8Array(await new Response(t).arrayBuffer());let o="";return n.forEach(e=>o+=String.fromCharCode(e)),btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}export async function unpack(e){const t=atob(e.replace(/-/g,"+").replace(/_/g,"/")),n=Uint8Array.from(t,e=>e.charCodeAt(0)),o=new Blob([n]).stream().pipeThrough(new DecompressionStream("deflate-raw"));return JSON.parse(await new Response(o).text())}export function download(e,t,n="text/plain"){const o="string"==typeof e?new Blob([e],{type:`${n};charset=utf-8`}):e,r=URL.createObjectURL(o),a=document.createElement("a");a.href=r,a.download=t,a.style.display="none",document.body.append(a),a.click(),a.remove(),setTimeout(()=>URL.revokeObjectURL(r),6e4)}export async function shareFiles(e,t,n){const o={files:e,title:t,...n?{text:n}:{}};if(!navigator.canShare?.(o))return!1;try{return await navigator.share(o),!0}catch{return!1}}export function fileName(e,t){return`${e.replace(/[\\/:*?"<>|]+/g,"").replace(/\s+/g," ").trim()||"demo"}.${t}`}export function pickFile(e=".json,application/json"){return new Promise(t=>{const n=document.createElement("input");n.type="file",n.accept=e,n.onchange=()=>t(n.files?.[0]),n.addEventListener("cancel",()=>t(void 0)),n.click()})}
package/ui/Actions.js CHANGED
@@ -1 +1 @@
1
- import e,{useState as t}from"react";import{describeTarget as a}from"../engine/Player.js";import{BUILT_IN_KINDS as l,INTERACT_KINDS as o,isPresent as r,PRESENT_KINDS as n}from"../model/Demo.js";import{fractionIn as c}from"../page/Targets.js";import{Button as s,Check as i,JsonField as d,Labelled as m,Menu as p,NumberField as h}from"./Kit.js";const u={click:{do:"click",target:{css:"button",text:""}},hover:{do:"hover",target:{css:"button",text:""}},type:{do:"type",target:{css:"input"},text:""},key:{do:"key",key:"Escape"},select:{do:"select",target:{css:"select"},option:""},drag:{do:"drag",target:{css:'[role="slider"]'},to:{at:[1,.5]}},scroll:{do:"scroll",target:{css:"main"}},waitFor:{do:"waitFor",target:{css:'[role="dialog"]'}},spotlight:{do:"spotlight",target:{css:"main"}},ring:{do:"ring",target:{css:"button",text:""}},arrow:{do:"arrow",target:{css:"button",text:""},text:""},callout:{do:"callout",text:"A note",corner:"top-right"},blur:{do:"blur",target:{css:'input[type="email"]'}},card:{do:"card",title:"Title",text:"",for:3e3},zoom:{do:"zoom",target:{css:"main"},scale:1.8},clear:{do:"clear"}},g=new Set(["click","hover","type","select","drag","waitFor","spotlight","ring","arrow","blur","zoom"]);export function readAction(e,t){return e.read(t)}export function addActionItems(e,t){const a=e.pluginKinds(),l=a=>({label:a,onClick:()=>t(JSON.parse(JSON.stringify(e.pluginAction(a)?.template?.()??u[a]??{do:a})))});return[{heading:"Interact"},...o.map(l),{heading:"Present"},...n.map(l),...a.length?[{heading:"App"},...a.map(l)]:[]]}export function ActionRow({engine:o,action:n,index:u,count:v,open:k,error:E,sentences:y,onOpen:w,onChange:x,onMove:f,onDelete:C,onDuplicate:N,picking:T}){const[A,S]=t(),j=n,F=e=>{const t={...n,...e};Object.keys(e).forEach(e=>(void 0===t[e]||""===t[e]||!1===t[e])&&delete t[e]),x(t)},D=l.includes(n.do),B=r(n),O=(t,l,r="Target",n=!1)=>e.createElement("div",{className:"wide col"},e.createElement("div",{className:"row"},e.createElement("span",{className:"small muted",style:{width:52}},r),e.createElement(s,{icon:"pick",small:!0,title:"Pick it on the page",onClick:()=>{(async e=>{T(!0);const t=await o.overlay.pick(e=>o.targets.targetElement(e),e=>a(o.targets.describe(e)));if(T(!1),!t)return;const l=o.targets.describe(t.element),r=t.element.matches('canvas, video, [role="slider"], input[type="range"]')||j.at?c(t.element,t.x,t.y):void 0;F("to"===e?{to:{target:l,...r?{at:r}:{}}}:{target:l,...r?{at:r}:{}})})("To"===r?"to":"target")}}),e.createElement(s,{icon:"show",small:!0,title:"Show it on the page",disabled:!t,onClick:()=>(e=>{if(!e)return;const t=o.targets.matches(e),a=t[e.index??0];S(a?`${t.length} match${1===t.length?"":"es"}`:"Not found here now"),a&&(a.scrollIntoView({block:"nearest",inline:"nearest"}),o.overlay.flash(a))})(t)}),n&&t&&e.createElement(s,{icon:"close",small:!0,kind:"bare",title:"No target",onClick:()=>l(void 0)}),A&&e.createElement("span",{className:"small muted"},A)),t&&e.createElement("div",{className:"row"},e.createElement("input",{className:"field mono grow",title:"CSS selector",placeholder:"css",value:t.css,onChange:e=>l({...t,css:e.target.value})}),e.createElement("input",{className:"field",style:{width:"24%"},title:"Its label: what it shows. Digits match any.",placeholder:"text",value:t.text??"",onChange:e=>l(b({...t,text:e.target.value}))}),e.createElement("input",{className:"field mono",style:{width:"20%"},title:"Its label by the app's locale key: found in every language",placeholder:"key",value:t.key??"",onChange:e=>l(b({...t,key:e.target.value}))}),e.createElement(h,{value:t.index,width:52,placeholder:"#",title:"Which of the matches, from 0",onChange:e=>l(b({...t,index:e}))})),!t&&n&&e.createElement(s,{small:!0,onClick:()=>l({css:"button",text:""})},"Add a target")),P=(t,a)=>e.createElement(m,{label:a},e.createElement("select",{className:"field",value:j[t]??"",onChange:e=>F({[t]:e.target.value||void 0})},e.createElement("option",{value:""},"where there is room"),["top","right","bottom","left"].map(t=>e.createElement("option",{key:t,value:t},t)))),I=(t,a,l=!1)=>e.createElement(m,{label:a,className:l?"wide":void 0},e.createElement("input",{className:"field",value:j[t]??"",onChange:e=>F({[t]:e.target.value})})),$=(t,a,l)=>e.createElement(m,{label:a},e.createElement(h,{value:j[t],width:120,placeholder:l,onChange:e=>F({[t]:e})})),z=(t,a,l="At (x, y in its box)")=>e.createElement(m,{label:l},e.createElement("div",{className:"row"},e.createElement(h,{value:t?.[0],width:60,placeholder:"0.5",onChange:e=>a(void 0===e&&void 0===t?.[1]?void 0:[e??.5,t?.[1]??.5])}),e.createElement(h,{value:t?.[1],width:60,placeholder:"0.5",onChange:e=>a(void 0===e&&void 0===t?.[0]?void 0:[t?.[0]??.5,e??.5])})));return e.createElement("div",{className:["action",k&&"on",E&&"failed"].filter(Boolean).join(" ")},e.createElement("div",{className:"row"},e.createElement(s,{icon:k?"expand":"right",small:!0,kind:"bare",title:k?"Less":"Details",onClick:w}),e.createElement("span",{className:"kind"+(B?" present":"")},n.do),e.createElement("span",{className:"grow ellipsis",title:E??readAction(o,n),onClick:w,style:{cursor:"pointer"}},readAction(o,n),E&&e.createElement("span",{className:"error"}," - ",E)),e.createElement("span",{className:"small muted",title:"ms before it"},"wait"),e.createElement(h,{value:n.wait,width:58,placeholder:"800",title:"ms before it, 800 by default",onChange:e=>F({wait:e})}),e.createElement("select",{className:"field small",style:{width:74},title:"Starts with this sentence of the step's narration",value:n.cue??"",onChange:e=>F({cue:""===e.target.value?void 0:Number(e.target.value)})},e.createElement("option",{value:""},"no cue"),y.map((t,a)=>e.createElement("option",{key:a,value:a,title:t},`cue ${a+1}`)),void 0!==n.cue&&n.cue>=y.length&&e.createElement("option",{value:n.cue},`cue ${n.cue+1}?`)),e.createElement(s,{icon:"play",small:!0,kind:"bare",title:"Try it now",onClick:()=>{o.check({id:"test",title:"Test",steps:[{say:{},actions:[{...n,wait:0}],hold:B?2500:0}]},{speed:1}).then(e=>S(e.ok?"Played":e.failures[0]?.error??e.error))}}),e.createElement(p,{title:"More",items:[{label:"Earlier",icon:"up",disabled:0===u,onClick:()=>f(-1)},{label:"Later",icon:"down",disabled:u===v-1,onClick:()=>f(1)},{label:"Duplicate",icon:"duplicate",onClick:N},{label:"Delete",icon:"delete",onClick:C}]})),k&&e.createElement("div",{className:"details"},(()=>{if(!D){const{do:t,wait:a,cue:l,...o}=j;return e.createElement(m,{label:`${n.do}: its details`,className:"wide"},e.createElement(d,{rows:3,value:o,onChange:e=>e&&"object"==typeof e&&x({do:n.do,...void 0!==j.wait?{wait:j.wait}:{},...void 0!==j.cue?{cue:j.cue}:{},...e})}))}const t=[];switch("callout"===n.do||"key"===n.do||"scroll"===n.do?t.push(O(j.target,e=>F({target:e}),"Target",!0)):g.has(n.do)&&t.push(O(j.target,e=>e&&F({target:e}))),n.do){case"click":t.push(z(j.at,e=>F({at:e}))),t.push(e.createElement("div",{className:"row",key:"mods",style:{flexWrap:"wrap",gap:10}},e.createElement(i,{label:"double",checked:Boolean(j.double),onChange:e=>F({double:e})}),e.createElement(i,{label:"right",checked:Boolean(j.right),onChange:e=>F({right:e})}),["shift","ctrl","alt","meta"].map(t=>e.createElement(i,{key:t,label:t,checked:Boolean(j[t]),onChange:e=>F({[t]:e})}))));break;case"hover":t.push(z(j.at,e=>F({at:e})));break;case"type":t.push(I("text","Text",!0));break;case"key":t.push(I("key","Key or chord: 'Enter', 'Control+K'"));break;case"select":t.push(I("option","Option, by its text or value"));break;case"drag":t.push(z(j.at,e=>F({at:e}),"From (x, y in its box)")),t.push(O(j.to?.target,e=>F({to:b({...j.to,target:e})}),"To",!0)),t.push(z(j.to?.at,e=>F({to:b({...j.to,at:e})}),"To (x, y in its box)"));break;case"scroll":t.push(e.createElement(m,{label:"By (x, y px)",key:"by"},e.createElement(d,{value:j.by,onChange:e=>F({by:e})})));break;case"waitFor":t.push(e.createElement(i,{key:"gone",label:"till it is gone",checked:Boolean(j.gone),onChange:e=>F({gone:e})})),t.push($("timeout","Timeout ms","10000"));break;case"spotlight":t.push(I("text","Note",!0),$("padding","Padding px","8"));break;case"ring":t.push(I("text","Label"),I("color","Colour"),$("padding","Padding px","6")),t.push(e.createElement(m,{label:"Shape",key:"shape"},e.createElement("select",{className:"field",value:j.shape??"box",onChange:e=>F({shape:"box"===e.target.value?void 0:e.target.value})},e.createElement("option",null,"box"),e.createElement("option",null,"circle"))));break;case"arrow":t.push(I("text","Label"),P("from","From"),I("color","Colour"));break;case"callout":t.push(I("text","Text",!0),P("side","Side (with a target)")),t.push(e.createElement(m,{label:"Corner (without)",key:"corner"},e.createElement("select",{className:"field",value:j.corner??"",onChange:e=>F({corner:e.target.value||void 0})},e.createElement("option",{value:""},"top-right"),["top-left","top-right","bottom-left","bottom-right"].map(t=>e.createElement("option",{key:t},t)))));break;case"card":t.push(I("title","Title",!0),I("text","Text",!0));break;case"zoom":t.push($("scale","Scale","1.8"))}return B&&"clear"!==n.do&&t.push($("for","For ms (else the step)","the step")),t.map((t,a)=>e.createElement(e.Fragment,{key:a},t))})()))}function b(e){const t={};return Object.entries(e).forEach(([e,a])=>{void 0!==a&&""!==a&&(t[e]=a)}),t}export{u as TEMPLATES};
1
+ import e,{useState as t}from"react";import{describeTarget as a}from"../engine/Player.js";import{BUILT_IN_KINDS as l,INTERACT_KINDS as o,isPresent as r,PRESENT_KINDS as n}from"../model/Demo.js";import{fractionIn as c}from"../page/Targets.js";import{Button as s,Check as i,JsonField as m,Labelled as d,Menu as p,NumberField as u}from"./Kit.js";const h={click:{do:"click",target:{css:"button",text:""}},hover:{do:"hover",target:{css:"button",text:""}},type:{do:"type",target:{css:"input"},text:""},key:{do:"key",key:"Escape"},select:{do:"select",target:{css:"select"},option:""},drag:{do:"drag",target:{css:'[role="slider"]'},to:{at:[1,.5]}},scroll:{do:"scroll",target:{css:"main"}},waitFor:{do:"waitFor",target:{css:'[role="dialog"]'}},spotlight:{do:"spotlight",target:{css:"main"}},ring:{do:"ring",target:{css:"button",text:""}},arrow:{do:"arrow",target:{css:"button",text:""},text:""},callout:{do:"callout",text:"A note",corner:"top-right"},blur:{do:"blur",target:{css:'input[type="email"]'}},card:{do:"card",title:"Title",text:"",for:3e3},zoom:{do:"zoom",target:{css:"main"},scale:1.8},clear:{do:"clear"}},g=new Set(["click","hover","type","select","drag","waitFor","spotlight","ring","arrow","blur","zoom"]);export function readAction(e,t){return e.read(t)}export function addActionItems(e,t){const a=e.pluginKinds(),l=a=>({label:a,onClick:()=>t(JSON.parse(JSON.stringify(e.pluginAction(a)?.template?.()??h[a]??{do:a})))});return[{heading:"Interact"},...o.map(l),{heading:"Present"},...n.map(l),...a.length?[{heading:"App"},...a.map(l)]:[]]}export function ActionRow({engine:o,action:n,index:h,count:v,open:E,error:k,sentences:y,onOpen:w,onChange:f,onMove:x,onDelete:C,onDuplicate:N,picking:T}){const[j,A]=t(),S=n,F=e=>{const t={...n,...e};Object.keys(e).forEach(e=>(void 0===t[e]||""===t[e]||!1===t[e])&&delete t[e]),f(t)},O=l.includes(n.do),D=r(n),$=(t,l,r="Target",n=!1)=>e.createElement("div",{className:"wide col"},e.createElement("div",{className:"row"},e.createElement("span",{className:"small muted",style:{width:52}},r),e.createElement(s,{icon:"pick",small:!0,title:"Pick it on the page",onClick:()=>{(async e=>{T(!0);const t=await o.overlay.pick(e=>o.targets.targetElement(e),e=>a(o.targets.describe(e)));if(T(!1),!t)return;const l=o.targets.describe(t.element),r=t.element.matches('canvas, video, [role="slider"], input[type="range"]')||S.at?c(t.element,t.x,t.y):void 0;F("to"===e?{to:{target:l,...r?{at:r}:{}}}:{target:l,...r?{at:r}:{}})})("To"===r?"to":"target")}}),e.createElement(s,{icon:"show",small:!0,title:"Show it on the page",disabled:!t,onClick:()=>(e=>{if(!e)return;const t=o.targets.matches(e),a=t[e.index??0];A(a?`${t.length} match${1===t.length?"":"es"}`:"Not found here now"),a&&(a.scrollIntoView({block:"nearest",inline:"nearest"}),o.overlay.flash(a))})(t)}),n&&t&&e.createElement(s,{icon:"close",small:!0,kind:"bare",title:"No target",onClick:()=>l(void 0)}),j&&e.createElement("span",{className:"small muted"},j)),t&&e.createElement("div",{className:"row"},e.createElement("input",{className:"field mono grow",title:"CSS selector",placeholder:"css",value:t.css,onChange:e=>l({...t,css:e.target.value})}),e.createElement("input",{className:"field",style:{width:"24%"},title:"Its label: what it shows. Digits match any.",placeholder:"text",value:t.text??"",onChange:e=>l(b({...t,text:e.target.value}))}),e.createElement("input",{className:"field mono",style:{width:"20%"},title:"Its label by the app's locale key: found in every language",placeholder:"key",value:t.key??"",onChange:e=>l(b({...t,key:e.target.value}))}),e.createElement(u,{value:t.index,width:52,placeholder:"#",title:"Which of the matches, from 0",onChange:e=>l(b({...t,index:e}))})),!t&&n&&e.createElement(s,{small:!0,onClick:()=>l({css:"button",text:""})},"Add a target")),B=(t,a)=>e.createElement(d,{label:a},e.createElement("select",{className:"field",value:S[t]??"",onChange:e=>F({[t]:e.target.value||void 0})},e.createElement("option",{value:""},"where there is room"),["top","right","bottom","left"].map(t=>e.createElement("option",{key:t,value:t},t)))),P=(t,a,l=!1)=>e.createElement(d,{label:a,className:l?"wide":void 0},e.createElement("input",{className:"field",value:S[t]??"",onChange:e=>F({[t]:e.target.value})})),I=(t,a,l=!1)=>{const r=S[t],n=o.languages();return r&&"object"==typeof r?e.createElement(d,{label:`${a}, per language`,className:l?"wide":void 0},[...new Set([...n,...Object.keys(r)])].map(a=>e.createElement("div",{className:"row",key:a},e.createElement("span",{className:"small muted mono",style:{width:22}},a),e.createElement("input",{className:"field grow",value:r[a]??"",onChange:e=>F({[t]:{...r,[a]:e.target.value}})})))):e.createElement(d,{label:a,className:l?"wide":void 0},e.createElement("div",{className:"row"},e.createElement("input",{className:"field grow",value:r??"",onChange:e=>F({[t]:e.target.value})}),n.length>1&&e.createElement(s,{small:!0,kind:"bare",title:`A text for each language: ${n.join(", ")}`,onClick:()=>F({[t]:Object.fromEntries(n.map(e=>[e,r??""]))})},"per language")))},z=(t,a,l)=>e.createElement(d,{label:a},e.createElement(u,{value:S[t],width:120,placeholder:l,onChange:e=>F({[t]:e})})),K=(t,a,l="At (x, y in its box)")=>e.createElement(d,{label:l},e.createElement("div",{className:"row"},e.createElement(u,{value:t?.[0],width:60,placeholder:"0.5",onChange:e=>a(void 0===e&&void 0===t?.[1]?void 0:[e??.5,t?.[1]??.5])}),e.createElement(u,{value:t?.[1],width:60,placeholder:"0.5",onChange:e=>a(void 0===e&&void 0===t?.[0]?void 0:[t?.[0]??.5,e??.5])})));return e.createElement("div",{className:["action",E&&"on",k&&"failed"].filter(Boolean).join(" ")},e.createElement("div",{className:"row"},e.createElement(s,{icon:E?"expand":"right",small:!0,kind:"bare",title:E?"Less":"Details",onClick:w}),e.createElement("span",{className:"kind"+(D?" present":"")},n.do),e.createElement("span",{className:"grow ellipsis",title:k??readAction(o,n),onClick:w,style:{cursor:"pointer"}},readAction(o,n),k&&e.createElement("span",{className:"error"}," - ",k)),e.createElement("span",{className:"small muted",title:"ms before it"},"wait"),e.createElement(u,{value:n.wait,width:58,placeholder:"800",title:"ms before it, 800 by default",onChange:e=>F({wait:e})}),e.createElement("select",{className:"field small",style:{width:74},title:"Starts with this sentence of the step's narration",value:n.cue??"",onChange:e=>F({cue:""===e.target.value?void 0:Number(e.target.value)})},e.createElement("option",{value:""},"no cue"),y.map((t,a)=>e.createElement("option",{key:a,value:a,title:t},`cue ${a+1}`)),void 0!==n.cue&&n.cue>=y.length&&e.createElement("option",{value:n.cue},`cue ${n.cue+1}?`)),e.createElement(s,{icon:"play",small:!0,kind:"bare",title:"Try it now",onClick:()=>{o.check({id:"test",title:"Test",steps:[{say:{},actions:[{...n,wait:0}],hold:D?2500:0}]},{speed:1}).then(e=>A(e.ok?"Played":e.failures[0]?.error??e.error))}}),e.createElement(p,{title:"More",items:[{label:"Earlier",icon:"up",disabled:0===h,onClick:()=>x(-1)},{label:"Later",icon:"down",disabled:h===v-1,onClick:()=>x(1)},{label:"Duplicate",icon:"duplicate",onClick:N},{label:"Delete",icon:"delete",onClick:C}]})),E&&e.createElement("div",{className:"details"},(()=>{if(!O){const{do:t,wait:a,cue:l,...o}=S;return e.createElement(d,{label:`${n.do}: its details`,className:"wide"},e.createElement(m,{rows:3,value:o,onChange:e=>e&&"object"==typeof e&&f({do:n.do,...void 0!==S.wait?{wait:S.wait}:{},...void 0!==S.cue?{cue:S.cue}:{},...e})}))}const t=[];switch("callout"===n.do||"key"===n.do||"scroll"===n.do?t.push($(S.target,e=>F({target:e}),"Target",!0)):g.has(n.do)&&t.push($(S.target,e=>e&&F({target:e}))),n.do){case"click":t.push(K(S.at,e=>F({at:e}))),t.push(e.createElement("div",{className:"row",key:"mods",style:{flexWrap:"wrap",gap:10}},e.createElement(i,{label:"double",checked:Boolean(S.double),onChange:e=>F({double:e})}),e.createElement(i,{label:"right",checked:Boolean(S.right),onChange:e=>F({right:e})}),["shift","ctrl","alt","meta"].map(t=>e.createElement(i,{key:t,label:t,checked:Boolean(S[t]),onChange:e=>F({[t]:e})}))));break;case"hover":t.push(K(S.at,e=>F({at:e})));break;case"type":t.push(P("text","Text",!0));break;case"key":t.push(P("key","Key or chord: 'Enter', 'Control+K'"));break;case"select":t.push(P("option","Option, by its text or value"));break;case"drag":t.push(K(S.at,e=>F({at:e}),"From (x, y in its box)")),t.push($(S.to?.target,e=>F({to:b({...S.to,target:e})}),"To",!0)),t.push(K(S.to?.at,e=>F({to:b({...S.to,at:e})}),"To (x, y in its box)"));break;case"scroll":t.push(e.createElement(d,{label:"By (x, y px)",key:"by"},e.createElement(m,{value:S.by,onChange:e=>F({by:e})})));break;case"waitFor":t.push(e.createElement(i,{key:"gone",label:"till it is gone",checked:Boolean(S.gone),onChange:e=>F({gone:e})})),t.push(z("timeout","Timeout ms","10000"));break;case"spotlight":t.push(I("text","Note",!0),z("padding","Padding px","8"));break;case"ring":t.push(I("text","Label"),P("color","Colour"),z("padding","Padding px","6")),t.push(e.createElement(d,{label:"Shape",key:"shape"},e.createElement("select",{className:"field",value:S.shape??"box",onChange:e=>F({shape:"box"===e.target.value?void 0:e.target.value})},e.createElement("option",null,"box"),e.createElement("option",null,"circle"))));break;case"arrow":t.push(I("text","Label"),B("from","From"),P("color","Colour"));break;case"callout":t.push(I("text","Text",!0),B("side","Side (with a target)")),t.push(e.createElement(d,{label:"Corner (without)",key:"corner"},e.createElement("select",{className:"field",value:S.corner??"",onChange:e=>F({corner:e.target.value||void 0})},e.createElement("option",{value:""},"top-right"),["top-left","top-right","bottom-left","bottom-right"].map(t=>e.createElement("option",{key:t},t)))));break;case"card":t.push(I("title","Title",!0),I("text","Text",!0));break;case"zoom":t.push(z("scale","Scale","1.8"))}return D&&"clear"!==n.do&&t.push(z("for","For ms (else the step)","the step")),t.map((t,a)=>e.createElement(e.Fragment,{key:a},t))})()))}function b(e){const t={};return Object.entries(e).forEach(([e,a])=>{void 0!==a&&""!==a&&(t[e]=a)}),t}export{h as TEMPLATES};
package/ui/EngineUI.js CHANGED
@@ -1 +1 @@
1
- import e,{useEffect as t}from"react";import{createRoot as a}from"react-dom/client";import{useEngine as n}from"./Hooks.js";import{Button as i,Icon as l,Menu as o,useTheme as s}from"./Kit.js";import{Library as r}from"./Library.js";import{AssistantPanel as m}from"./Assistant.js";import{Dialog as c}from"./Dialogs.js";import{Studio as d}from"./Studio.js";import{UI_CSS as p}from"./Styles.js";export function mountUI(t){t.overlay.addStyles(p);const n=a(t.overlay.ui);return n.render(e.createElement(u,{engine:t})),()=>n.unmount()}function u({engine:t}){const a=n(t),p=s(t.options.theme??"dark"),{session:u}=a,E="playing"===u.mode&&(u.filming&&!u.paused||u.looping)||"recording"===u.mode&&u.filming;return e.createElement(e.Fragment,null,"ready"===u.mode&&e.createElement("div",{className:"pde ready","data-theme":p,onClick:e=>e.target===e.currentTarget&&u.cancel()},e.createElement("div",{className:"box"},e.createElement(i,{icon:"Film"===u.verb?"film":"Record"===u.verb?"record":"play",kind:"primary",autoFocus:!0,onClick:u.go},u.verb," “",u.title,"”"),e.createElement("div",{className:"small muted"},"A click here, in the app's window, lets it speak","Play"===u.verb?"":" and be filmed","."),e.createElement(i,{kind:"bare",onClick:u.cancel},"Cancel"))),"preparing"===u.mode&&e.createElement("div",{className:"pde bar","data-theme":p},e.createElement("span",null,u.title),e.createElement("span",{className:"muted"},u.text),void 0!==a.speech.loading&&e.createElement("span",{className:"muted"},Math.round(100*a.speech.loading)," %"),e.createElement(i,{icon:"stop",small:!0,kind:"bare",title:"Stop",onClick:()=>t.stop()})),"playing"===u.mode&&!u.checking&&!E&&e.createElement("div",{className:"pde bar","data-theme":p},u.filming&&e.createElement("span",{className:"dot",title:"Filming: paused time is left out"}),e.createElement("span",{className:"ellipsis",style:{maxWidth:320}},u.title),!u.filming&&e.createElement(i,{icon:"back",small:!0,kind:"bare",title:"Back: this step again; pressed early, the one before (←, PageUp)",onClick:()=>t.back()}),u.filming?e.createElement("span",{className:"muted"},`${u.step+1} / ${u.steps}`):e.createElement(o,{title:"Go to a step (1-9, Home, End)",icon:"expand",label:e.createElement("span",{className:"muted"},u.catchingUp?`… ${u.step+1}`:`${u.step+1} / ${u.steps}`),align:"left",items:u.demo.steps.map((a,n)=>({label:e.createElement("span",{style:{fontWeight:n===u.step?700:400}},`${n+1}. ${a.title??(Object.values(a.say).find(Boolean)??"").slice(0,48)}`),onClick:()=>t.goTo(n)}))}),void 0!==a.speech.loading&&e.createElement("span",{className:"muted small",title:"Downloaded once, then kept by the browser: subtitles meanwhile"},"voice ",Math.round(100*a.speech.loading)," %"),a.hint&&e.createElement("span",{className:"small",style:{color:"var(--accent)"}},a.hint),u.paused&&!u.waiting&&!a.hint&&e.createElement("span",{className:"muted small",title:"What you do now, the demo goes on from"},"paused: the app is yours"),u.guided&&u.instruction&&e.createElement("span",{className:"ellipsis",style:{maxWidth:360,fontWeight:600}},u.instruction),u.guided&&u.instruction&&e.createElement(i,{icon:"flash",title:"The demo does it",onClick:()=>t.doItForMe()},"Do it for me"),e.createElement(i,{icon:u.paused?"play":"pause",kind:u.paused?"primary":void 0,title:"Space",onClick:()=>u.waiting?t.next():t.togglePause()},u.waiting?"Continue":u.paused?"Resume":"Pause"),!u.waiting&&e.createElement(i,{icon:"right",title:"Next step (→, PageDown)",onClick:()=>t.next()}),u.presenting&&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()},u.guided?"Exit":"Stop")),a.loop?.visitor&&e.createElement("div",{className:"pde bar","data-theme":p,style:{top:"auto",bottom:12,left:"auto",right:12,transform:"none",padding:"4px 6px 4px 12px",opacity:.85}},e.createElement(l,{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"===u.mode&&e.createElement(g,{engine:t,theme:p,filmed:u.filming}),a.message&&"idle"===u.mode&&e.createElement(h,{engine:t,theme:p,text:a.message.text,error:a.message.error}),a.studio&&!E&&e.createElement(d,{key:a.studio.opened,engine:t,theme:p}),a.assistant.open&&!1!==t.options.assistant&&("idle"===u.mode||"playing"===u.mode&&u.checking)&&e.createElement(m,{engine:t,theme:p}),t.options.launcher&&"idle"===u.mode&&!a.loop&&!a.studio&&e.createElement(e.Fragment,null,e.createElement("div",{className:"pde launcher","data-theme":p},e.createElement(i,{kind:a.library?"primary":void 0,onClick:()=>t.showLibrary(a.library?void 0:"demos")},e.createElement(l,{name:"demos"}),"Demos")),a.library&&e.createElement(r,{engine:t,theme:p,floating:!0})),a.dialog&&"idle"===u.mode&&e.createElement(c,{engine:t,request:a.dialog,theme:p}))}function g({engine:t,theme:a,filmed:l}){const{session:o}=n(t);return"recording"!==o.mode?null:l?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 h({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}from"react";import{createRoot as a}from"react-dom/client";import{useEngine as n}from"./Hooks.js";import{Button as i,Icon as l,Menu as o,useTheme as s}from"./Kit.js";import{Library as r}from"./Library.js";import{AssistantPanel as m}from"./Assistant.js";import{Dialog as c}from"./Dialogs.js";import{Studio as d}from"./Studio.js";import{UI_CSS as p}from"./Styles.js";export function mountUI(t){t.overlay.addStyles(p);const n=a(t.overlay.ui);return n.render(e.createElement(u,{engine:t})),()=>n.unmount()}function u({engine:t}){const a=n(t),p=s(t.options.theme??"dark"),{session:u}=a,E="playing"===u.mode&&(u.filming&&!u.paused||u.looping)||"recording"===u.mode&&u.filming;return e.createElement(e.Fragment,null,"ready"===u.mode&&e.createElement("div",{className:"pde ready","data-theme":p,onClick:e=>e.target===e.currentTarget&&u.cancel()},e.createElement("div",{className:"box"},e.createElement(i,{icon:"Film"===u.verb?"film":"Record"===u.verb?"record":"play",kind:"primary",autoFocus:!0,onClick:u.go},u.verb," “",u.title,"”"),e.createElement("div",{className:"small muted"},"A click here, in the app's window, lets it speak","Play"===u.verb?"":" and be filmed","."),e.createElement(i,{kind:"bare",onClick:u.cancel},"Cancel"))),"preparing"===u.mode&&e.createElement("div",{className:"pde bar","data-theme":p},e.createElement("span",null,u.title),e.createElement("span",{className:"muted"},u.text),void 0!==a.speech.loading&&e.createElement("span",{className:"muted"},Math.round(100*a.speech.loading)," %"),e.createElement(i,{icon:"stop",small:!0,kind:"bare",title:"Stop",onClick:()=>t.stop()})),"playing"===u.mode&&!u.checking&&!E&&e.createElement("div",{className:"pde bar","data-theme":p},u.filming&&e.createElement("span",{className:"dot",title:"Filming: paused time is left out"}),e.createElement("span",{className:"ellipsis",style:{maxWidth:320}},u.title),!u.filming&&e.createElement(i,{icon:"back",small:!0,kind:"bare",title:"Back: this step again; pressed early, the one before (←, PageUp)",onClick:()=>t.back()}),u.filming?e.createElement("span",{className:"muted"},`${u.step+1} / ${u.steps}`):e.createElement(o,{title:"Go to a step (1-9, Home, End)",icon:"expand",label:e.createElement("span",{className:"muted"},u.catchingUp?`… ${u.step+1}`:`${u.step+1} / ${u.steps}`),align:"left",items:u.demo.steps.map((a,n)=>({label:e.createElement("span",{style:{fontWeight:n===u.step?700:400}},`${n+1}. ${a.title??(Object.values(a.say).find(Boolean)??"").slice(0,48)}`),onClick:()=>t.goTo(n)}))}),void 0!==a.speech.loading&&e.createElement("span",{className:"muted small",title:"Downloaded once, then kept by the browser: subtitles meanwhile"},"voice ",Math.round(100*a.speech.loading)," %"),a.hint&&e.createElement("span",{className:"small",style:{color:"var(--accent)"}},a.hint),u.paused&&!u.waiting&&!a.hint&&e.createElement("span",{className:"muted small",title:"What you do now, the demo goes on from"},"paused: the app is yours"),u.guided&&u.instruction&&e.createElement("span",{className:"ellipsis",style:{maxWidth:360,fontWeight:600}},u.instruction),u.guided&&u.instruction&&e.createElement(i,{icon:"flash",title:"The demo does it",onClick:()=>t.doItForMe()},"Do it for me"),e.createElement(i,{icon:u.paused?"play":"pause",kind:u.paused?"primary":void 0,title:"Space",onClick:()=>u.waiting?t.next():t.togglePause()},u.waiting?"Continue":u.paused?"Resume":"Pause"),!u.waiting&&e.createElement(i,{icon:"right",title:"Next step (→, PageDown)",onClick:()=>t.next()}),u.presenting&&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()},u.guided?"Exit":"Stop")),a.loop?.visitor&&e.createElement("div",{className:"pde bar","data-theme":p,style:{top:"auto",bottom:12,left:"auto",right:12,transform:"none",padding:"4px 6px 4px 12px",opacity:.85}},e.createElement(l,{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"===u.mode&&e.createElement(g,{engine:t,theme:p,filmed:u.filming}),a.message&&"idle"===u.mode&&e.createElement(h,{engine:t,theme:p,text:a.message.text,error:a.message.error}),a.studio&&!E&&e.createElement(d,{key:a.studio.opened,engine:t,theme:p}),a.assistant.open&&!0===t.options.assistant&&("idle"===u.mode||"playing"===u.mode&&u.checking)&&e.createElement(m,{engine:t,theme:p}),t.options.launcher&&"idle"===u.mode&&!a.loop&&!a.studio&&e.createElement(e.Fragment,null,e.createElement("div",{className:"pde launcher","data-theme":p},e.createElement(i,{kind:a.library?"primary":void 0,onClick:()=>t.showLibrary(a.library?void 0:"demos")},e.createElement(l,{name:"demos"}),"Demos")),a.library&&e.createElement(r,{engine:t,theme:p,floating:!0})),a.dialog&&"idle"===u.mode&&e.createElement(c,{engine:t,request:a.dialog,theme:p}))}function g({engine:t,theme:a,filmed:l}){const{session:o}=n(t);return"recording"!==o.mode?null:l?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 h({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 o}from"react";import{createPortal as l}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{pickFile as m}from"../store/Share.js";import{useDemos as d,useEngine as p}from"./Hooks.js";import{Button as g,Check as h,Icon as u,Labelled as E,Menu as k,Segmented as b,useTheme as v}from"./Kit.js";import{Flagged as y}from"./Flag.js";import{VideoLook as w}from"./Dialogs.js";import{UI_CSS as f}from"./Styles.js";const C=[["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=v(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]=o();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=f,t.append(a)}r(t)},[]),e.createElement("div",{ref:i,"data-demo-ignore":!0,style:{display:"contents"}},s&&l(t,s))}export function Library({engine:t,theme:a,floating:n}){const o=p(t),l=d(t),i="idle"!==o.session.mode,s=o.library??"demos",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"settings"===s?e.createElement("div",{className:"pde library"+(n?" floating":""),"data-theme":a,"data-demo-ignore":!0},e.createElement("div",{className:"row"},e.createElement(g,{icon:"back",kind:"bare",title:"Back to the demos",onClick:()=>t.showLibrary(n?"demos":void 0)}),e.createElement("h2",{className:"grow"},"Settings")),e.createElement(Settings,{engine:t})):e.createElement("div",{className:"pde library"+(n?" floating":""),"data-theme":a,"data-demo-ignore":!0},e.createElement("div",{className:"row"},e.createElement("h2",{className:"grow"},"Demos"),o.loop&&e.createElement(g,{small:!0,icon:"stop",onClick:()=>t.stopLoop()},"Stop the loop"),e.createElement(k,{title:"Make a demo",icon:"add",label:"New",items:[!1!==t.options.assistant&&{label:"Ask Claude: say what it should show",icon:"spark",onClick:()=>t.openAssistant()},{label:"Record one: do it on the page",icon:"record",disabled:i,onClick:()=>t.openDialog({kind:"record"})},{label:"Start empty, in the studio",icon:"edit",onClick:()=>t.openStudio(t.create())},{label:"Import a .demo.json",icon:"upload",onClick:()=>{m().then(e=>e?.text()).then(e=>{if(e)return r(e)})}},{label:"Paste its JSON",icon:"copy",onClick:()=>{navigator.clipboard.readText().then(r,()=>t.say("Could not read the clipboard",!0))}}]}),e.createElement(g,{icon:"tune",kind:"bare",title:"Settings: voices, languages, subtitles",onClick:()=>t.openSettings()})),o.message&&e.createElement("div",{className:"small "+(o.message.error?"error":"muted")},o.message.text),0===l.length&&e.createElement("div",{className:"small muted"},!1!==t.options.assistant?"None yet: New → Ask Claude, or record one.":"None yet: record one (New)."),l.map(a=>e.createElement(N,{key:a.demo.id,engine:t,entry:a,busy:i})),l.length>1&&e.createElement(g,{kind:"bare",icon:"loop",disabled:i,onClick:()=>t.openDialog({kind:"loop",demos:l.map(e=>e.demo)})},"Loop them all at a booth…"))}function N({engine:t,entry:a,busy:n}){const{demo:o,origin:l,video:s}=a,r=i(t.timing(o).duration);return e.createElement("div",{className:"demo"},e.createElement("div",{className:"row"},e.createElement("span",{className:"title grow ellipsis",title:o.description},o.title),"app"!==l&&e.createElement("span",{className:"badge"},"edited"===l?"edited here":"made here")),o.description&&e.createElement("div",{className:"small muted"},o.description),e.createElement("div",{className:"small muted"},o.steps.length," steps · ~",r,t.languagesOf(o).length?` · ${t.languagesOf(o).join(", ")}`:""),e.createElement("div",{className:"row"},e.createElement(g,{icon:"play",small:!0,kind:"primary",disabled:n,onClick:()=>{t.play(o)}},"Play"),e.createElement(g,{icon:"present",small:!0,disabled:n,title:"Step by step, the presenter’s screen beside it",onClick:()=>t.present(o)},"Present"),e.createElement(g,{icon:"guide",small:!0,disabled:n,title:"The viewer does each step: a tutorial",onClick:()=>{t.guide(o)}},"Guide"),e.createElement("span",{className:"grow"}),e.createElement(g,{icon:"edit",small:!0,kind:"bare",title:"Edit in the studio",onClick:()=>t.openStudio(o)}),e.createElement(k,{title:"More",items:[{label:"Film a video…",icon:"film",disabled:n,onClick:()=>t.openDialog({kind:"film",demo:o})},{label:"Loop at a booth…",icon:"loop",disabled:n,onClick:()=>t.openDialog({kind:"loop",demos:[o]})},s&&{label:"The video’s subtitles .srt",icon:"subtitles",onClick:()=>t.downloadVideo(s,o.title,"srt")},s&&{label:"Share the video…",icon:"share",onClick:()=>{t.shareVideo(s,o.title).then(e=>!e&&t.say("No share sheet here: download it instead."))}},{heading:"Share the demo"},{label:"Copy a link with the demo",icon:"link",onClick:()=>{t.link(o).then(e=>navigator.clipboard.writeText(e)).then(()=>t.say("Link copied."))}},{label:"Download .demo.json",icon:"download",onClick:()=>t.downloadDemo(o)},{label:"Download scenario .md",icon:"download",onClick:()=>t.downloadDemo({...o,scenario:a.scenario},"md")},{label:"Narration pack (.zip)",icon:"listen",onClick:()=>{t.downloadPack(o)}},{heading:"This demo"},{label:"Clone",icon:"duplicate",onClick:()=>t.openStudio({...JSON.parse(JSON.stringify(o)),id:t.create(o.title).id,title:`${o.title} (copy)`})},!1!==t.options.assistant&&{label:"Ask Claude about it: change, clone, translate",icon:"spark",onClick:()=>t.openAssistant(o)},"edited"===l&&{label:"Revert to the app’s version",icon:"undo",onClick:()=>window.confirm("Drop the changes kept here?")&&void t.remove(o.id)},"here"===l&&{label:"Delete",icon:"delete",onClick:()=>window.confirm(`Delete "${o.title}"?`)&&void t.remove(o.id)}]})),s&&e.createElement("div",{className:"row video-line"},e.createElement(u,{name:"film"}),e.createElement(w,{video:s}),e.createElement("span",{className:"grow small muted ellipsis",title:new Date(s.at).toLocaleString()},new Date(s.at).toLocaleDateString(),s.json!==JSON.stringify(o)&&s.json!==JSON.stringify({...o,scenario:void 0})?" · older version":""),e.createElement(g,{icon:"play",small:!0,kind:"bare",title:"Watch",onClick:()=>t.openDialog({kind:"video",demo:o,video:s})}),e.createElement(g,{icon:"download",small:!0,kind:"bare",title:s.look?.subtitles?"Download":"Download, with its subtitles beside it",onClick:()=>{t.downloadVideo(s,o.title),s.look?.subtitles||t.downloadVideo(s,o.title,"vtt")}}),e.createElement(g,{icon:"delete",small:!0,kind:"bare",title:"Delete the video",onClick:()=>{window.confirm("Delete this video?")&&t.store.deleteVideo(s.id)}})))}export function Settings({engine:t}){const{settings:a,speech:n}=p(t),o=a.speech.voice,l=t.language(),i=e=>t.changeSettings({speech:{...a.speech,...e}});return e.createElement(e.Fragment,null,e.createElement("section",{className:"section"},e.createElement("h3",null,"Voice"),e.createElement(b,{value:o,onChange:e=>i({voice:e}),options:C.map(([e,t,a])=>[e,t,a])}),"free"===o&&e.createElement(S,{engine:t}),"elevenlabs"===o&&e.createElement(D,{engine:t}),"system"===o&&e.createElement(L,{engine:t,language:l}),e.createElement(E,{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)})})),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)),e.createElement("section",{className:"section"},e.createElement("h3",null,"Language and subtitles"),e.createElement(E,{label:"Narration in"},e.createElement(b,{value:a.language,onChange:e=>t.changeSettings({language:e}),options:[["page",e.createElement(y,{key:"page",language:"page"},"The page's"),`The page's language: ${t.options.language?.()??l} now`],...t.languages().map(t=>[t,e.createElement(y,{key:t,language:t})])]})),e.createElement(h,{label:"Subtitles",checked:a.subtitles,onChange:e=>t.changeSettings({subtitles:e})}),e.createElement(h,{label:"A 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("section",{className:"section"},e.createElement("h3",null,"Playing from a step"),e.createElement(h,{label:"Earlier steps first, quickly: the app where the step expects it",checked:a.catchUp,onChange:e=>t.changeSettings({catchUp:e})})),e.createElement("div",{className:"small muted"},"Playing: Space pauses, → or PageDown goes on, ← or PageUp goes back, 1-9 a step, Esc stops. Videos, recordings, booths and presentations ask what they need as they start."))}function S({engine:a}){const{settings:n}=p(a),[l,i]=o([]);return t(()=>{c().then(i,()=>i([]))},[]),e.createElement("div",{className:"col"},a.languages().map(t=>{const o=a.speech.freeVoice(t)??"",i=t.split(/[-_]/)[0],s=l.filter(e=>e.language.split("_")[0]===i);return e.createElement(E,{key:t,label:`Voice for ${t}`},e.createElement("select",{className:"field",value:o,onChange:e=>a.changeSettings({speech:{...n.speech,free:{...n.speech.free,[t]:e.target.value}}})},!o&&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"},o.startsWith("piper:")&&!s.some(e=>`piper:${e.id}`===o)&&e.createElement("option",{value:o},o.slice(6)),s.map(t=>e.createElement("option",{key:t.id,value:`piper:${t.id}`},t.name)))))}))}function D({engine:a}){const{settings:n}=p(a),{key:l,voices:i={}}=n.speech.elevenlabs,[r,c]=o([]),m=e=>a.changeSettings({speech:{...n.speech,elevenlabs:{...n.speech.elevenlabs,...e}}});t(()=>{l&&s(l).then(c,()=>c([]))},[l]);const d=a.languages();return e.createElement("div",{className:"col"},e.createElement(E,{label:"API key, kept in this browser"},e.createElement("input",{className:"field",type:"password",autoComplete:"off",value:l,onChange:e=>m({key:e.target.value.trim()})})),r.length>0&&d.map((t,n)=>{const o=a.speech.elevenLabsVoice(t),l=t.toLowerCase().split(/[-_]/)[0],s=r.filter(e=>e.languages.includes(l)),c=r.filter(e=>!e.languages.includes(l)),d=function(e){try{return new Intl.DisplayNames(["en"],{type:"language"}).of(e)??e}catch{return e}}(l);return e.createElement(E,{key:t,label:`Voice for ${d}`},e.createElement("select",{className:"field",value:o,onChange:e=>m({voices:{...i,[t]:e.target.value},...0===n?{voice:e.target.value}:{}})},!r.some(e=>e.id===o)&&e.createElement("option",{value:o},o),s.length>0&&e.createElement("optgroup",{label:`Checked for ${d}`},s.map(t=>e.createElement("option",{key:t.id,value:t.id},t.name))),e.createElement("optgroup",{label:s.length>0?"Other voices: they speak it too":`Every voice speaks ${d}`},c.map(t=>e.createElement("option",{key:t.id,value:t.id},t.name)))))}))}function L({engine:a,language:n}){const{settings:l}=p(a),[i,s]=o(()=>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(E,{label:`Voice for ${n}`},e.createElement("select",{className:"field",value:l.speech.system[n]??"",onChange:e=>a.changeSettings({speech:{...l.speech,system:{...l.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))))}
1
+ import e,{useEffect as t,useLayoutEffect as a,useRef as n,useState as o}from"react";import{createPortal as l}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{pickFile as m}from"../store/Share.js";import{useDemos as d,useEngine as p}from"./Hooks.js";import{Button as g,Check as h,Icon as u,Labelled as k,Menu as b,Segmented as E,useTheme as v}from"./Kit.js";import{Flagged as y}from"./Flag.js";import{VideoLook as w}from"./Dialogs.js";import{UI_CSS as f}from"./Styles.js";const C=[["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=v(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]=o();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=f,t.append(a)}r(t)},[]),e.createElement("div",{ref:i,"data-demo-ignore":!0,style:{display:"contents"}},s&&l(t,s))}export function Library({engine:t,theme:a,floating:n}){const o=p(t),l=d(t),i="idle"!==o.session.mode,s=o.library??"demos",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"settings"===s?e.createElement("div",{className:"pde library"+(n?" floating":""),"data-theme":a,"data-demo-ignore":!0},e.createElement("div",{className:"row"},e.createElement(g,{icon:"back",kind:"bare",title:"Back to the demos",onClick:()=>t.showLibrary(n?"demos":void 0)}),e.createElement("h2",{className:"grow"},"Settings")),e.createElement(Settings,{engine:t})):e.createElement("div",{className:"pde library"+(n?" floating":""),"data-theme":a,"data-demo-ignore":!0},e.createElement("div",{className:"row"},e.createElement("h2",{className:"grow"},"Demos"),o.loop&&e.createElement(g,{small:!0,icon:"stop",onClick:()=>t.stopLoop()},"Stop the loop"),e.createElement(b,{title:"Make a demo",icon:"add",label:"New",items:[Boolean(t.agentName())&&{label:"With your own Claude: copy a prompt for it",icon:"spark",onClick:()=>{N(t)}},!0===t.options.assistant&&{label:"Ask Claude: say what it should show",icon:"spark",onClick:()=>t.openAssistant()},{label:"Record one: do it on the page",icon:"record",disabled:i,onClick:()=>t.openDialog({kind:"record"})},{label:"Start empty, in the studio",icon:"edit",onClick:()=>t.openStudio(t.create())},{label:"Import a .demo.json",icon:"upload",onClick:()=>{m().then(e=>e?.text()).then(e=>{if(e)return r(e)})}},{label:"Paste its JSON",icon:"copy",onClick:()=>{navigator.clipboard.readText().then(r,()=>t.say("Could not read the clipboard",!0))}}]}),e.createElement(g,{icon:"tune",kind:"bare",title:"Settings: voices, languages, subtitles",onClick:()=>t.openSettings()})),o.message&&e.createElement("div",{className:"small "+(o.message.error?"error":"muted")},o.message.text),0===l.length&&e.createElement("div",{className:"small muted"},t.agentName()?"None yet: New → have your own Claude make one, or record one.":"None yet: record one (New)."),l.map(a=>e.createElement(S,{key:a.demo.id,engine:t,entry:a,busy:i})),l.length>1&&e.createElement(g,{kind:"bare",icon:"loop",disabled:i,onClick:()=>t.openDialog({kind:"loop",demos:l.map(e=>e.demo)})},"Loop them all at a booth…"))}async function N(e,t){const a=await e.claudePrompt(t);a&&await navigator.clipboard.writeText(a).then(()=>e.say("Copied: paste it into your Claude and say what you want, at its end."),()=>e.say("Could not copy to the clipboard",!0))}function S({engine:t,entry:a,busy:n}){const{demo:o,origin:l,video:s}=a,r=i(t.timing(o).duration);return e.createElement("div",{className:"demo"},e.createElement("div",{className:"row"},e.createElement("span",{className:"title grow ellipsis",title:o.description},o.title),"app"!==l&&e.createElement("span",{className:"badge"},"edited"===l?"edited here":"made here")),o.description&&e.createElement("div",{className:"small muted"},o.description),e.createElement("div",{className:"small muted"},o.steps.length," steps · ~",r,t.languagesOf(o).length?` · ${t.languagesOf(o).join(", ")}`:""),e.createElement("div",{className:"row"},e.createElement(g,{icon:"play",small:!0,kind:"primary",disabled:n,onClick:()=>{t.play(o)}},"Play"),e.createElement(g,{icon:"present",small:!0,disabled:n,title:"Step by step, the presenter’s screen beside it",onClick:()=>t.present(o)},"Present"),e.createElement(g,{icon:"guide",small:!0,disabled:n,title:"The viewer does each step: a tutorial",onClick:()=>{t.guide(o)}},"Guide"),e.createElement("span",{className:"grow"}),e.createElement(g,{icon:"edit",small:!0,kind:"bare",title:"Edit in the studio",onClick:()=>t.openStudio(o)}),e.createElement(b,{title:"More",items:[{label:"Film a video…",icon:"film",disabled:n,onClick:()=>t.openDialog({kind:"film",demo:o})},{label:"Loop at a booth…",icon:"loop",disabled:n,onClick:()=>t.openDialog({kind:"loop",demos:[o]})},s&&{label:"The video’s subtitles .srt",icon:"subtitles",onClick:()=>t.downloadVideo(s,o.title,"srt")},s&&{label:"Share the video…",icon:"share",onClick:()=>{t.shareVideo(s,o.title).then(e=>!e&&t.say("No share sheet here: download it instead."))}},{heading:"Share the demo"},{label:"Copy a link with the demo",icon:"link",onClick:()=>{t.link(o).then(e=>navigator.clipboard.writeText(e)).then(()=>t.say("Link copied."))}},{label:"Download .demo.json",icon:"download",onClick:()=>t.downloadDemo(o)},{label:"Download scenario .md",icon:"download",onClick:()=>t.downloadDemo({...o,scenario:a.scenario},"md")},{label:"Narration pack (.zip)",icon:"listen",onClick:()=>{t.downloadPack(o)}},{heading:"This demo"},{label:"Clone",icon:"duplicate",onClick:()=>t.openStudio({...JSON.parse(JSON.stringify(o)),id:t.create(o.title).id,title:`${o.title} (copy)`})},Boolean(t.agentName())&&{label:"Change it with your own Claude: copy a prompt",icon:"spark",onClick:()=>{N(t,o)}},!0===t.options.assistant&&{label:"Ask Claude about it: change, clone, translate",icon:"spark",onClick:()=>t.openAssistant(o)},"edited"===l&&{label:"Revert to the app’s version",icon:"undo",onClick:()=>window.confirm("Drop the changes kept here?")&&void t.remove(o.id)},"here"===l&&{label:"Delete",icon:"delete",onClick:()=>window.confirm(`Delete "${o.title}"?`)&&void t.remove(o.id)}]})),s&&e.createElement("div",{className:"row video-line"},e.createElement(u,{name:"film"}),e.createElement(w,{video:s}),e.createElement("span",{className:"grow small muted ellipsis",title:new Date(s.at).toLocaleString()},new Date(s.at).toLocaleDateString(),s.json!==JSON.stringify(o)&&s.json!==JSON.stringify({...o,scenario:void 0})?" · older version":""),e.createElement(g,{icon:"play",small:!0,kind:"bare",title:"Watch",onClick:()=>t.openDialog({kind:"video",demo:o,video:s})}),e.createElement(g,{icon:"download",small:!0,kind:"bare",title:s.look?.subtitles?"Download":"Download, with its subtitles beside it",onClick:()=>{t.downloadVideo(s,o.title),s.look?.subtitles||t.downloadVideo(s,o.title,"vtt")}}),e.createElement(g,{icon:"delete",small:!0,kind:"bare",title:"Delete the video",onClick:()=>{window.confirm("Delete this video?")&&t.store.deleteVideo(s.id)}})))}export function Settings({engine:t}){const{settings:a,speech:n}=p(t),o=a.speech.voice,l=t.language(),i=e=>t.changeSettings({speech:{...a.speech,...e}});return e.createElement(e.Fragment,null,e.createElement("section",{className:"section"},e.createElement("h3",null,"Voice"),e.createElement(E,{value:o,onChange:e=>i({voice:e}),options:C.map(([e,t,a])=>[e,t,a])}),"free"===o&&e.createElement(D,{engine:t}),"elevenlabs"===o&&e.createElement(L,{engine:t}),"system"===o&&e.createElement($,{engine:t,language:l}),e.createElement(k,{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)})})),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)),e.createElement("section",{className:"section"},e.createElement("h3",null,"Language and subtitles"),e.createElement(k,{label:"Narration in"},e.createElement(E,{value:a.language,onChange:e=>t.changeSettings({language:e}),options:[["page",e.createElement(y,{key:"page",language:"page"},"The page's"),`The page's language: ${t.options.language?.()??l} now`],...t.languages().map(t=>[t,e.createElement(y,{key:t,language:t})])]})),e.createElement(h,{label:"Subtitles",checked:a.subtitles,onChange:e=>t.changeSettings({subtitles:e})}),e.createElement(h,{label:"A 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("section",{className:"section"},e.createElement("h3",null,"Playing from a step"),e.createElement(h,{label:"Earlier steps first, quickly: the app where the step expects it",checked:a.catchUp,onChange:e=>t.changeSettings({catchUp:e})})),e.createElement("div",{className:"small muted"},"Playing: Space pauses, → or PageDown goes on, ← or PageUp goes back, 1-9 a step, Esc stops. Videos, recordings, booths and presentations ask what they need as they start."))}function D({engine:a}){const{settings:n}=p(a),[l,i]=o([]);return t(()=>{c().then(i,()=>i([]))},[]),e.createElement("div",{className:"col"},a.languages().map(t=>{const o=a.speech.freeVoice(t)??"",i=t.split(/[-_]/)[0],s=l.filter(e=>e.language.split("_")[0]===i);return e.createElement(k,{key:t,label:`Voice for ${t}`},e.createElement("select",{className:"field",value:o,onChange:e=>a.changeSettings({speech:{...n.speech,free:{...n.speech.free,[t]:e.target.value}}})},!o&&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"},o.startsWith("piper:")&&!s.some(e=>`piper:${e.id}`===o)&&e.createElement("option",{value:o},o.slice(6)),s.map(t=>e.createElement("option",{key:t.id,value:`piper:${t.id}`},t.name)))))}))}function L({engine:a}){const{settings:n}=p(a),{key:l,voices:i={}}=n.speech.elevenlabs,[r,c]=o([]),m=e=>a.changeSettings({speech:{...n.speech,elevenlabs:{...n.speech.elevenlabs,...e}}});t(()=>{l&&s(l).then(c,()=>c([]))},[l]);const d=a.languages();return e.createElement("div",{className:"col"},e.createElement(k,{label:"API key, kept in this browser"},e.createElement("input",{className:"field",type:"password",autoComplete:"off",value:l,onChange:e=>m({key:e.target.value.trim()})})),r.length>0&&d.map((t,n)=>{const o=a.speech.elevenLabsVoice(t),l=t.toLowerCase().split(/[-_]/)[0],s=r.filter(e=>e.languages.includes(l)),c=r.filter(e=>!e.languages.includes(l)),d=function(e){try{return new Intl.DisplayNames(["en"],{type:"language"}).of(e)??e}catch{return e}}(l);return e.createElement(k,{key:t,label:`Voice for ${d}`},e.createElement("select",{className:"field",value:o,onChange:e=>m({voices:{...i,[t]:e.target.value},...0===n?{voice:e.target.value}:{}})},!r.some(e=>e.id===o)&&e.createElement("option",{value:o},o),s.length>0&&e.createElement("optgroup",{label:`Checked for ${d}`},s.map(t=>e.createElement("option",{key:t.id,value:t.id},t.name))),e.createElement("optgroup",{label:s.length>0?"Other voices: they speak it too":`Every voice speaks ${d}`},c.map(t=>e.createElement("option",{key:t.id,value:t.id},t.name)))))}))}function $({engine:a,language:n}){const{settings:l}=p(a),[i,s]=o(()=>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(k,{label:`Voice for ${n}`},e.createElement("select",{className:"field",value:l.speech.system[n]??"",onChange:e=>a.changeSettings({speech:{...l.speech,system:{...l.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))))}
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 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,JsonField as E,Labelled as w,Menu as k,NumberField as y,Segmented as b}from"./Kit.js";import{Timeline as N}from"./Timeline.js";const C="protomaze-demo-engine:studio-height";export function Studio({engine:d,theme:m}){const j=u(d),$=j.studio,[O,L]=i(()=>o($.demo)),[R,T]=i(()=>JSON.stringify($.demo)),A=n({back:[],forward:[]}),[M,J]=i(0),[B,U]=i(),[F,P]=i("steps"),[V,z]=i({json:"",scenario:""}),[W,H]=i(),[I,K]=i(new Map),[q,Y]=i(()=>Number(localStorage.getItem(C))||Math.round(.46*innerHeight)),[G,Z]=i(!1),[Q,X]=i(!1),[_,ee]=i(!1),[te,ae]=i(!1),[ne,ie]=i(()=>d.language()),oe=j.session,le="idle"!==oe.mode,se="playing"!==oe.mode||oe.checking?void 0:oe,re=O.steps,ce=Math.min(M,Math.max(0,re.length-1)),de=se&&se.demo.id===O.id?se.step:ce,me=JSON.stringify(O)!==R,pe=a(()=>Array.from(new Set([...d.languages(),...d.languagesOf(O)])),[O]),he=d.entriesNow().find(e=>e.demo.id===O.id),ge=d.timing(O,ne),ue=j.lastRun?.json===JSON.stringify(O)&&j.lastRun.language===ne,ve=(e,t=!0)=>{t&&(A.current.back.push(O),A.current.back.length>200&&A.current.back.shift(),A.current.forward=[]),L(e)},fe=()=>{const e=A.current.back.pop();e&&(A.current.forward.push(O),L(e))},Ee=()=>{const e=A.current.forward.pop();e&&(A.current.back.push(O),L(e))},we=e=>ve({...O,...e}),ke=e=>we({steps:e}),ye=e=>ke(re.map((t,a)=>a===ce?e:t));t(()=>{$.recorded&&ve({...O,steps:$.recorded.steps})},[$.recorded?.at]);const be=()=>{const{demo:e,problems:t}=d.parse(V.json);if(e)return H(void 0),{...e,scenario:V.scenario};H(t.slice(0,4).map(e=>`${e.path||"demo"}: ${e.message}`).join(" · "))},Ne=async()=>{const e="text"===F?be():O;if(e)try{await d.save(e),L(e),T(JSON.stringify(e)),d.say(`Saved "${e.title}".`)}catch(e){d.say(e.message,!0)}},Ce=e=>{d.play(O,{from:e,language:ne})},xe=e=>{const t=ce+e;if(t<0||t>=re.length)return;const a=[...re];[a[ce],a[t]]=[a[t],a[ce]],ke(a),J(t)},Se=G||te||"recording"===oe.mode||Boolean(se),De=re[ce],je=e=>{const t=ge.steps.find(t=>t.step===e);return t?`${((t.end-t.start)/1e3).toFixed(1)} s`:""};return e.createElement("div",{className:"pde studio"+(Se?" 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(),Ne()):"z"!==t||e.shiftKey||"text"===F?("y"===t||"z"===t&&e.shiftKey)&&"text"!==F&&(e.preventDefault(),Ee()):(e.preventDefault(),fe())},style:{height:Se?void 0:q,display:te?"none":void 0}},e.createElement("div",{className:"grip",onPointerDown:e=>{const t=e.clientY,a=q,n=e=>Y(Math.max(180,Math.min(innerHeight-40,a+t-e.clientY))),i=()=>{window.removeEventListener("pointermove",n),window.removeEventListener("pointerup",i),Y(e=>(localStorage.setItem(C,String(e)),e))};window.addEventListener("pointermove",n),window.addEventListener("pointerup",i)}}),e.createElement("div",{className:"head"},e.createElement("input",{className:"field title",value:O.title,title:"Title",onChange:e=>we({title:e.target.value})}),e.createElement("div",{className:"sep"}),!se&&e.createElement(e.Fragment,null,e.createElement(v,{icon:"play",kind:"primary",disabled:le,title:`Play from step ${ce+1}`,onClick:()=>Ce(ce)},"Play"),e.createElement(k,{title:"Play from the start, present, guide, loop",icon:"expand",align:"left",items:[{label:"From the start",icon:"first",disabled:le,onClick:()=>Ce(0)},{label:`Present from step ${ce+1}…`,icon:"present",disabled:le,onClick:()=>d.present(O,{from:ce})},{label:`Guide from step ${ce+1}: the viewer does it`,icon:"guide",disabled:le,onClick:()=>{d.guide(O,{from:ce,language:ne})}},{label:"Loop at a booth…",icon:"loop",disabled:le,onClick:()=>d.openDialog({kind:"loop",demos:[O]})},...pe.length>1?[{heading:"Narration in"},...pe.map(e=>({label:`${e===ne?"● ":""}${e}`,onClick:()=>ie(e)}))]:[]]}),e.createElement(v,{icon:"record",title:`Record new steps after step ${ce+1}…`,disabled:le,onClick:()=>d.openDialog({kind:"record",into:O,after:ce}),style:{color:"var(--danger)"}}),e.createElement(v,{icon:"film",title:"Film a video…",disabled:le,onClick:()=>d.openDialog({kind:"film",demo:O})}),e.createElement(v,{icon:"check",title:"Check: plays it fast and silent, and marks what fails",disabled:le,onClick:()=>{(async()=>{const e=await d.check(O);K(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&&(J(t.step),U(t.index))})()}}),!1!==d.options.assistant&&e.createElement(v,{icon:"spark",title:"Ask Claude to change this demo, in words",onClick:()=>d.openAssistant(O)})),se&&e.createElement(e.Fragment,null,e.createElement(v,{icon:se.paused?"play":"pause",kind:"primary",onClick:()=>se.waiting?d.next():d.togglePause()},se.waiting?"Continue":se.paused?"Resume":"Pause"),e.createElement(v,{icon:"back",title:"Back (←)",onClick:()=>d.back()}),e.createElement(v,{icon:"right",title:"Next step (→)",onClick:()=>d.next()}),e.createElement(v,{icon:"stop",title:"Stop (Esc)",onClick:()=>d.stop()})),e.createElement("span",{className:"grow"}),e.createElement(v,{icon:"undo",kind:"bare",title:"Undo (Ctrl+Z)",disabled:0===A.current.back.length,onClick:fe}),e.createElement(v,{icon:"redo",kind:"bare",title:"Redo (Ctrl+Y)",disabled:0===A.current.forward.length,onClick:Ee}),e.createElement(v,{icon:"save",kind:me?"primary":void 0,title:"Save here (Ctrl+S)",onClick:()=>{Ne()}},me?"Save":"Saved"),e.createElement(k,{title:"Share, export",icon:"share",items:[{label:"Copy a link with the demo",icon:"link",onClick:()=>{d.link(O).then(e=>navigator.clipboard.writeText(e)).then(()=>d.say("Link copied: it opens the app with this demo."))}},{label:"Download .demo.json",icon:"download",onClick:()=>d.downloadDemo(O)},{label:"Download scenario .md",icon:"download",onClick:()=>d.downloadDemo(O,"md")},{label:"Copy JSON",icon:"copy",onClick:()=>{navigator.clipboard.writeText(JSON.stringify({...O,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(O)}},he?.video&&{label:"Download the video",icon:"film",onClick:()=>d.downloadVideo(he.video,O.title)},("edited"===he?.origin||"here"===he?.origin)&&{heading:"This demo"},"edited"===he?.origin&&{label:"Revert to the app’s version",icon:"undo",onClick:()=>{window.confirm("Drop the changes kept here?")&&d.remove(O.id)}},"here"===he?.origin&&{label:"Delete",icon:"delete",onClick:()=>{window.confirm(`Delete "${O.title}"?`)&&d.remove(O.id)}}]}),e.createElement(b,{value:F,onChange:e=>{if(e!==F){if("text"===F){const e=be();if(!e)return;JSON.stringify(e)!==JSON.stringify(O)&&ve(e)}"text"===e&&(()=>{const{scenario:e,savedAt:t,...a}=O;z({json:JSON.stringify(a,null,2),scenario:O.scenario??s(O,ne)}),H(void 0)})(),P(e)}},options:[["steps","Steps"],["text","Text"],["video","Video",he?.video?"Its last video":"Not filmed yet"]]}),e.createElement(v,{icon:G?"maximize":"minimize",kind:"bare",title:G?"Unfold":"Fold",onClick:()=>Z(!G)}),e.createElement(v,{icon:"close",kind:"bare",title:"Close",onClick:()=>{me&&!window.confirm("Close without saving?")||d.closeStudio()}})),e.createElement(N,{demo:O,timing:ge,measured:ue,step:de,action:B,theme:m,accent:"#ffb300",playhead:se&&se.demo.id===O.id?()=>d.elapsed():void 0,read:e=>g(d,e),onPick:(e,t)=>{se&&se.demo.id===O.id&&d.goTo(e)||(J(e),U(t),G&&Z(!1))}}),W&&e.createElement("div",{className:"error small",style:{padding:"4px 12px"}},W),e.createElement("div",{className:"body"},"text"!==F&&e.createElement("div",{className:"steps"},e.createElement("div",{className:["step",_&&"on"].filter(Boolean).join(" "),style:{marginBottom:4},onClick:()=>{ee(!0),X(!1),U(void 0)},title:"Its title, who it is for, where it starts"},e.createElement("span",{className:"n"},"i"),e.createElement("div",{className:"col grow",style:{gap:2}},e.createElement("span",{style:{fontWeight:500}},"About this demo"),e.createElement("span",{className:"say"},O.description||"Who it is for, what it shows"))),re.map((t,a)=>e.createElement("div",{key:a,className:["step",a===ce&&!Q&&!_&&"on",se&&a===de&&"playing"].filter(Boolean).join(" "),onClick:()=>{J(a),U(void 0),X(!1),ee(!1),function(e){if("video"!==F)return;const t=he?.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,ne)||"Untitled"),e.createElement("span",{className:"small muted"},je(a))),t.title&&e.createElement("span",{className:"say"},l(t,ne)),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:()=>{ke([...re.slice(0,ce+1),{say:{},actions:[]},...re.slice(ce+1)]),J(ce+1),X(!1)}},"New step"),e.createElement("div",{className:["step",Q&&"on"].filter(Boolean).join(" "),style:{marginTop:6},onClick:()=>{X(!0),ee(!1),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"},(O.cleanup??[]).length," action",1===(O.cleanup??[]).length?"":"s"," after it, unseen")))),"steps"===F&&_&&e.createElement("div",{className:"pane"},e.createElement("strong",null,"About this demo"),e.createElement(w,{label:"Title"},e.createElement("input",{className:"field",value:O.title,onChange:e=>we({title:e.target.value})})),e.createElement(w,{label:"Description: who it is for, what it shows"},e.createElement("textarea",{className:"field",rows:3,value:O.description??"",onChange:e=>we({description:e.target.value})})),e.createElement(w,{label:"Its start: where the app is when it plays (the app's start.go)"},e.createElement(E,{value:O.start,onChange:e=>we({start:e&&"object"==typeof e?e:void 0})})),e.createElement("span",{className:"small muted"},"Id: ",e.createElement("span",{className:"mono"},O.id)," · ",re.length," steps · ",d.languagesOf(O).join(", ")||"no narration yet")),"steps"===F&&Q&&e.createElement("div",{className:"pane"},e.createElement("div",{className:"row"},e.createElement("strong",{className:"grow"},"Cleanup"),e.createElement(k,{title:"Add an action",icon:"add",label:"Add",items:h(d,e=>{we({cleanup:[...O.cleanup??[],e]}),U((O.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"),")."),(O.cleanup??[]).map((t,a)=>e.createElement(p,{key:`cleanup.${a}`,engine:d,action:t,index:a,count:(O.cleanup??[]).length,open:B===a,sentences:[],onOpen:()=>U(B===a?void 0:a),onChange:e=>we({cleanup:(O.cleanup??[]).map((t,n)=>n===a?e:t)}),onMove:e=>{const t=[...O.cleanup??[]],n=a+e;n<0||n>=t.length||([t[a],t[n]]=[t[n],t[a]],we({cleanup:t}),U(n))},onDuplicate:()=>we({cleanup:[...(O.cleanup??[]).slice(0,a+1),o(t),...(O.cleanup??[]).slice(a+1)]}),onDelete:()=>{we({cleanup:(O.cleanup??[]).filter((e,t)=>t!==a)}),U(void 0)},picking:ae}))),"steps"===F&&De&&!Q&&!_&&e.createElement(e.Fragment,null,e.createElement("div",{className:"pane"},e.createElement("div",{className:"row"},e.createElement("strong",{className:"grow"},"Step ",ce+1," of ",re.length),e.createElement(v,{icon:"up",small:!0,kind:"bare",title:"Earlier",disabled:0===ce,onClick:()=>xe(-1)}),e.createElement(v,{icon:"down",small:!0,kind:"bare",title:"Later",disabled:ce===re.length-1,onClick:()=>xe(1)}),e.createElement(v,{icon:"duplicate",small:!0,kind:"bare",title:"Duplicate",onClick:()=>{ke([...re.slice(0,ce+1),o(De),...re.slice(ce+1)]),J(ce+1)}}),e.createElement(v,{icon:"delete",small:!0,kind:"bare",title:"Delete this step",disabled:re.length<2,onClick:()=>{ke(re.filter((e,t)=>t!==ce)),J(Math.max(0,ce-1))}})),e.createElement("input",{className:"field",placeholder:"Title, for the editor and the timeline",value:De.title??"",onChange:e=>ye(x(De,"title",e.target.value||void 0))}),pe.map(t=>e.createElement(S,{key:t,engine:d,language:t,text:De.say[t]??"",onChange:e=>ye({...De,say:x(De.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:De.notes??"",onChange:e=>ye(x(De,"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(y,{value:De.hold,width:70,placeholder:"0",onChange:e=>ye(x(De,"hold",e))}),e.createElement(f,{label:"Wait for the presenter after it",checked:Boolean(De.pause),onChange:e=>ye(x(De,"pause",e||void 0))}),e.createElement("span",{className:"small muted"},je(ce)))),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(k,{title:"Add an action",icon:"add",label:"Add",items:h(d,e=>{ye({...De,actions:[...De.actions,e]}),U(De.actions.length)})})),0===De.actions.length&&e.createElement("div",{className:"muted small"},"None yet: add one, or record them (●) by doing them on the page."),De.actions.map((t,a)=>e.createElement(p,{key:`${ce}.${a}`,engine:d,action:t,index:a,count:De.actions.length,open:B===a,error:I.get(`${ce}.${a}`),sentences:r(l(De,ne)),onOpen:()=>U(B===a?void 0:a),onChange:e=>((e,t)=>ye({...re[ce],actions:re[ce].actions.map((a,n)=>n===e?t:a)}))(a,e),onMove:e=>((e,t)=>{const a=e+t,n=[...re[ce].actions];a<0||a>=n.length||([n[e],n[a]]=[n[a],n[e]],ye({...re[ce],actions:n}),U(a))})(a,e),onDuplicate:()=>ye({...De,actions:[...De.actions.slice(0,a+1),o(t),...De.actions.slice(a+1)]}),onDelete:()=>{ye({...De,actions:De.actions.filter((e,t)=>t!==a)}),U(void 0)},picking:ae})))),"text"===F&&e.createElement("div",{className:"pane",style:{flexDirection:"row"}},e.createElement("textarea",{className:"field mono grow",spellCheck:!1,value:V.json,onChange:e=>z({...V,json:e.target.value})}),e.createElement("textarea",{className:"field mono grow",spellCheck:!1,value:V.scenario,placeholder:"The scenario, for people (.md)",onChange:e=>z({...V,scenario:e.target.value})})),"video"===F&&e.createElement(D,{engine:d,draft:O})))}function x(e,t,a){const n={...e,[t]:a};return void 0===a&&delete n[t],n}function S({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 D({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"))))}
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,JsonField as E,Labelled as w,Menu as k,NumberField as y,Segmented as b}from"./Kit.js";import{Timeline as N}from"./Timeline.js";const C="protomaze-demo-engine:studio-height";export function Studio({engine:d,theme:m}){const j=u(d),$=j.studio,[O,L]=i(()=>o($.demo)),[R,T]=i(()=>JSON.stringify($.demo)),A=n({back:[],forward:[]}),[M,J]=i(0),[B,U]=i(),[F,P]=i("steps"),[V,z]=i({json:"",scenario:""}),[W,H]=i(),[I,K]=i(new Map),[q,Y]=i(()=>Number(localStorage.getItem(C))||Math.round(.46*innerHeight)),[G,Z]=i(!1),[Q,X]=i(!1),[_,ee]=i(!1),[te,ae]=i(!1),[ne,ie]=i(()=>d.language()),oe=j.session,le="idle"!==oe.mode,se="playing"!==oe.mode||oe.checking?void 0:oe,re=O.steps,ce=Math.min(M,Math.max(0,re.length-1)),de=se&&se.demo.id===O.id?se.step:ce,me=JSON.stringify(O)!==R,pe=a(()=>Array.from(new Set([...d.languages(),...d.languagesOf(O)])),[O]),he=d.entriesNow().find(e=>e.demo.id===O.id),ge=d.timing(O,ne),ue=j.lastRun?.json===JSON.stringify(O)&&j.lastRun.language===ne,ve=(e,t=!0)=>{t&&(A.current.back.push(O),A.current.back.length>200&&A.current.back.shift(),A.current.forward=[]),L(e)},fe=()=>{const e=A.current.back.pop();e&&(A.current.forward.push(O),L(e))},Ee=()=>{const e=A.current.forward.pop();e&&(A.current.back.push(O),L(e))},we=e=>ve({...O,...e}),ke=e=>we({steps:e}),ye=e=>ke(re.map((t,a)=>a===ce?e:t));t(()=>{$.recorded&&ve({...O,steps:$.recorded.steps})},[$.recorded?.at]);const be=()=>{const{demo:e,problems:t}=d.parse(V.json);if(e)return H(void 0),{...e,scenario:V.scenario};H(t.slice(0,4).map(e=>`${e.path||"demo"}: ${e.message}`).join(" · "))},Ne=async()=>{const e="text"===F?be():O;if(e)try{await d.save(e),L(e),T(JSON.stringify(e)),d.say(`Saved "${e.title}".`)}catch(e){d.say(e.message,!0)}},Ce=e=>{d.play(O,{from:e,language:ne})},xe=e=>{const t=ce+e;if(t<0||t>=re.length)return;const a=[...re];[a[ce],a[t]]=[a[t],a[ce]],ke(a),J(t)},Se=G||te||"recording"===oe.mode||Boolean(se),De=re[ce],je=e=>{const t=ge.steps.find(t=>t.step===e);return t?`${((t.end-t.start)/1e3).toFixed(1)} s`:""};return e.createElement("div",{className:"pde studio"+(Se?" 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(),Ne()):"z"!==t||e.shiftKey||"text"===F?("y"===t||"z"===t&&e.shiftKey)&&"text"!==F&&(e.preventDefault(),Ee()):(e.preventDefault(),fe())},style:{height:Se?void 0:q,display:te?"none":void 0}},e.createElement("div",{className:"grip",onPointerDown:e=>{const t=e.clientY,a=q,n=e=>Y(Math.max(180,Math.min(innerHeight-40,a+t-e.clientY))),i=()=>{window.removeEventListener("pointermove",n),window.removeEventListener("pointerup",i),Y(e=>(localStorage.setItem(C,String(e)),e))};window.addEventListener("pointermove",n),window.addEventListener("pointerup",i)}}),e.createElement("div",{className:"head"},e.createElement("input",{className:"field title",value:O.title,title:"Title",onChange:e=>we({title:e.target.value})}),e.createElement("div",{className:"sep"}),!se&&e.createElement(e.Fragment,null,e.createElement(v,{icon:"play",kind:"primary",disabled:le,title:`Play from step ${ce+1}`,onClick:()=>Ce(ce)},"Play"),e.createElement(k,{title:"Play from the start, present, guide, loop",icon:"expand",align:"left",items:[{label:"From the start",icon:"first",disabled:le,onClick:()=>Ce(0)},{label:`Present from step ${ce+1}…`,icon:"present",disabled:le,onClick:()=>d.present(O,{from:ce})},{label:`Guide from step ${ce+1}: the viewer does it`,icon:"guide",disabled:le,onClick:()=>{d.guide(O,{from:ce,language:ne})}},{label:"Loop at a booth…",icon:"loop",disabled:le,onClick:()=>d.openDialog({kind:"loop",demos:[O]})},...pe.length>1?[{heading:"Narration in"},...pe.map(e=>({label:`${e===ne?"● ":""}${e}`,onClick:()=>ie(e)}))]:[]]}),e.createElement(v,{icon:"record",title:`Record new steps after step ${ce+1}…`,disabled:le,onClick:()=>d.openDialog({kind:"record",into:O,after:ce}),style:{color:"var(--danger)"}}),e.createElement(v,{icon:"film",title:"Film a video…",disabled:le,onClick:()=>d.openDialog({kind:"film",demo:O})}),e.createElement(v,{icon:"check",title:"Check: plays it fast and silent, and marks what fails",disabled:le,onClick:()=>{(async()=>{const e=await d.check(O);K(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&&(J(t.step),U(t.index))})()}}),!0===d.options.assistant&&e.createElement(v,{icon:"spark",title:"Ask Claude to change this demo, in words",onClick:()=>d.openAssistant(O)})),se&&e.createElement(e.Fragment,null,e.createElement(v,{icon:se.paused?"play":"pause",kind:"primary",onClick:()=>se.waiting?d.next():d.togglePause()},se.waiting?"Continue":se.paused?"Resume":"Pause"),e.createElement(v,{icon:"back",title:"Back (←)",onClick:()=>d.back()}),e.createElement(v,{icon:"right",title:"Next step (→)",onClick:()=>d.next()}),e.createElement(v,{icon:"stop",title:"Stop (Esc)",onClick:()=>d.stop()})),e.createElement("span",{className:"grow"}),e.createElement(v,{icon:"undo",kind:"bare",title:"Undo (Ctrl+Z)",disabled:0===A.current.back.length,onClick:fe}),e.createElement(v,{icon:"redo",kind:"bare",title:"Redo (Ctrl+Y)",disabled:0===A.current.forward.length,onClick:Ee}),e.createElement(v,{icon:"save",kind:me?"primary":void 0,title:"Save here (Ctrl+S)",onClick:()=>{Ne()}},me?"Save":"Saved"),e.createElement(k,{title:"Share, export",icon:"share",items:[{label:"Copy a link with the demo",icon:"link",onClick:()=>{d.link(O).then(e=>navigator.clipboard.writeText(e)).then(()=>d.say("Link copied: it opens the app with this demo."))}},{label:"Download .demo.json",icon:"download",onClick:()=>d.downloadDemo(O)},{label:"Download scenario .md",icon:"download",onClick:()=>d.downloadDemo(O,"md")},{label:"Copy JSON",icon:"copy",onClick:()=>{navigator.clipboard.writeText(JSON.stringify({...O,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(O)}},he?.video&&{label:"Download the video",icon:"film",onClick:()=>d.downloadVideo(he.video,O.title)},("edited"===he?.origin||"here"===he?.origin)&&{heading:"This demo"},"edited"===he?.origin&&{label:"Revert to the app’s version",icon:"undo",onClick:()=>{window.confirm("Drop the changes kept here?")&&d.remove(O.id)}},"here"===he?.origin&&{label:"Delete",icon:"delete",onClick:()=>{window.confirm(`Delete "${O.title}"?`)&&d.remove(O.id)}}]}),e.createElement(b,{value:F,onChange:e=>{if(e!==F){if("text"===F){const e=be();if(!e)return;JSON.stringify(e)!==JSON.stringify(O)&&ve(e)}"text"===e&&(()=>{const{scenario:e,savedAt:t,...a}=O;z({json:JSON.stringify(a,null,2),scenario:O.scenario??s(O,ne)}),H(void 0)})(),P(e)}},options:[["steps","Steps"],["text","Text"],["video","Video",he?.video?"Its last video":"Not filmed yet"]]}),e.createElement(v,{icon:G?"maximize":"minimize",kind:"bare",title:G?"Unfold":"Fold",onClick:()=>Z(!G)}),e.createElement(v,{icon:"close",kind:"bare",title:"Close",onClick:()=>{me&&!window.confirm("Close without saving?")||d.closeStudio()}})),e.createElement(N,{demo:O,timing:ge,measured:ue,step:de,action:B,theme:m,accent:"#ffb300",playhead:se&&se.demo.id===O.id?()=>d.elapsed():void 0,read:e=>g(d,e),onPick:(e,t)=>{se&&se.demo.id===O.id&&d.goTo(e)||(J(e),U(t),G&&Z(!1))}}),W&&e.createElement("div",{className:"error small",style:{padding:"4px 12px"}},W),e.createElement("div",{className:"body"},"text"!==F&&e.createElement("div",{className:"steps"},e.createElement("div",{className:["step",_&&"on"].filter(Boolean).join(" "),style:{marginBottom:4},onClick:()=>{ee(!0),X(!1),U(void 0)},title:"Its title, who it is for, where it starts"},e.createElement("span",{className:"n"},"i"),e.createElement("div",{className:"col grow",style:{gap:2}},e.createElement("span",{style:{fontWeight:500}},"About this demo"),e.createElement("span",{className:"say"},O.description||"Who it is for, what it shows"))),re.map((t,a)=>e.createElement("div",{key:a,className:["step",a===ce&&!Q&&!_&&"on",se&&a===de&&"playing"].filter(Boolean).join(" "),onClick:()=>{J(a),U(void 0),X(!1),ee(!1),function(e){if("video"!==F)return;const t=he?.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,ne)||"Untitled"),e.createElement("span",{className:"small muted"},je(a))),t.title&&e.createElement("span",{className:"say"},l(t,ne)),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:()=>{ke([...re.slice(0,ce+1),{say:{},actions:[]},...re.slice(ce+1)]),J(ce+1),X(!1)}},"New step"),e.createElement("div",{className:["step",Q&&"on"].filter(Boolean).join(" "),style:{marginTop:6},onClick:()=>{X(!0),ee(!1),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"},(O.cleanup??[]).length," action",1===(O.cleanup??[]).length?"":"s"," after it, unseen")))),"steps"===F&&_&&e.createElement("div",{className:"pane"},e.createElement("strong",null,"About this demo"),e.createElement(w,{label:"Title"},e.createElement("input",{className:"field",value:O.title,onChange:e=>we({title:e.target.value})})),e.createElement(w,{label:"Description: who it is for, what it shows"},e.createElement("textarea",{className:"field",rows:3,value:O.description??"",onChange:e=>we({description:e.target.value})})),e.createElement(w,{label:"Its start: where the app is when it plays (the app's start.go)"},e.createElement(E,{value:O.start,onChange:e=>we({start:e&&"object"==typeof e?e:void 0})})),e.createElement("span",{className:"small muted"},"Id: ",e.createElement("span",{className:"mono"},O.id)," · ",re.length," steps · ",d.languagesOf(O).join(", ")||"no narration yet")),"steps"===F&&Q&&e.createElement("div",{className:"pane"},e.createElement("div",{className:"row"},e.createElement("strong",{className:"grow"},"Cleanup"),e.createElement(k,{title:"Add an action",icon:"add",label:"Add",items:h(d,e=>{we({cleanup:[...O.cleanup??[],e]}),U((O.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"),")."),(O.cleanup??[]).map((t,a)=>e.createElement(p,{key:`cleanup.${a}`,engine:d,action:t,index:a,count:(O.cleanup??[]).length,open:B===a,sentences:[],onOpen:()=>U(B===a?void 0:a),onChange:e=>we({cleanup:(O.cleanup??[]).map((t,n)=>n===a?e:t)}),onMove:e=>{const t=[...O.cleanup??[]],n=a+e;n<0||n>=t.length||([t[a],t[n]]=[t[n],t[a]],we({cleanup:t}),U(n))},onDuplicate:()=>we({cleanup:[...(O.cleanup??[]).slice(0,a+1),o(t),...(O.cleanup??[]).slice(a+1)]}),onDelete:()=>{we({cleanup:(O.cleanup??[]).filter((e,t)=>t!==a)}),U(void 0)},picking:ae}))),"steps"===F&&De&&!Q&&!_&&e.createElement(e.Fragment,null,e.createElement("div",{className:"pane"},e.createElement("div",{className:"row"},e.createElement("strong",{className:"grow"},"Step ",ce+1," of ",re.length),e.createElement(v,{icon:"up",small:!0,kind:"bare",title:"Earlier",disabled:0===ce,onClick:()=>xe(-1)}),e.createElement(v,{icon:"down",small:!0,kind:"bare",title:"Later",disabled:ce===re.length-1,onClick:()=>xe(1)}),e.createElement(v,{icon:"duplicate",small:!0,kind:"bare",title:"Duplicate",onClick:()=>{ke([...re.slice(0,ce+1),o(De),...re.slice(ce+1)]),J(ce+1)}}),e.createElement(v,{icon:"delete",small:!0,kind:"bare",title:"Delete this step",disabled:re.length<2,onClick:()=>{ke(re.filter((e,t)=>t!==ce)),J(Math.max(0,ce-1))}})),e.createElement("input",{className:"field",placeholder:"Title, for the editor and the timeline",value:De.title??"",onChange:e=>ye(x(De,"title",e.target.value||void 0))}),pe.map(t=>e.createElement(S,{key:t,engine:d,language:t,text:De.say[t]??"",onChange:e=>ye({...De,say:x(De.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:De.notes??"",onChange:e=>ye(x(De,"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(y,{value:De.hold,width:70,placeholder:"0",onChange:e=>ye(x(De,"hold",e))}),e.createElement(f,{label:"Wait for the presenter after it",checked:Boolean(De.pause),onChange:e=>ye(x(De,"pause",e||void 0))}),e.createElement("span",{className:"small muted"},je(ce)))),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(k,{title:"Add an action",icon:"add",label:"Add",items:h(d,e=>{ye({...De,actions:[...De.actions,e]}),U(De.actions.length)})})),0===De.actions.length&&e.createElement("div",{className:"muted small"},"None yet: add one, or record them (●) by doing them on the page."),De.actions.map((t,a)=>e.createElement(p,{key:`${ce}.${a}`,engine:d,action:t,index:a,count:De.actions.length,open:B===a,error:I.get(`${ce}.${a}`),sentences:r(l(De,ne)),onOpen:()=>U(B===a?void 0:a),onChange:e=>((e,t)=>ye({...re[ce],actions:re[ce].actions.map((a,n)=>n===e?t:a)}))(a,e),onMove:e=>((e,t)=>{const a=e+t,n=[...re[ce].actions];a<0||a>=n.length||([n[e],n[a]]=[n[a],n[e]],ye({...re[ce],actions:n}),U(a))})(a,e),onDuplicate:()=>ye({...De,actions:[...De.actions.slice(0,a+1),o(t),...De.actions.slice(a+1)]}),onDelete:()=>{ye({...De,actions:De.actions.filter((e,t)=>t!==a)}),U(void 0)},picking:ae})))),"text"===F&&e.createElement("div",{className:"pane",style:{flexDirection:"row"}},e.createElement("textarea",{className:"field mono grow",spellCheck:!1,value:V.json,onChange:e=>z({...V,json:e.target.value})}),e.createElement("textarea",{className:"field mono grow",spellCheck:!1,value:V.scenario,placeholder:"The scenario, for people (.md)",onChange:e=>z({...V,scenario:e.target.value})})),"video"===F&&e.createElement(D,{engine:d,draft:O})))}function x(e,t,a){const n={...e,[t]:a};return void 0===a&&delete n[t],n}function S({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 D({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"))))}