@joplo-app/core 0.7.1 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -46,7 +46,7 @@ export declare const MENTAL_MODEL: readonly ["Joplo shows are playable, interact
46
46
  /** 推荐的起步顺序(X2:先做最小的一条正常流程 + 一条错误恢复流程,在看板里确认交互模型后再扩展)。 */
47
47
  export declare const START_ORDER: readonly ["Choose the starting template: compare feature options with npx joplo init <dir> (or --template starter); make one show people can play, pause and try with npx joplo init <dir> --template work. Bare names select built-ins, never a same-named local directory; use --template ./work for a local folder. Names matching [a-z0-9][a-z0-9-]* select directories in the template repository default branch, without version tags. Init installs engine skills and AGENTS.md, preserving any bundled plugin guides; after installing dependencies run skill install.", "Read npx joplo skill authoring and choose the capabilities; for feature review read cases before asking the user about edge cases; demo and installed plugin skills as needed.", "Plan before coding (npx joplo skill story): audience, one to three points, one line per scenario (Given → When → Then, how it opens and ends; a case's expected is its Then); show the plan to the user. A demo is a story, not a feature tour.", "With minimal code, write one chapter for a standalone work, or one happy path and one error-and-recovery scenario for feature review.", "Run npx joplo check, then npx joplo dev; confirm typing, clicks, and layers really behave as intended in the board.", "Extend to every option and every case agreed with the user for feature review, or to the agreed chapters for a standalone work; run check until 0 errors.", "Required after every round of development: before handing off, read npx joplo skill review and start npx joplo feedback watch [dir] --local --follow --json in its own shell (joplo dev prints this exact command); only then give the user the board URL dev printed. Never hand off with only a URL, and never end your response without a running watcher (use --once below). While they test, read its output with short waits (about 1–5s) and acknowledge each feedback right away; do not wait for approval or process exit. If you end your response while they test, add --once so the watcher exits (and wakes a host that resumes on background exit) on the first event, then resume with --since. Receive and apply review results with the joplo-feedback skill."];
48
48
  /** 最常见的坑:一句话 + 详细主题。 */
49
- export declare const PITFALLS: readonly [readonly ["Finishing development is not the end: always start npx joplo feedback watch [dir] --local --follow --json (add --once if you will end your response) before you give the user the board URL, and keep receiving their feedback", "review"], readonly ["when takes a condition, not a boolean: when={eq($.ui.mode, 'code')}, never when={mode === 'code'}; for values known while writing use {flag && <X/>}", "authoring"], readonly ["Every interactive element needs a flow step, disabled={true} with disabledReason, or unmodeled; otherwise check warns UNBOUND_INTERACTIVE", "check"], readonly ["No onClick or other function props: behavior lives in flow steps (.click/.type/.select) and effects (set, push, go, done)", "authoring"], readonly ["Full-height layouts squeeze tables and forms: rows exist in the DOM but are cut off on screen; show 5–8 rows or move the table to its own layer", "demo"], readonly ["Deep links use short params ?o=&c=&s=&step=&l= (l is the layer key and pins that layer, so later steps stop switching layers; layer= is ignored); wait for rendering before screenshots", "demo"], readonly ["Rules you assume stay origin ai_assumption, status pending; never mark them confirmed for the user", "cases"], readonly ["CHOICE_REQUIRED (exit 2): ask both publishing questions; never fix it by silently adding --private --no-review, and do not reuse the previous invocation", "publish"], readonly ["Public portfolio work and the always-private review version are two separate links: give reviewers data.review.url, the audience data.url", "publish"], readonly ["Required: before every share, ask the user public or private AND whether to also publish a review version. Never choose for them or reuse a previous choice; CI must pin both flags in its workflow", "publish"], readonly ["Public shares enter the portfolio and search engines: write the project name, description, and feature goals and work summaries as search-result content; exclude unpublished information", "publish"], readonly ["Never invent or set an access password for the user: ask them to type it in their own terminal or set JOPLO_SHARE_PASSWORD; never put passwords in command history, files, or conversation summaries. Private Pro shares accept --password; omit both password flags to preserve protection", "publish"], readonly ["Never share or deploy without the user's go-ahead. Free links no longer expire, but every live share counts toward the account storage; if share fails with QUOTA_EXCEEDED (exit 6), tell the user the numbers and the two links from error.details, never delete their shares yourself", "publish"], readonly ["Joplo Cloud narration spends the user's characters: run npx joplo voice --work <work-id> --dry-run (omit --work for all; --scenario follows continuing predecessors), inspect per-step details, use narrate(false) for silent steps, and tell them the estimate before a large batch; on TTS_QUOTA_EXCEEDED (exit 7) keep what was made, pass on error.details.usageUrl, and never retry in a loop or buy for them", "publish"], readonly ["AiHubMix, OpenAI-compatible gateways and custom HTTP voice providers are gone: VOICE_UNSUPPORTED means ask the user to switch to Joplo Cloud narration, OpenAI or ElevenLabs (old audio still plays and ships); never hand-edit ~/.joplo/voice/profiles.json", "publish"], readonly ["Playing a demo never generates Joplo Cloud narration (it would spend characters): steps without audio use the browser voice until the user clicks Generate missing audio or you run npx joplo voice with their go-ahead", "publish"], readonly ["Re-sharing with the default voice keeps valid local clips plus reusable published clips, even when their voices differ (automatic captions must still match current text in the clip language; stale audio is excluded); an old custom provider named cloud stays unsupported until the user explicitly chooses official Joplo Cloud (use voice.profile: 'Joplo Cloud' when config owns the selection)", "publish"], readonly ["HAPPY_PATH_ONLY applies only to feature review: for a standalone explainer use work() + chapter(), with no cases or uses(); do not invent failure scenarios", "check"], readonly ["Required for short films and explainers: static storyboards cannot show hard cuts or frozen pictures. Run npx joplo render <dir> --scenario-id <first chapter> --film --chain, fix every CUT and STILL it reports, and watch --video once before handing over (render supports --viewport/--no-frame, --crop and public --frames-out/--timeline; --video takes --width/--height, --voice, --clean and --srt for publishing; see joplo skill demo)", "demo"], readonly ["For multimodal stories, list assets and licenses first, prove one real asset in a playable chapter, then extend the batch within the agreed spending limit. Keep source claims separate from interpretations", "story"], readonly ["For generated binary assets, first look for CC0/public-domain material; use an enabled generation plugin for gaps. Run resources --dry-run before spending; check/build/render never generate paid artifacts. Commit outputs and metadata, keep keys local", "plugins"], readonly ["For background audio use a media plugin: enable it explicitly, read its skill, place play/stop in steps, and verify sound after a viewer gesture; local resource failures are warnings", "plugins"], readonly ["Collect reusable assets before drawing complex visuals; keep source URLs, authors, licenses and changes in assets/SOURCES.md, and verify bundled fonts and samples separately", "story"], readonly ["For audience exploration, use native UI controls or work.free; keep deterministic results in flow steps. Read demo before using drag, hover, scroll or plugin actions", "demo"], readonly ["Components outside the catalog may exist as plugins: install the npm package, add it to config({ plugins }), then read npx joplo skill <plugin id> before writing its components", "plugins"]];
49
+ export declare const PITFALLS: readonly [readonly ["Finishing development is not the end: always start npx joplo feedback watch [dir] --local --follow --json (add --once if you will end your response) before you give the user the board URL, and keep receiving their feedback", "review"], readonly ["when takes a condition, not a boolean: when={eq($.ui.mode, 'code')}, never when={mode === 'code'}; for values known while writing use {flag && <X/>}", "authoring"], readonly ["Every interactive element needs a flow step, disabled={true} with disabledReason, or unmodeled; otherwise check warns UNBOUND_INTERACTIVE", "check"], readonly ["No onClick or other function props: behavior lives in flow steps (.click/.type/.select) and effects (set, push, go, done)", "authoring"], readonly ["Full-height layouts squeeze tables and forms: rows exist in the DOM but are cut off on screen; show 5–8 rows or move the table to its own layer", "demo"], readonly ["Deep links use short params ?o=&c=&s=&step=&l= (l is the layer key and pins that layer, so later steps stop switching layers; layer= is ignored); wait for rendering before screenshots", "demo"], readonly ["Rules you assume stay origin ai_assumption, status pending; never mark them confirmed for the user", "cases"], readonly ["CHOICE_REQUIRED (exit 2): ask both publishing questions; never fix it by silently adding --private --no-review, and do not reuse the previous invocation", "publish"], readonly ["Public portfolio work and the always-private review version are two separate links: give reviewers data.review.url, the audience data.url", "publish"], readonly ["Required: before every share, ask the user public or private AND whether to also publish a review version. Never choose for them or reuse a previous choice; CI must pin both flags in its workflow", "publish"], readonly ["Public shares enter the portfolio and search engines: write the project name, description, and feature goals and work summaries as search-result content; exclude unpublished information", "publish"], readonly ["Never invent or set an access password for the user: ask them to type it in their own terminal or set JOPLO_SHARE_PASSWORD; never put passwords in command history, files, or conversation summaries. Private Pro shares accept --password; omit both password flags to preserve protection", "publish"], readonly ["Never share or deploy without the user's go-ahead. Free links no longer expire, but every live share counts toward the account storage; if share fails with QUOTA_EXCEEDED (exit 6), tell the user the numbers and the two links from error.details, never delete their shares yourself", "publish"], readonly ["Prepared narration/dialogue uses narrate(text, { audio: asset(...) }) or say(text, { role, audio: localResource(...) }); explicit audio never calls TTS or counts generation characters. Use hold('voice', { pad: 0.4 }) / hold('audio', ref) for measured-or-estimated audio dwell; check and outline identify the source; see demo before lining up tracks", "demo"], readonly ["Joplo Cloud narration spends the user's characters: run npx joplo voice --work <work-id> --dry-run (omit --work for all; --scenario follows continuing predecessors), inspect per-step details, use narrate(false) for silent steps, and tell them the estimate before a large batch; on TTS_QUOTA_EXCEEDED (exit 7) keep what was made, pass on error.details.usageUrl, and never retry in a loop or buy for them", "publish"], readonly ["AiHubMix, OpenAI-compatible gateways and custom HTTP voice providers are gone: VOICE_UNSUPPORTED means ask the user to switch to Joplo Cloud narration, OpenAI or ElevenLabs (old audio still plays and ships); never hand-edit ~/.joplo/voice/profiles.json", "publish"], readonly ["Playing a demo never generates Joplo Cloud narration (it would spend characters): steps without audio use the browser voice until the user clicks Generate missing audio or you run npx joplo voice with their go-ahead", "publish"], readonly ["Re-sharing with the default voice keeps valid local clips plus reusable published clips, even when their voices differ (automatic captions must still match current text in the clip language; stale audio is excluded); an old custom provider named cloud stays unsupported until the user explicitly chooses official Joplo Cloud (use voice.profile: 'Joplo Cloud' when config owns the selection)", "publish"], readonly ["HAPPY_PATH_ONLY applies only to feature review: for a standalone explainer use work() + chapter(), with no cases or uses(); do not invent failure scenarios", "check"], readonly ["Required for short films and explainers: static storyboards cannot show hard cuts or frozen pictures. Run npx joplo render <dir> --scenario-id <first chapter> --film --chain, fix every CUT and STILL it reports, and watch --video once before handing over (render supports --viewport/--no-frame, --crop and public --frames-out/--timeline; --video takes --width/--height, --voice, --clean and --srt for publishing; see joplo skill demo)", "demo"], readonly ["For multimodal stories, list assets and licenses first, prove one real asset in a playable chapter, then extend the batch within the agreed spending limit. Keep source claims separate from interpretations", "story"], readonly ["For generated binary assets, first look for CC0/public-domain material; use an enabled generation plugin for gaps. Run resources --dry-run before spending; check/build/render never generate paid artifacts. Commit outputs and metadata, keep keys local", "plugins"], readonly ["For background audio use a media plugin: enable it explicitly, read its skill, place play/stop in steps, and verify sound after a viewer gesture; local resource failures are warnings", "plugins"], readonly ["Collect reusable assets before drawing complex visuals; keep source URLs, authors, licenses and changes in assets/SOURCES.md, and verify bundled fonts and samples separately", "story"], readonly ["For audience exploration, use native UI controls or work.free; keep deterministic results in flow steps. Read demo before using drag, hover, scroll or plugin actions", "demo"], readonly ["Components outside the catalog may exist as plugins: install the npm package, add it to config({ plugins }), then read npx joplo skill <plugin id> before writing its components", "plugins"]];
50
50
  export type AgentSkill = {
51
51
  name: string;
52
52
  description: string;
@@ -53,6 +53,7 @@ export const PITFALLS = [
53
53
  ["Public shares enter the portfolio and search engines: write the project name, description, and feature goals and work summaries as search-result content; exclude unpublished information", "publish"],
54
54
  ["Never invent or set an access password for the user: ask them to type it in their own terminal or set JOPLO_SHARE_PASSWORD; never put passwords in command history, files, or conversation summaries. Private Pro shares accept --password; omit both password flags to preserve protection", "publish"],
55
55
  ["Never share or deploy without the user's go-ahead. Free links no longer expire, but every live share counts toward the account storage; if share fails with QUOTA_EXCEEDED (exit 6), tell the user the numbers and the two links from error.details, never delete their shares yourself", "publish"],
56
+ ["Prepared narration/dialogue uses narrate(text, { audio: asset(...) }) or say(text, { role, audio: localResource(...) }); explicit audio never calls TTS or counts generation characters. Use hold('voice', { pad: 0.4 }) / hold('audio', ref) for measured-or-estimated audio dwell; check and outline identify the source; see demo before lining up tracks", "demo"],
56
57
  ["Joplo Cloud narration spends the user's characters: run npx joplo voice --work <work-id> --dry-run (omit --work for all; --scenario follows continuing predecessors), inspect per-step details, use narrate(false) for silent steps, and tell them the estimate before a large batch; on TTS_QUOTA_EXCEEDED (exit 7) keep what was made, pass on error.details.usageUrl, and never retry in a loop or buy for them", "publish"],
57
58
  ["AiHubMix, OpenAI-compatible gateways and custom HTTP voice providers are gone: VOICE_UNSUPPORTED means ask the user to switch to Joplo Cloud narration, OpenAI or ElevenLabs (old audio still plays and ships); never hand-edit ~/.joplo/voice/profiles.json", "publish"],
58
59
  ["Playing a demo never generates Joplo Cloud narration (it would spend characters): steps without audio use the browser voice until the user clicks Generate missing audio or you run npx joplo voice with their go-ahead", "publish"],
@@ -118,6 +119,7 @@ function joploBody() {
118
119
  'Required: whenever you finish a round of development the user will look at, start the follower below before handing off, even for small changes and even if the user did not ask for a review. A hand-off without a running watcher loses their feedback.',
119
120
  'The user reviews in the board: they click through scenarios, write comments with the board\'s native feedback icon, and may confirm (approve) an option. You receive each event the moment it is saved.',
120
121
  '1. Start npx joplo feedback watch <dir> --local --follow --json in its own long-running shell (joplo dev prints this exact command; the board\'s feedback panel can copy it too). One follower covers every option of the project and attaches by itself to the new round each source edit opens.',
122
+ ' Successful dev startup/join registers review rounds before printing the ready link; no browser visit is required. Fix compile errors before starting watch. There is no idle expiry: inspect feedback list --local --all --json for closing reasons. A joined project depends on the original board process; keep its terminal running, or restart dev and watch after it stops.',
121
123
  '2. Then give the user the board URL that dev printed (do not assume port 4790) and point them to the native feedback icon. If they want to drive the UI themselves, only give the link.',
122
124
  '3. While they test, read the follower\'s output with short waits (about 1–5 seconds). Each stdout line is one JSON event (feedback, approved, closed) carrying eventId, workId, sessionId and context (route, scenario, step, source); deduplicate by eventId. A background shell alone does not wake an idle agent: stay in a receive loop, and do not claim you are still listening after ending your response unless the host can resume you.',
123
125
  ' - If you will end your response while the user tests, and your host wakes you when a background command finishes (a host configured to resume on process exit does): run the follower in the background with --once added. It exits 0 on the first feedback or approval, which wakes you. Handle the events, then start it again with --since <createdAt of the last event> (the exit message prints this exact command) so nothing is replayed or lost. Without such a host, tell the user to message you after they confirm.',
package/dist/compile.js CHANGED
@@ -232,6 +232,8 @@ export function compile(src, mode, opts = {}) {
232
232
  list.push(ctx);
233
233
  return list;
234
234
  };
235
+ /** 每个画面的元素事件(写法 v2),编译剧本与本地反应时读取。 */
236
+ const sceneEvents = new Map();
235
237
  const composeScene = (route, ctx) => {
236
238
  const sceneId = ctx ? `${ctx.qid}@${route.path}` : `@${route.path}`;
237
239
  const page = route.page;
@@ -270,7 +272,9 @@ export function compile(src, mode, opts = {}) {
270
272
  const base = tree;
271
273
  const rootJ = { ...base, type: base.type, children: [...base.children, ...overlays] };
272
274
  const ids = new Map();
273
- const root = toSceneNode(rootJ, 'root', ids, nodeCtx, null);
275
+ const events = new Map();
276
+ const root = toSceneNode(rootJ, 'root', ids, { ...nodeCtx, events }, null);
277
+ sceneEvents.set(sceneId, events);
274
278
  const scene = { id: sceneId, workId: ctx?.qid ?? null, route: route.path, name: `${page.title}${ctx ? ` · ${ctx.def.title}` : ''}`, viewport: page.viewport ?? 'desktop', root };
275
279
  if (!diags.some(d => d.severity === 'error'))
276
280
  host.derive(scene);
@@ -349,8 +353,10 @@ export function compile(src, mode, opts = {}) {
349
353
  }
350
354
  const rootJ = nodes.length === 1 ? nodes[0] : { ...nodes[0], type: '#fragment', props: {}, children: nodes };
351
355
  const ids = new Map();
352
- const root = toSceneNode(rootJ, `layer_${lk}`, ids, nodeCtx, null);
353
356
  const sceneId = `${qid}~${lk}`;
357
+ const events = new Map();
358
+ const root = toSceneNode(rootJ, `layer_${lk}`, ids, { ...nodeCtx, events }, null);
359
+ sceneEvents.set(sceneId, events);
354
360
  const scene = { id: sceneId, workId: qid, route: layerRoute, name: `${ld.title} · ${def.title}`, viewport: ld.viewport ?? 'desktop', root, layer: lk };
355
361
  if (!diags.some(d => d.severity === 'error'))
356
362
  host.derive(scene);
@@ -369,6 +375,10 @@ export function compile(src, mode, opts = {}) {
369
375
  const layersWith = (id) => layerScenes.filter((l) => findIn(l.scene.root, id)).map((l) => l.key);
370
376
  const layerSceneWith = (id) => layerScenes.find((l) => findIn(l.scene.root, id))?.scene;
371
377
  const effectRoots = [...layerScenes.map(l => l.scene), ...[...sceneFor.values()].filter(x => x.workId === qid || !isIsolated && x.workId == null)];
378
+ /** 这件作品的观众会看到的画面:有层级时是各层,否则是每个路径在这件作品里的画面。 */
379
+ const viewScenes = hasLayers ? layerScenes.map(l => l.scene) : [...ctxRoutes].map(path => sceneFor.get(sceneOf(path))).filter((x) => !!x);
380
+ /** 某一步(所在路径 route)点到的元素自带的 onClick。 */
381
+ const eventOf = (route, target) => hasLayers ? sceneEvents.get(layerSceneWith(target)?.id ?? '')?.get(target) : sceneEvents.get(sceneOf(route))?.get(target);
372
382
  const scenarioIds = {};
373
383
  // flow({ from }) 接力:按依赖顺序编译,被接的场景先编译,记下它结尾的路径与导演层;
374
384
  // 接力场景的逐步校验(页面里找目标、焦点提示、镜头、自动字幕)都从那里开始,而不是默认起点
@@ -392,16 +402,18 @@ export function compile(src, mode, opts = {}) {
392
402
  /** 每个场景编译完之后的结尾:路径(按 go / back 推算)与导演层。 */
393
403
  const scenarioEnd = new Map();
394
404
  for (const skey of orderedKeys) {
395
- const fl = scenarioDefs[skey];
405
+ const authored = scenarioDefs[skey];
396
406
  const sid = `${qid}.${skey}`;
397
- const fromEnd = fl.opts.from !== undefined && fl.opts.from !== skey ? scenarioEnd.get(fl.opts.from) : undefined;
398
- if (fl.opts.from !== undefined && fl.opts.start !== undefined)
399
- err('FROM_WITH_START', `flow({ from: ${JSON.stringify(fl.opts.from)}, start: ${JSON.stringify(fl.opts.start)} }): a scenario that continues another starts where that one ended; remove start (or remove from to start fresh)`, fl.source);
400
- const start = fromEnd?.route ?? fl.opts.start ?? (isIsolated ? '/' : touched[0] ?? src.config.home ?? [...ctxRoutes][0]);
407
+ const fromEnd = authored.opts.from !== undefined && authored.opts.from !== skey ? scenarioEnd.get(authored.opts.from) : undefined;
408
+ if (authored.opts.from !== undefined && authored.opts.start !== undefined)
409
+ err('FROM_WITH_START', `flow({ from: ${JSON.stringify(authored.opts.from)}, start: ${JSON.stringify(authored.opts.start)} }): a scenario that continues another starts where that one ended; remove start (or remove from to start fresh)`, authored.source);
410
+ const start = fromEnd?.route ?? authored.opts.start ?? (isIsolated ? '/' : touched[0] ?? src.config.home ?? [...ctxRoutes][0]);
401
411
  if (!start || !ctxRoutes.has(start)) {
402
- err('UNKNOWN_ROUTE', `Scenario ${sid} starts at unknown route ${start ?? '(none)'}`, fl.source);
412
+ err('UNKNOWN_ROUTE', `Scenario ${sid} starts at unknown route ${start ?? '(none)'}`, authored.source);
403
413
  continue;
404
414
  }
415
+ // 写法 v2:点击步骤先执行被点元素的 onClick,再执行步骤自己写的效果。页面跟踪(go / back)看得到合并后的效果。
416
+ const fl = Object.assign(Object.create(Object.getPrototypeOf(authored)), authored, { steps: withElementEvents(authored.steps, start, eventOf, warn) });
405
417
  for (const c of fl.opts.cases ?? []) {
406
418
  if (!fdef?.cases?.[c])
407
419
  err('UNKNOWN_CASE', `Scenario ${sid} covers case "${c}", which is not in feature.cases`, fl.source);
@@ -522,6 +534,49 @@ export function compile(src, mode, opts = {}) {
522
534
  }
523
535
  free[key] = { action: a.data, effects, ...(reaction.source ? { source: rel(reaction.source) } : {}) };
524
536
  }
537
+ // 元素事件生成本地反应:观众接管后点它,效果和剧本里那一步相同(uses 只是规则关联,不进本地层)
538
+ {
539
+ const seen = new Map();
540
+ for (const scene of viewScenes)
541
+ for (const [target, ev] of sceneEvents.get(scene.id) ?? []) {
542
+ const effects = [];
543
+ for (const e of ev.effects) {
544
+ if (e.type === 'go') {
545
+ if (!ctxRoutes.has(e.route)) {
546
+ err('UNKNOWN_ROUTE', `onClick go("${e.route}") on ${target} navigates to an unknown route`, ev.at);
547
+ continue;
548
+ }
549
+ effects.push({ type: 'navigate', sceneId: sceneOf(e.route) });
550
+ }
551
+ else if (e.type === 'set' || e.type === 'append')
552
+ effects.push({ type: e.type, path: e.path, value: e.value });
553
+ else if (e.type === 'toast')
554
+ effects.push({ type: 'toast', text: e.text, tone: e.tone });
555
+ }
556
+ const parsed = effects.map(e => Effect.safeParse(e));
557
+ if (parsed.some(r => !r.success)) {
558
+ err('EVENT_EFFECT_INVALID', `onClick on ${target} writes an invalid state path or value`, ev.at);
559
+ continue;
560
+ }
561
+ const json = JSON.stringify(effects);
562
+ const prev = seen.get(target);
563
+ if (prev) {
564
+ if (prev.json !== json)
565
+ err('EVENT_CONFLICT', `${target} has a different onClick on two stages of work ${qid} (other location: ${rel(prev.at) ?? 'unknown'}); one id has one behavior, so give the elements different ids`, ev.at);
566
+ continue;
567
+ }
568
+ seen.set(target, { json, ...(ev.at ? { at: ev.at } : {}) });
569
+ if (!effects.length)
570
+ continue;
571
+ const handWritten = Object.entries(free).find(([, r]) => r.action.type === 'click' && 'target' in r.action && r.action.target === target);
572
+ if (handWritten) {
573
+ err('FREE_EVENT_CONFLICT', `Free reaction ${handWritten[0]} also handles clicks on ${target}, which has onClick; keep one: move its effects into onClick and delete the free reaction`, ev.at);
574
+ continue;
575
+ }
576
+ const key = eventFreeKey(target, free);
577
+ free[key] = { action: { type: 'click', target }, effects: parsed.map(r => r.data), ...(ev.at && rel(ev.at) ? { source: rel(ev.at) } : {}) };
578
+ }
579
+ }
525
580
  if (fdef)
526
581
  out.features[fid].alternatives[qid] = { decisionFocus: strip ? '' : def.focus ?? '', tradeoffs: strip ? [] : def.tradeoffs ?? [], coverage };
527
582
  out.works[qid] = {
@@ -611,6 +666,8 @@ export function compile(src, mode, opts = {}) {
611
666
  }
612
667
  if (diags.some((d) => d.severity === 'error'))
613
668
  return { project: null, diagnostics: diags };
669
+ if (Object.keys(host.embeddedAudio).length)
670
+ out.mediaAssets = host.embeddedAudio;
614
671
  const parsed = Project.safeParse(out);
615
672
  if (!parsed.success) {
616
673
  // 同一根因(共享的 JSX)在多个画面展开时合并成一条,定位到作者元素(schema-issues.ts)
@@ -718,6 +775,8 @@ function lowerStep(c, st, i) {
718
775
  let sayRole = null;
719
776
  const narrates = [];
720
777
  let mute = false;
778
+ const sayAudio = [], narrateAudio = [];
779
+ let holdFor;
721
780
  /** 插件效果声明的最短停留(D98):同一步取最大值。 */
722
781
  let effectHoldMs = 0;
723
782
  const ext = {};
@@ -753,6 +812,8 @@ function lowerStep(c, st, i) {
753
812
  else if (e.type === 'shot' || e.type === 'mark' || e.type === 'fork' || e.type === 'cue' || e.type === 'callout' || e.type === 'hold')
754
813
  continue; // 镜头与焦点提示不是状态变化,下面单独归类
755
814
  else if (e.type === 'say') {
815
+ if (e.audio !== undefined)
816
+ sayAudio.push(e.audio);
756
817
  if (e.role !== undefined) {
757
818
  if (typeof e.role !== 'string' || !roleKeys.has(e.role))
758
819
  err('ROLE_UNKNOWN', `say() role "${String(e.role)}" is not in ${roleScope}${roleKeys.size ? ` (available: ${[...roleKeys].join(', ')})` : ` (${roleScope} must use { key: role('Name') })`}`, st.source);
@@ -767,6 +828,8 @@ function lowerStep(c, st, i) {
767
828
  err('SAY_EMPTY', 'say() needs the line the character speaks, for example say(\'I can make it!\'). Remove it to read the caption instead', st.source);
768
829
  }
769
830
  else if (e.type === 'narrate') {
831
+ if (e.audio !== undefined)
832
+ narrateAudio.push(e.audio);
770
833
  if (e.text === false)
771
834
  mute = true;
772
835
  else if (typeof e.text === 'string' && e.text.trim())
@@ -865,6 +928,18 @@ function lowerStep(c, st, i) {
865
928
  }
866
929
  }
867
930
  else if (e.type === 'hold') {
931
+ if ('timing' in e) {
932
+ const pad = e.pad ?? 0.45;
933
+ if (!['voice', 'audio'].includes(e.timing) || typeof pad !== 'number' || !Number.isFinite(pad) || pad < 0 || pad > 30)
934
+ err('HOLD_AUDIO_INVALID', 'Audio-derived hold pad must be finite seconds from 0 to 30', st.source);
935
+ else if (holdFor)
936
+ err('HOLD_AUDIO_CONFLICT', 'A step can have only one audio-derived hold declaration', st.source);
937
+ else {
938
+ const audio = e.timing === 'audio' ? host.audioSource(e.audio, st.source) : undefined;
939
+ holdFor = { kind: e.timing, padMs: Math.round(pad * 1000), ...(audio ? { audio } : {}) };
940
+ }
941
+ continue;
942
+ }
868
943
  const sec = e.seconds;
869
944
  if (typeof sec !== 'number' || !Number.isFinite(sec) || sec < HOLD_MIN_SECONDS || sec > HOLD_MAX_SECONDS)
870
945
  err('HOLD_INVALID', `hold(${String(sec)}) must be between ${HOLD_MIN_SECONDS} and ${HOLD_MAX_SECONDS} seconds`, st.source);
@@ -942,6 +1017,18 @@ function lowerStep(c, st, i) {
942
1017
  for (const s of shots)
943
1018
  frame.set(s.layer === DIRECTOR_LAYER ? director : s.layer, [...s.targets]);
944
1019
  const generated = st.caption === undefined ? autoCaption(st, (hasLayers && actionTarget ? layerSceneWith(actionTarget) : undefined) ?? sceneBefore, out) : null;
1020
+ const selectedAudio = narrates.length ? narrateAudio : sayAudio;
1021
+ const selectedLines = narrates.length ? narrates : says;
1022
+ if (!mute && selectedAudio.length && (selectedAudio.length !== 1 || selectedLines.length !== 1))
1023
+ err('SPEECH_AUDIO_CONFLICT', 'An explicit audio clip must accompany exactly one selected narrate() or say() line per step', st.source);
1024
+ const audio = !mute && selectedAudio.length === 1 ? host.audioSource(selectedAudio[0], st.source) : undefined;
1025
+ if (holdFor) {
1026
+ const cached = holdFor.kind === 'voice' && !audio && !mute ? host.voiceDuration(`${sid}#${i + 1}`) : undefined;
1027
+ const duration = holdFor.kind === 'audio' ? (holdFor.audio ? host.audioDuration(holdFor.audio) : undefined)
1028
+ : mute ? undefined : audio ? host.audioDuration(audio) : cached?.durationMs;
1029
+ if (typeof duration === 'number' && Number.isFinite(duration) && duration > 0)
1030
+ holdFor = { ...holdFor, durationMs: duration, durationKey: cached?.key ?? (holdFor.kind === 'audio' ? holdFor.audio : audio) };
1031
+ }
945
1032
  c.director = director;
946
1033
  return {
947
1034
  id: `${sid}#${i + 1}`,
@@ -962,6 +1049,8 @@ function lowerStep(c, st, i) {
962
1049
  marks,
963
1050
  ...(cues.length ? { cues } : {}),
964
1051
  ...(callouts.length ? { callouts } : {}),
1052
+ ...(audio ? { audio } : {}),
1053
+ ...(holdFor ? { holdFor } : {}),
965
1054
  ...(holdMs !== undefined ? { hold: holdMs } : {}),
966
1055
  ...(effectHoldMs > 0 ? { effectHold: effectHoldMs } : {}),
967
1056
  ...(says.length ? { say: says.join(' ') } : {}),
@@ -1037,6 +1126,22 @@ function expandSlots(n, fill, outlet) {
1037
1126
  function tagFrom(n, from) {
1038
1127
  return { ...n, props: { ...n.props, __from: from } };
1039
1128
  }
1129
+ /** 元素事件里允许的效果:会改变画面状态的本地效果,加上规则关联。完成、镜头、朗读、插件效果属于剧本步骤。 */
1130
+ const EVENT_EFFECTS = new Set(['set', 'append', 'toast', 'go', 'uses']);
1131
+ /** onClick={effect} 或 onClick={[effect, [effect]]};不是效果时返回 null。 */
1132
+ function eventEffects(v) {
1133
+ const out = [];
1134
+ const rec = (x) => {
1135
+ if (Array.isArray(x))
1136
+ return x.every(rec);
1137
+ if (x && typeof x === 'object' && x.kind === 'effect') {
1138
+ out.push(x);
1139
+ return true;
1140
+ }
1141
+ return false;
1142
+ };
1143
+ return rec(v) && out.length ? out : null;
1144
+ }
1040
1145
  function toSceneNode(n, fallbackId, ids, nc, parentType) {
1041
1146
  const { report: err, rel } = nc;
1042
1147
  n = { ...n, props: n.props ?? {}, children: n.children ?? [] };
@@ -1065,6 +1170,38 @@ function toSceneNode(n, fallbackId, ids, nc, parentType) {
1065
1170
  if (spec?.needsId && typeof rawId !== 'string' && !interactive)
1066
1171
  err('MISSING_ID', `<${n.type}> "${labelOf(n)}" requires an id`, at);
1067
1172
  const id = typeof rawId === 'string' ? rawId : `_${fallbackId}`;
1173
+ for (const k of Object.keys(rest)) {
1174
+ if (!/^on[A-Z]/.test(k))
1175
+ continue;
1176
+ const v = rest[k];
1177
+ delete rest[k];
1178
+ if (v === undefined)
1179
+ continue;
1180
+ if (typeof v === 'function' && !isBind(v)) {
1181
+ err('FUNCTION_PROP', `<${n.type}> prop ${k} is a function, and callbacks never run. Give a button its behavior as effects, for example onClick={set($.ui.open, true)}, or put it in the flow steps`, at);
1182
+ continue;
1183
+ }
1184
+ if (k !== 'onClick') {
1185
+ err('EVENT_UNSUPPORTED', `<${n.type}> ${k} is not supported yet; only onClick takes effects. Bind inputs with value={$.ui.name} and put other reactions in the steps`, at);
1186
+ continue;
1187
+ }
1188
+ const effects = eventEffects(v);
1189
+ if (!effects) {
1190
+ err('EVENT_EFFECT_INVALID', `<${n.type}> onClick must be effects, for example onClick={set($.ui.open, true)} or onClick={[set($.ui.open, true), go('/next')]}; got ${JSON.stringify(v)}`, at);
1191
+ continue;
1192
+ }
1193
+ const bad = effects.find(e => !EVENT_EFFECTS.has(e.type));
1194
+ if (bad) {
1195
+ err('EVENT_EFFECT_INVALID', `<${n.type}> onClick: ${bad.type === 'complete' ? 'done()' : `${bad.type}()`} cannot run when the viewer clicks. onClick takes set, push, toast, go and uses; put completion, camera, narration and plugin effects in the step that clicks it`, at);
1196
+ continue;
1197
+ }
1198
+ if (!interactive) {
1199
+ err('EVENT_NOT_INTERACTIVE', `<${n.type}> "${labelOf(n)}" cannot be clicked, so onClick would never run; put it on a button, link or other interactive element`, at);
1200
+ continue;
1201
+ }
1202
+ if (typeof rawId === 'string')
1203
+ nc.events?.set(rawId, { effects, ...(at ? { at } : {}) });
1204
+ }
1068
1205
  if (ids.has(id))
1069
1206
  err('DUPLICATE_ID', `Duplicate id "${id}" in the same stage (other location: ${rel(ids.get(id)) ?? 'unknown'})`, at);
1070
1207
  ids.set(id, at);
@@ -1073,7 +1210,7 @@ function toSceneNode(n, fallbackId, ids, nc, parentType) {
1073
1210
  if (v === undefined)
1074
1211
  continue; // 写了属性但值是 undefined(如 description={cond ? '…' : undefined})= 没写
1075
1212
  if (typeof v === 'function' && !isBind(v)) {
1076
- err('FUNCTION_PROP', `<${n.type}> prop ${k} is a function. Put behavior in the work's flow steps instead of event callbacks`, at);
1213
+ err('FUNCTION_PROP', `<${n.type}> prop ${k} is a function, and callbacks never run. Give a button its behavior as effects, for example onClick={set($.ui.open, true)}, or put it in the flow steps`, at);
1077
1214
  continue;
1078
1215
  }
1079
1216
  if (isNode(v)) {
@@ -1198,6 +1335,42 @@ function stepRouteBefore(steps, i, start) {
1198
1335
  }
1199
1336
  return route;
1200
1337
  }
1338
+ /**
1339
+ * 写法 v2:把被点元素的 onClick 合并进点击步骤(元素效果在前,步骤自己的效果在后)。
1340
+ * 按与 stepRouteBefore 相同的顺序跟踪路径,并且看得到合并进来的 go(),所以元素跳页之后的步骤在新页面上找目标。
1341
+ */
1342
+ function withElementEvents(steps, start, eventOf, warn) {
1343
+ let route = start;
1344
+ const stack = [];
1345
+ return steps.map((st) => {
1346
+ if (st.action.type === 'back')
1347
+ route = stack.pop() ?? route;
1348
+ let next = st;
1349
+ const target = st.action.type === 'click' ? st.action.target : null;
1350
+ const ev = target ? eventOf(route, target) : undefined;
1351
+ if (target && ev) {
1352
+ const writes = new Set(ev.effects.flatMap(e => e.type === 'set' || e.type === 'append' ? [e.path] : []));
1353
+ const repeated = st.effects.find((e) => (e.type === 'set' || e.type === 'append') && writes.has(e.path));
1354
+ if (repeated)
1355
+ warn('STEP_REPEATS_EVENT', `This click on ${target} writes ${repeated.path}, which its onClick already writes; delete the write from the step (onClick runs first, then the step's own effects)`, st.source);
1356
+ next = { ...st, effects: [...ev.effects, ...st.effects] };
1357
+ }
1358
+ for (const e of next.effects)
1359
+ if (e.type === 'go') {
1360
+ stack.push(route);
1361
+ route = e.route;
1362
+ }
1363
+ return next;
1364
+ });
1365
+ }
1366
+ /** 元素事件生成的本地反应用 on-<id> 作键;与作者写的 free 键重名时加序号。 */
1367
+ function eventFreeKey(target, taken) {
1368
+ const base = `on-${target}`.slice(0, 64);
1369
+ let key = base;
1370
+ for (let n = 2; Object.hasOwn(taken, key); n++)
1371
+ key = `${base.slice(0, 60)}-${n}`;
1372
+ return key;
1373
+ }
1201
1374
  /** id 是 frameId 本身或它的子孙(在同一棵树里)。 */
1202
1375
  function findIn(node, id) {
1203
1376
  if (node.id === id)