@joplo-app/core 0.2.16 → 0.2.18

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/dist/compile.js CHANGED
@@ -10,9 +10,10 @@
10
10
  import { isBind, isNode, bindPath, toCondition } from '@joplo-app/kit/node';
11
11
  import { BUILTIN_THEMES, COMPONENT_TYPES, DIRECTOR_LAYER, INTERACTIVE_TYPES, PAGE_LAYER, matchChoice, nodeLabel } from "./catalog.js";
12
12
  import { HOLD_MAX_SECONDS, HOLD_MIN_SECONDS, inShotFrame } from "./focus.js";
13
- import { choicesOf, commonPrefix } from "./player.js";
13
+ import { cameraAt, choicesOf, commonPrefix, stateAt } from "./player.js";
14
14
  import { CALLOUT_SIDES, LAYER_ICONS, Project, SCHEMA_VERSION } from "./schema.js";
15
15
  import { schemaDiagnostics } from "./schema-issues.js";
16
+ import { CONTENT_LOCALES, collectMessages, isContentLocale, nearestKey, pruneMessages } from "./content-i18n.js";
16
17
  import { DIAGRAM_GROUP_ICONS, DIAGRAM_NODE_KINDS, DIAGRAM_PINS, DIAGRAM_TONES, GRAPH_FAMILY, SEQUENCE_BLOCK_KINDS, SEQUENCE_FAMILY, attachLayouts, diagramsIn, isDiagramRoot } from "./diagram/index.js";
17
18
  const KNOWN = new Set(COMPONENT_TYPES);
18
19
  const OVERLAY = 'overlay';
@@ -36,6 +37,8 @@ export function compile(src, mode, opts = {}) {
36
37
  seenHints.add(key);
37
38
  diags.push({ severity, code, message, source: 'structure', ...(at ? { at: rel(at) } : {}) });
38
39
  };
40
+ /** flow({ from }) 接力:所有场景编译完后,按回放结果替换初始状态(见文末)。 */
41
+ const pendingFrom = new Map();
39
42
  const out = {
40
43
  schemaVersion: SCHEMA_VERSION,
41
44
  name: src.config.name,
@@ -208,7 +211,10 @@ export function compile(src, mode, opts = {}) {
208
211
  return { id: sceneId, optionId: ctx?.qid ?? null, route: route.path, name: `${page.title}${ctx ? ` · ${ctx.def.name}` : ''}`, viewport: page.viewport ?? 'desktop', root };
209
212
  };
210
213
  if (src.config.voice !== undefined && !voiceConfigOf(src.config.voice, true))
211
- err('VOICE_CONFIG_INVALID', `config({ voice }) must be { profile?: string, narrator?: string, roles?: { [roleKey]: string } } with non-empty strings; got ${JSON.stringify(src.config.voice)}`, src.config.source ?? `${src.config.file}:1:1`);
214
+ err('VOICE_CONFIG_INVALID', `config({ voice }) must be { profile?: string, narrator?: string, roles?: { [roleKey]: string }, locales?: { [locale]: { narrator?: string, roles?: { [roleKey]: string } } } } with non-empty strings; got ${JSON.stringify(src.config.voice)}`, src.config.source ?? `${src.config.file}:1:1`);
215
+ const i18nCfg = contentLocalesOf(src, err);
216
+ if (i18nCfg)
217
+ out.i18n = { default: i18nCfg[0], locales: i18nCfg, messages: Object.fromEntries(i18nCfg.slice(1).map((l) => [l, Object.fromEntries(Object.entries(src.locales?.[l] ?? {}).filter(([, v]) => typeof v === 'string' && v.trim()))])) };
212
218
  if (src.config.autoFocus !== undefined && typeof src.config.autoFocus !== 'boolean')
213
219
  err('AUTOFOCUS_INVALID', `config({ autoFocus }) must be true or false (default true); got ${JSON.stringify(src.config.autoFocus)}`, src.config.source ?? `${src.config.file}:1:1`);
214
220
  // 主题(D51):config.theme 必须是内置主题或 themes/<name>.css
@@ -378,9 +384,34 @@ export function compile(src, mode, opts = {}) {
378
384
  return finishTrace();
379
385
  };
380
386
  const scenarioIds = {};
381
- for (const [skey, fl] of Object.entries(def.scenarios ?? {})) {
387
+ // flow({ from }) 接力:按依赖顺序编译,被接的场景先编译,记下它结尾的路径与导演层;
388
+ // 接力场景的逐步校验(页面里找目标、焦点提示、镜头、自动字幕)都从那里开始,而不是默认起点
389
+ const scenarioDefs = def.scenarios ?? {};
390
+ const orderedKeys = [];
391
+ {
392
+ const placed = new Set();
393
+ const place = (k, seen) => {
394
+ if (placed.has(k) || seen.has(k))
395
+ return;
396
+ seen.add(k);
397
+ const dep = scenarioDefs[k]?.opts.from;
398
+ if (dep !== undefined && dep !== k && Object.hasOwn(scenarioDefs, dep))
399
+ place(dep, seen);
400
+ placed.add(k);
401
+ orderedKeys.push(k);
402
+ };
403
+ for (const k of Object.keys(scenarioDefs))
404
+ place(k, new Set());
405
+ }
406
+ /** 每个场景编译完之后的结尾:路径(按 go / back 推算)与导演层。 */
407
+ const scenarioEnd = new Map();
408
+ for (const skey of orderedKeys) {
409
+ const fl = scenarioDefs[skey];
382
410
  const sid = `${qid}.${skey}`;
383
- const start = fl.opts.start ?? touched[0] ?? src.config.home ?? [...ctxRoutes][0];
411
+ const fromEnd = fl.opts.from !== undefined && fl.opts.from !== skey ? scenarioEnd.get(fl.opts.from) : undefined;
412
+ if (fl.opts.from !== undefined && fl.opts.start !== undefined)
413
+ 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);
414
+ const start = fromEnd?.route ?? fl.opts.start ?? touched[0] ?? src.config.home ?? [...ctxRoutes][0];
384
415
  if (!start || !ctxRoutes.has(start)) {
385
416
  err('UNKNOWN_ROUTE', `Scenario ${sid} starts at unknown route ${start ?? '(none)'}`, fl.source);
386
417
  continue;
@@ -393,7 +424,19 @@ export function compile(src, mode, opts = {}) {
393
424
  }
394
425
  // 镜头状态(与 player.cameraAt 同一规则,逐步累积):判断焦点提示的目标在不在当前镜头里(D70)
395
426
  const frame = new Map();
396
- let director = hasLayers ? Object.keys(layers)[0] : PAGE_LAYER;
427
+ let director = fromEnd?.director ?? (hasLayers ? Object.keys(layers)[0] : PAGE_LAYER);
428
+ if (fl.opts.layer !== undefined) {
429
+ if (!hasLayers || !Object.hasOwn(layers, fl.opts.layer))
430
+ err('LAYER_UNKNOWN', `flow({ layer: ${JSON.stringify(fl.opts.layer)} }) is not a layer of option ${qid}${hasLayers ? ` (layers: ${Object.keys(layers).join(', ')})` : '; this option declares no layers'}`, fl.source);
431
+ else
432
+ director = fl.opts.layer;
433
+ }
434
+ if (fl.opts.from !== undefined) {
435
+ if (!Object.hasOwn(def.scenarios ?? {}, fl.opts.from) || fl.opts.from === skey)
436
+ err('FROM_UNKNOWN', `flow({ from: ${JSON.stringify(fl.opts.from)} }) must name another scenario key of option ${qid} (available: ${Object.keys(def.scenarios ?? {}).filter((k) => k !== skey).join(', ') || 'none'})`, fl.source);
437
+ else
438
+ pendingFrom.set(sid, { from: `${qid}.${fl.opts.from}`, state: fl.opts.state, layer: fl.opts.layer, at: fl.source });
439
+ }
397
440
  const stepKeys = new Set();
398
441
  const steps = fl.steps.map((st, i) => {
399
442
  if (st.key !== undefined) {
@@ -432,7 +475,7 @@ export function compile(src, mode, opts = {}) {
432
475
  effects.push({ type: 'stream', path: e.path, value: e.value });
433
476
  else if (e.type === 'toast')
434
477
  effects.push({ type: 'toast', text: e.text, tone: e.tone });
435
- else if (e.type === 'shot' || e.type === 'mark' || e.type === 'fork' || e.type === 'cue' || e.type === 'callout' || e.type === 'hold')
478
+ else if (e.type === 'shot' || e.type === 'mark' || e.type === 'fork' || e.type === 'cue' || e.type === 'callout' || e.type === 'hold' || e.type === 'camera')
436
479
  continue; // 镜头与焦点提示不是状态变化,下面单独归类
437
480
  else if (e.type === 'say') {
438
481
  if (typeof e.text === 'string' && e.text.trim())
@@ -465,6 +508,27 @@ export function compile(src, mode, opts = {}) {
465
508
  const sceneBefore = sceneFor.get(sceneOf(stepRouteBefore(fl.steps, i, start)));
466
509
  const sceneAfter = sceneFor.get(sceneOf(stepRouteBefore(fl.steps, i + 1, start)));
467
510
  const actionTarget = 'target' in st.action ? st.action.target : null;
511
+ /** 画布镜头(camera()):状态里记一份 ui.__camera,<Canvas> 按它取景;导演切到第一个目标所在的层。 */
512
+ const cameraTargets = [];
513
+ for (const e of st.effects) {
514
+ if (e.type !== 'camera')
515
+ continue;
516
+ const bad = (k, v, lo, hi) => v !== undefined && (typeof v !== 'number' || !Number.isFinite(v) || v < lo || v > hi) ? `${k} must be a number from ${lo} to ${hi}` : null;
517
+ const problem = bad('pad', e.pad, 0, 2000) ?? bad('zoom', e.zoom, 0.1, 10) ?? bad('ms', e.ms, 0, 10_000);
518
+ if (problem) {
519
+ err('CAMERA_INVALID', `camera(…): ${problem}`, st.source);
520
+ continue;
521
+ }
522
+ const missing = e.targets.filter((id) => (hasLayers ? !layersWith(id).length : !(sceneAfter && findIn(sceneAfter.root, id))));
523
+ if (missing.length) {
524
+ err('CAMERA_UNKNOWN', `camera(${missing.map((m) => JSON.stringify(m)).join(', ')}) target is not in ${hasLayers ? 'any layer' : 'the stage for this step'}; aim it at elements inside a <Canvas>`, st.source);
525
+ continue;
526
+ }
527
+ for (const id of e.targets)
528
+ if (!cameraTargets.includes(id))
529
+ cameraTargets.push(id);
530
+ effects.push({ type: 'set', path: 'ui.__camera', value: { targets: [...e.targets], ...(e.pad !== undefined ? { pad: e.pad } : {}), ...(e.zoom !== undefined ? { zoom: e.zoom } : {}), ...(e.ms !== undefined ? { ms: e.ms } : {}) } });
531
+ }
468
532
  for (const e of st.effects) {
469
533
  if (e.type === 'fork') {
470
534
  if (!Object.hasOwn(def.scenarios, e.scenario) || e.scenario === skey)
@@ -562,6 +626,9 @@ export function compile(src, mode, opts = {}) {
562
626
  }
563
627
  }
564
628
  }
629
+ // 画布镜头:导演切到镜头目标所在的层(优先于焦点提示与操作目标)
630
+ if (hasLayers && !directorLayer && cameraTargets.length)
631
+ directorLayer = layersWith(cameraTargets[0])[0] ?? null;
565
632
  // 没写 shot、写了焦点提示(D70):导演切到第一个提示目标所在的层(提示要被看见)
566
633
  if (hasLayers && !directorLayer && focusTargets.length)
567
634
  directorLayer = layersWith(focusTargets[0])[0] ?? null;
@@ -633,12 +700,25 @@ export function compile(src, mode, opts = {}) {
633
700
  description: fl.opts.description ?? '',
634
701
  caseIds: strip ? [] : (fl.opts.cases ?? []).filter((c) => fdef.cases?.[c]).map((c) => `${fid}.${c}`),
635
702
  mock: { label: fl.opts.mock ?? MOCK_LABEL[outcome], outcome, ...(fl.opts.mock === undefined ? { auto: true } : {}) },
636
- initial: { sceneId: sceneOf(start), ui: state.ui, data: state.data, inputs: state.inputs },
703
+ initial: { sceneId: sceneOf(start), ui: state.ui, data: state.data, inputs: state.inputs, ...(hasLayers && fl.opts.layer !== undefined && Object.hasOwn(layers, fl.opts.layer) ? { layer: fl.opts.layer } : {}) },
637
704
  steps,
638
705
  expected: fl.opts.expected ?? '',
639
706
  ...(fl.source ? { source: rel(fl.source) } : {}),
640
707
  };
641
708
  out.scenarios[sid] = sc;
709
+ scenarioEnd.set(skey, { route: stepRouteBefore(fl.steps, fl.steps.length, start), director });
710
+ }
711
+ // 按依赖顺序编译后,恢复作者声明的顺序(发布站按它当章节播放,情况里的场景列表也按它排)
712
+ {
713
+ const declared = Object.keys(scenarioDefs).map((k) => `${qid}.${k}`);
714
+ for (const id of declared)
715
+ if (Object.hasOwn(out.scenarios, id)) {
716
+ const v = out.scenarios[id];
717
+ delete out.scenarios[id];
718
+ out.scenarios[id] = v;
719
+ }
720
+ for (const list of Object.values(scenarioIds))
721
+ list.sort((a, b) => declared.indexOf(a) - declared.indexOf(b));
642
722
  }
643
723
  // 所有场景完成后再解析分叉(允许向后声明的场景),不把创作信息参与前缀比较。
644
724
  for (const sc of Object.values(out.scenarios)) {
@@ -716,7 +796,114 @@ export function compile(src, mode, opts = {}) {
716
796
  diags.push(...schemaDiagnostics(out, parsed.error.issues, { limit: 20, rel }));
717
797
  return { project: null, diagnostics: diags };
718
798
  }
719
- return { project: parsed.data, diagnostics: diags };
799
+ const project = pruneMessages(parsed.data);
800
+ // flow({ from }) 接力:初始状态 = 被接的场景最后一步之后的状态(路径、ui / data / inputs、导演层),再叠上本场景写的 state。
801
+ // 链式接力按依赖顺序解析;成环或被接的场景回放失败时报错。
802
+ if (pendingFrom.size) {
803
+ const done = new Set();
804
+ const visiting = new Set();
805
+ const resolve = (sid) => {
806
+ const p = pendingFrom.get(sid);
807
+ if (!p || done.has(sid))
808
+ return true;
809
+ if (visiting.has(sid)) {
810
+ err('FROM_CYCLE', `Scenario ${sid} continues from itself through flow({ from }); break the cycle`, p.at);
811
+ return false;
812
+ }
813
+ visiting.add(sid);
814
+ const ok = resolve(p.from);
815
+ visiting.delete(sid);
816
+ if (!ok)
817
+ return false;
818
+ const target = project.scenarios[sid];
819
+ const prev = project.scenarios[p.from];
820
+ if (!target || !prev)
821
+ return false;
822
+ try {
823
+ const end = stateAt(project, p.from, prev.steps.length);
824
+ const hasLayers = Object.keys(project.options[target.optionId]?.layers ?? {}).length > 0;
825
+ const layer = p.layer ?? (hasLayers ? cameraAt(project, p.from, prev.steps.length).directorLayer : undefined);
826
+ const merged = mergeState({ ui: end.ui, data: end.data, inputs: end.inputs }, p.state);
827
+ target.initial = { sceneId: end.sceneId, ui: merged.ui, data: merged.data, inputs: merged.inputs, ...(layer ? { layer } : {}) };
828
+ }
829
+ catch (e) {
830
+ err('FROM_FAILED', `Scenario ${sid} continues from ${p.from}, which does not replay: ${e.message}`, p.at);
831
+ return false;
832
+ }
833
+ done.add(sid);
834
+ return true;
835
+ };
836
+ for (const sid of pendingFrom.keys())
837
+ resolve(sid);
838
+ if (diags.some((d) => d.severity === 'error'))
839
+ return { project: null, diagnostics: diags };
840
+ }
841
+ if (mode === 'dev' && project.i18n) {
842
+ const stale = localeDiagnostics(project, src, diags);
843
+ project.i18n = { ...project.i18n, stale };
844
+ }
845
+ return { project, diagnostics: diags };
846
+ }
847
+ /** config.locales(D84):非空、不重复、都是支持的语言;第一个是默认语言。没写时为 null。 */
848
+ function contentLocalesOf(src, err) {
849
+ const v = src.config.locales;
850
+ const at = src.config.source ?? `${src.config.file}:1:1`;
851
+ if (v === undefined) {
852
+ for (const [l, f] of Object.entries(src.localeFiles ?? {}))
853
+ err('LOCALES_UNDECLARED', `${f} exists but joplo.config.ts has no locales; add locales: ['<source language>', '${l}'] (the first is the language the source files are written in)`, at);
854
+ return null;
855
+ }
856
+ const bad = !Array.isArray(v) || !v.length ? 'must be a non-empty array' : v.find((x) => !isContentLocale(x)) !== undefined ? `contains "${String(v.find((x) => !isContentLocale(x)))}"` : new Set(v).size !== v.length ? 'lists a language twice' : null;
857
+ if (bad) {
858
+ err('LOCALES_INVALID', `config({ locales }) ${bad}. Write the source language first, for example locales: ['zh-CN', 'en', 'ja']; supported: ${CONTENT_LOCALES.join(', ')}`, at);
859
+ return null;
860
+ }
861
+ for (const [l, f] of Object.entries(src.localeFiles ?? {}))
862
+ if (!v.includes(l))
863
+ err('LOCALES_UNDECLARED', `${f} is not in config({ locales }); add '${l}' to locales or delete the file`, at);
864
+ if (src.localeFiles?.[v[0]])
865
+ err('LOCALES_UNDECLARED', `${src.localeFiles[v[0]]} translates the default language ${v[0]}; the source files are already in ${v[0]}, so delete it (or put another language first in locales)`, at);
866
+ return [...v];
867
+ }
868
+ /**
869
+ * 译文的检查(D84,只在 dev):每种语言一条 I18N_MISSING(缺多少、前几条)、原文改过的每条一条 I18N_STALE(附最接近的旧条目)、
870
+ * 没人用的旧条目一条 I18N_UNUSED。返回每种语言的过期条数,给看板菜单显示。
871
+ */
872
+ function localeDiagnostics(project, src, diags) {
873
+ const i18n = project.i18n;
874
+ const uses = collectMessages(project);
875
+ const texts = new Set(uses.map((u) => u.text));
876
+ const stale = {};
877
+ const q = (s) => JSON.stringify(s.length > 40 ? `${s.slice(0, 40)}…` : s);
878
+ for (const l of i18n.locales.slice(1)) {
879
+ const file = src.localeFiles?.[l] ?? `locales/${l}.json`;
880
+ const table = src.locales?.[l] ?? {};
881
+ const unused = Object.keys(table).filter((k) => !texts.has(k) && typeof table[k] === 'string' && table[k].trim());
882
+ const missing = uses.filter((u) => !(typeof table[u.text] === 'string' && table[u.text].trim()));
883
+ const plain = [];
884
+ const matched = new Set();
885
+ let n = 0;
886
+ for (const m of missing) {
887
+ const old = nearestKey(m.text, unused);
888
+ if (old === null) {
889
+ plain.push(m);
890
+ continue;
891
+ }
892
+ matched.add(old);
893
+ n++;
894
+ diags.push({ severity: 'warning', code: 'I18N_STALE', message: `${file}: no translation for ${q(m.text)}; the closest old entry is ${q(old)}: ${q(table[old])} (the source text changed). Update the key and translation`, source: 'structure', ...(m.at ? { at: m.at } : {}) });
895
+ }
896
+ stale[l] = n;
897
+ if (plain.length) {
898
+ const first = plain.slice(0, 5).map((m) => q(m.text)).join(', ');
899
+ const hint = src.localeFiles?.[l] ? `translate them in ${file}` : `run npx joplo i18n add ${l}, then translate ${file}`;
900
+ diags.push({ severity: 'warning', code: 'I18N_MISSING', message: `${l}: ${plain.length} of ${uses.length} texts have no translation (${first}${plain.length > 5 ? `, +${plain.length - 5} more` : ''}); ${hint}. Viewers see the ${i18n.default} source text for them`, source: 'structure', at: `${file}:1:1` });
901
+ }
902
+ const leftover = unused.filter((k) => !matched.has(k));
903
+ if (leftover.length)
904
+ diags.push({ severity: 'info', code: 'I18N_UNUSED', message: `${file}: ${leftover.length} entries are not used by any text (${leftover.slice(0, 3).map(q).join(', ')}${leftover.length > 3 ? ', …' : ''}); delete them or run npx joplo i18n add ${l} --prune`, source: 'structure', at: `${file}:1:1` });
905
+ }
906
+ return stale;
720
907
  }
721
908
  // ---------- 帮助函数 ----------
722
909
  /** 角色的颜色(D56):没写 color 时按声明顺序取。 */
@@ -1181,24 +1368,46 @@ function voiceConfigOf(v, strict = false) {
1181
1368
  const o = v;
1182
1369
  const str = (x) => (typeof x === 'string' && x.trim() ? x.trim() : null);
1183
1370
  for (const k of Object.keys(o))
1184
- if (!['profile', 'narrator', 'roles'].includes(k))
1371
+ if (!['profile', 'narrator', 'roles', 'locales'].includes(k))
1185
1372
  return null;
1186
1373
  if (o.profile !== undefined && !str(o.profile))
1187
1374
  return null;
1188
- if (o.narrator !== undefined && !str(o.narrator))
1375
+ /** 旁白与角色(顶层,或某种语言下);形状不对时返回 false。 */
1376
+ const voices = (x) => {
1377
+ if (x.narrator !== undefined && !str(x.narrator))
1378
+ return false;
1379
+ let roles;
1380
+ if (x.roles !== undefined) {
1381
+ if (!x.roles || typeof x.roles !== 'object' || Array.isArray(x.roles))
1382
+ return false;
1383
+ roles = {};
1384
+ for (const [k, val] of Object.entries(x.roles)) {
1385
+ const s = str(val);
1386
+ if (!s)
1387
+ return false;
1388
+ roles[k] = s;
1389
+ }
1390
+ }
1391
+ return { ...(str(x.narrator) ? { narrator: str(x.narrator) } : {}), ...(roles && Object.keys(roles).length ? { roles } : {}) };
1392
+ };
1393
+ const top = voices(o);
1394
+ if (!top)
1189
1395
  return null;
1190
- let roles;
1191
- if (o.roles !== undefined) {
1192
- if (!o.roles || typeof o.roles !== 'object' || Array.isArray(o.roles))
1396
+ let locales;
1397
+ if (o.locales !== undefined) {
1398
+ if (!o.locales || typeof o.locales !== 'object' || Array.isArray(o.locales))
1193
1399
  return null;
1194
- roles = {};
1195
- for (const [k, val] of Object.entries(o.roles)) {
1196
- const s = str(val);
1197
- if (!s)
1400
+ locales = {};
1401
+ for (const [l, x] of Object.entries(o.locales)) {
1402
+ if (!x || typeof x !== 'object' || Array.isArray(x) || Object.keys(x).some((k) => k !== 'narrator' && k !== 'roles'))
1403
+ return null;
1404
+ const vv = voices(x);
1405
+ if (!vv)
1198
1406
  return null;
1199
- roles[k] = s;
1407
+ if (Object.keys(vv).length)
1408
+ locales[l] = vv;
1200
1409
  }
1201
1410
  }
1202
- const out = { ...(str(o.profile) ? { profile: str(o.profile) } : {}), ...(str(o.narrator) ? { narrator: str(o.narrator) } : {}), ...(roles && Object.keys(roles).length ? { roles } : {}) };
1411
+ const out = { ...(str(o.profile) ? { profile: str(o.profile) } : {}), ...top, ...(locales && Object.keys(locales).length ? { locales } : {}) };
1203
1412
  return Object.keys(out).length ? out : strict ? out : null;
1204
1413
  }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * 作者内容多语言(D84):源文件用默认语言写,译文放在 `locales/<语言>.json`(原文 → 译文)。
3
+ *
4
+ * - 编译时把译文放进 IR 的 `i18n.messages`(只留这份 IR 用得到的条目,见 pruneMessages),默认语言没有译文表。
5
+ * - 看板、发布站、服务端都用 localizeProject 把整份 IR 换成某种语言:同一个原文在任何位置都换成同一个译文,
6
+ * 所以状态值与条件里的同一个字面量一起换,比较结果不变;结构字段(id、路径、连线两端、颜色等)从不翻译。
7
+ * - collectMessages 列出这份 IR 里要翻译的原文(joplo i18n add 与 check 用)。状态里的字符串只收显示出来的
8
+ * (路径和某个绑定重叠),输入值与状态值跳过像代码的单个 ASCII 词(id、邮箱、网址)。
9
+ * - 内容语言只能是界面支持的 10 种(D57),观众选界面语言就是选内容语言;项目没有这种语言时退回默认语言。
10
+ */
11
+ import type { Project } from './schema.js';
12
+ /** 内容语言 = 界面支持的 10 种语言(与网页、服务端的 locale 列表一致)。 */
13
+ export declare const CONTENT_LOCALES: readonly ["en", "zh-CN", "zh-TW", "ja", "ko", "es", "fr", "de", "pt-BR", "ru"];
14
+ export type ContentLocale = (typeof CONTENT_LOCALES)[number];
15
+ export declare const isContentLocale: (v: unknown) => v is ContentLocale;
16
+ export type ContentI18n = {
17
+ default: string;
18
+ locales: string[];
19
+ messages: Record<string, Record<string, string>>;
20
+ };
21
+ export type MessageUse = {
22
+ text: string;
23
+ at?: string;
24
+ };
25
+ /** 这份 IR 里要翻译的原文(去重,按首次出现的顺序;at 是第一次出现的源位置)。 */
26
+ export declare function collectMessages(p: Project): MessageUse[];
27
+ /** 把 IR 换成某种语言;没有 i18n、语言是默认语言或没有译文表时原样返回。 */
28
+ export declare function localizeProject(p: Project, locale: string | null | undefined): Project;
29
+ /** 观众的界面语言对应的内容语言:项目有这种语言就用它,否则退回默认语言(用户 2026-11-08 选定)。没有 i18n 时为 null。 */
30
+ export declare function contentLocaleFor(p: Pick<Project, 'i18n'>, uiLocale: string | null | undefined): string | null;
31
+ /** 只留这份 IR 用得到的译文(编译、范围分享之后调用,不带别的功能的文字)。 */
32
+ export declare function pruneMessages(p: Project): Project;
33
+ /** 最接近的旧条目(原文改过时给 check 提示):编辑距离不超过较长一方的一半;没有时为 null。 */
34
+ export declare function nearestKey(text: string, candidates: readonly string[]): string | null;
@@ -0,0 +1,242 @@
1
+ /** 内容语言 = 界面支持的 10 种语言(与网页、服务端的 locale 列表一致)。 */
2
+ export const CONTENT_LOCALES = ['en', 'zh-CN', 'zh-TW', 'ja', 'ko', 'es', 'fr', 'de', 'pt-BR', 'ru'];
3
+ export const isContentLocale = (v) => typeof v === 'string' && CONTENT_LOCALES.includes(v);
4
+ const BIND = /^\$(ui|data|inputs)(\.|$)/;
5
+ const isBinding = (s) => BIND.test(s);
6
+ /** 不翻译的属性:引用、样式与枚举。值是字符串时也原样保留。 */
7
+ const STRUCTURAL = new Set(['from', 'to', 'accessor', 'target', 'href', 'src', 'type', 'kind', 'tone', 'variant', 'color', 'c', 'bg', 'size', 'radius', 'position', 'direction', 'icon', 'pin', 'states', 'style', 'layout', 'orientation', 'align', 'justify', 'ff', 'fw', 'fz', 'ta', 'shadow', 'dir', 'lang', 'id', 'key', 'side', 'tt', 'td', 'fs', 'lh', 'display', 'pos', 'inset', 'top', 'left', 'right', 'bottom',
8
+ 'p', 'px', 'py', 'pt', 'pb', 'pl', 'pr', 'm', 'mx', 'my', 'mt', 'mb', 'ml', 'mr', 'w', 'h', 'maw', 'mah', 'miw', 'mih', 'gap', 'rowGap', 'columnGap', 'gutter', 'spacing', 'verticalSpacing', 'horizontalSpacing',
9
+ 'cols', 'span', 'offset', 'order', 'wrap', 'grow', 'mode', 'aspect', 'fit', 'inputMode', 'autoComplete', 'visibleFrom', 'hiddenFrom', 'transition', 'transitionProps', 'loaderProps', 'overlayProps', 'zIndex', 'opacity']);
10
+ /** 选项、列表项(数组里的对象)的 value 是选项的身份:照常按同一张表换(和状态值、选择动作的值一致),但收集时当作普通属性(像 id 的单词不收)。 */
11
+ const ITEM_VALUE = 'value';
12
+ /** 显示文字的属性:收集时不跳过单个英文词(英文项目的按钮名就是一个词)。其余属性里的单个 ASCII 词多半是枚举(sm、blue),不收。 */
13
+ const DISPLAY_PROPS = new Set(['text', 'label', 'title', 'description', 'placeholder', 'aria-label', 'alt', 'error', 'hint', 'caption', 'message', 'content', 'subtitle', 'tooltip', 'leftSection', 'rightSection', 'name', 'value', 'data', 'records', 'labels', 'emptyText', 'actionLabel', 'sub', 'badge', 'status', 'items']);
14
+ /** 每一行都是邮箱或网址:不翻译。 */
15
+ const addressLike = (s) => s.split('\n').every((l) => /^\s*([^\s@]+@[^\s@]+|https?:\/\/\S+)\s*$/.test(l));
16
+ /** 有没有字母(任何文字):纯数字、符号不翻译。 */
17
+ const hasLetter = (s) => /\p{L}/u.test(s);
18
+ /** 像代码的单个 ASCII 词:id、邮箱、网址、命令参数。只对状态值和输入值跳过。 */
19
+ const codeLike = (s) => /^[\x21-\x7e]+$/.test(s.trim());
20
+ function mapDeep(v, visit, path, inItem = false, itemValue = false) {
21
+ if (typeof v === 'string')
22
+ return isBinding(v) ? v : visit(v, path, itemValue);
23
+ if (Array.isArray(v))
24
+ return v.map((x, i) => mapDeep(x, visit, `${path}.${i}`, true));
25
+ if (v && typeof v === 'object') {
26
+ const out = {};
27
+ for (const [k, x] of Object.entries(v))
28
+ out[k] = STRUCTURAL.has(k) ? x : mapDeep(x, visit, `${path}.${k}`, false, inItem && k === ITEM_VALUE);
29
+ return out;
30
+ }
31
+ return v;
32
+ }
33
+ function mapCondition(c, visit) {
34
+ if (!c)
35
+ return c;
36
+ if ('eq' in c)
37
+ return { eq: [c.eq[0], mapDeep(c.eq[1], (s) => visit(s, 'state'), '')] };
38
+ if ('neq' in c)
39
+ return { neq: [c.neq[0], mapDeep(c.neq[1], (s) => visit(s, 'state'), '')] };
40
+ if ('in' in c)
41
+ return { in: [c.in[0], c.in[1].map((x) => mapDeep(x, (s) => visit(s, 'state'), ''))] };
42
+ if ('and' in c)
43
+ return { and: c.and.map((x) => mapCondition(x, visit)) };
44
+ if ('or' in c)
45
+ return { or: c.or.map((x) => mapCondition(x, visit)) };
46
+ if ('not' in c)
47
+ return { not: mapCondition(c.not, visit) };
48
+ return c;
49
+ }
50
+ function mapNode(n, visit) {
51
+ const out = { ...n };
52
+ if (n.props) {
53
+ const props = {};
54
+ for (const [k, v] of Object.entries(n.props))
55
+ props[k] = STRUCTURAL.has(k) ? v : mapDeep(v, (s, _p, itemValue) => visit(s, DISPLAY_PROPS.has(k) && !itemValue ? 'text' : 'prop', n.source), '');
56
+ out.props = props;
57
+ }
58
+ if (n.children)
59
+ out.children = n.children.map((c) => mapNode(c, visit));
60
+ if (n.when)
61
+ out.when = mapCondition(n.when, visit);
62
+ if (n.disabled && typeof n.disabled === 'object')
63
+ out.disabled = mapCondition(n.disabled, visit);
64
+ if (n.redact && typeof n.redact === 'object')
65
+ out.redact = mapCondition(n.redact, visit);
66
+ if (n.disabledReason && !isBinding(n.disabledReason))
67
+ out.disabledReason = visit(n.disabledReason, 'text', n.source);
68
+ // 设计备注(看板检查元素时显示;发布站没有)
69
+ if (n.note)
70
+ out.note = visit(n.note, 'text', n.source);
71
+ return out;
72
+ }
73
+ const t = (s, visit, at) => (s ? visit(s, 'text', at) : s);
74
+ const stateMap = (v, base, visit) => mapDeep(v, (s, p) => visit(s, 'state', undefined, `${base}${p}`), '');
75
+ function mapStep(st, visit) {
76
+ const at = st.source;
77
+ const a = st.action;
78
+ const action = a.type === 'card' ? { ...a, title: visit(a.title, 'text', at), ...(a.sub ? { sub: visit(a.sub, 'text', at) } : {}), ...(a.points ? { points: a.points.map((p) => visit(p, 'text', at)) } : {}) }
79
+ : a.type === 'type' || a.type === 'select' ? { ...a, value: visit(a.value, 'typed', at) }
80
+ : a.type === 'event' ? { ...a, name: visit(a.name, 'text', at) }
81
+ : a;
82
+ const effects = st.effects.map((e) => {
83
+ if (e.type === 'set' || e.type === 'append')
84
+ return { ...e, value: stateMap(e.value, e.path, visit) };
85
+ if (e.type === 'stream')
86
+ return { ...e, value: visit(e.value, 'text', at) };
87
+ if (e.type === 'toast' || e.type === 'complete')
88
+ return { ...e, text: visit(e.text, 'text', at) };
89
+ return e;
90
+ });
91
+ return {
92
+ ...st,
93
+ action,
94
+ // 自动字幕是英文兜底,网页按 captionAuto 生成;只换它引用的元素名和值
95
+ caption: st.captionAuto ? st.caption : visit(st.caption, 'text', at),
96
+ ...(st.captionAuto ? { captionAuto: { ...st.captionAuto, label: visit(st.captionAuto.label, 'state'), ...(st.captionAuto.value !== undefined ? { value: visit(st.captionAuto.value, 'state') } : {}) } } : {}),
97
+ effects,
98
+ ...(st.explain ? { explain: visit(st.explain, 'text', at) } : {}),
99
+ ...(st.say ? { say: visit(st.say, 'text', at) } : {}),
100
+ ...(st.narrate ? { narrate: visit(st.narrate, 'text', at) } : {}),
101
+ ...(st.callouts ? { callouts: st.callouts.map((c) => ({ ...c, text: visit(c.text, 'text', at) })) } : {}),
102
+ marks: st.marks.map((m) => (m.note ? { ...m, note: visit(m.note, 'text', at) } : m)),
103
+ forks: st.forks.map((f) => ({ ...f, label: visit(f.label, 'text', at) })),
104
+ };
105
+ }
106
+ function mapScenario(sc, visit) {
107
+ const at = sc.source;
108
+ return {
109
+ ...sc,
110
+ name: visit(sc.name, 'text', at),
111
+ description: t(sc.description, visit, at) ?? '',
112
+ ...(sc.expected !== undefined ? { expected: t(sc.expected, visit, at) ?? '' } : {}),
113
+ mock: sc.mock.auto ? sc.mock : { ...sc.mock, label: visit(sc.mock.label, 'text', at) },
114
+ initial: { ...sc.initial, ui: stateMap(sc.initial.ui, 'ui', visit), data: stateMap(sc.initial.data, 'data', visit), inputs: stateMap(sc.initial.inputs, 'inputs', visit) },
115
+ steps: sc.steps.map((st) => mapStep(st, visit)),
116
+ };
117
+ }
118
+ /** 对 IR 里所有作者内容字符串调用 visit,返回替换后的新 IR(不改原对象)。 */
119
+ function mapProject(p, visit) {
120
+ // 缺字段(旧 IR、测试里的最小 IR)原样保留,不补空对象
121
+ const obj = (o, f) => (o ? Object.fromEntries(Object.entries(o).map(([k, v]) => [k, f(v)])) : o);
122
+ const arr = (a, f) => (a ? a.map(f) : a);
123
+ return {
124
+ ...p,
125
+ name: visit(p.name, 'text'),
126
+ description: t(p.description, visit) ?? '',
127
+ routes: obj(p.routes, (r) => ({ ...r, title: visit(r.title, 'text', r.source) })),
128
+ features: obj(p.features, (f) => ({ ...f, name: visit(f.name, 'text', f.source), goal: visit(f.goal, 'text', f.source), roles: arr(f.roles, (r) => ({ ...r, name: visit(r.name, 'text', f.source), ...(r.desc ? { desc: visit(r.desc, 'text', f.source) } : {}) })), constraints: arr(f.constraints, (c) => ({ ...c, text: visit(c.text, 'text', f.source) })) })),
129
+ options: obj(p.options, (o) => ({
130
+ ...o,
131
+ name: visit(o.name, 'text', o.source),
132
+ idea: visit(o.idea, 'text', o.source),
133
+ ...(o.decisionFocus !== undefined ? { decisionFocus: t(o.decisionFocus, visit, o.source) ?? '' } : {}),
134
+ tradeoffs: arr(o.tradeoffs, (x) => visit(x, 'text', o.source)),
135
+ coverage: obj(o.coverage, (c) => (c.reason ? { ...c, reason: visit(c.reason, 'text', o.source) } : c)),
136
+ layers: obj(o.layers, (l) => ({ ...l, title: visit(l.title, 'text', o.source) })),
137
+ })),
138
+ // 创作侧信息(看板与评审里显示;发布站不带,所以发布 IR 里收不到也不带译文)
139
+ cases: obj(p.cases, (c) => ({ ...c, title: visit(c.title, 'text', c.source), expected: t(c.expected, visit, c.source) ?? '' })),
140
+ rules: obj(p.rules, (r) => ({ ...r, text: visit(r.text, 'text', r.source) })),
141
+ issues: obj(p.issues, (q) => ({ ...q, text: visit(q.text, 'text', q.source) })),
142
+ scenes: obj(p.scenes, (s) => ({ ...s, root: mapNode(s.root, visit) })),
143
+ scenarios: obj(p.scenarios, (s) => mapScenario(s, visit)),
144
+ };
145
+ }
146
+ /** 画面里显示出来的状态路径(文字、属性、禁用原因里的绑定)。 */
147
+ function boundPaths(p) {
148
+ const out = new Set();
149
+ const add = (s) => {
150
+ if (isBinding(s))
151
+ out.add(s.slice(1));
152
+ };
153
+ const walk = (v) => {
154
+ if (typeof v === 'string')
155
+ add(v);
156
+ else if (Array.isArray(v))
157
+ v.forEach(walk);
158
+ else if (v && typeof v === 'object')
159
+ Object.values(v).forEach(walk);
160
+ };
161
+ const node = (n) => {
162
+ if (n.props)
163
+ for (const [k, v] of Object.entries(n.props))
164
+ if (k !== 'style')
165
+ walk(v);
166
+ if (n.disabledReason)
167
+ add(n.disabledReason);
168
+ n.children?.forEach(node);
169
+ };
170
+ for (const s of Object.values(p.scenes))
171
+ node(s.root);
172
+ return [...out];
173
+ }
174
+ const overlaps = (a, b) => a === b || a.startsWith(`${b}.`) || b.startsWith(`${a}.`);
175
+ /** 这份 IR 里要翻译的原文(去重,按首次出现的顺序;at 是第一次出现的源位置)。 */
176
+ export function collectMessages(p) {
177
+ const shown = boundPaths(p);
178
+ const seen = new Map();
179
+ mapProject(p, (s, kind, at, path) => {
180
+ const text = s;
181
+ if (!text.trim() || !hasLetter(text) || addressLike(text) || seen.has(text))
182
+ return s;
183
+ if (kind === 'state' && (!path || codeLike(text) || !shown.some((b) => overlaps(b, path))))
184
+ return s;
185
+ if ((kind === 'typed' || kind === 'prop') && codeLike(text))
186
+ return s;
187
+ seen.set(text, { text, ...(at ? { at } : {}) });
188
+ return s;
189
+ });
190
+ return [...seen.values()];
191
+ }
192
+ /** 把 IR 换成某种语言;没有 i18n、语言是默认语言或没有译文表时原样返回。 */
193
+ export function localizeProject(p, locale) {
194
+ const i18n = p.i18n;
195
+ if (!i18n || !locale || locale === i18n.default)
196
+ return p;
197
+ const table = i18n.messages[locale];
198
+ if (!table || !Object.keys(table).length)
199
+ return p;
200
+ return mapProject(p, (s) => (Object.hasOwn(table, s) && table[s] ? table[s] : s));
201
+ }
202
+ /** 观众的界面语言对应的内容语言:项目有这种语言就用它,否则退回默认语言(用户 2026-11-08 选定)。没有 i18n 时为 null。 */
203
+ export function contentLocaleFor(p, uiLocale) {
204
+ const i18n = p.i18n;
205
+ if (!i18n)
206
+ return null;
207
+ return uiLocale && i18n.locales.includes(uiLocale) ? uiLocale : i18n.default;
208
+ }
209
+ /** 只留这份 IR 用得到的译文(编译、范围分享之后调用,不带别的功能的文字)。 */
210
+ export function pruneMessages(p) {
211
+ if (!p.i18n)
212
+ return p;
213
+ const used = new Set(collectMessages(p).map((m) => m.text));
214
+ const messages = Object.fromEntries(Object.entries(p.i18n.messages).map(([l, table]) => [l, Object.fromEntries(Object.entries(table).filter(([k, v]) => used.has(k) && v))]));
215
+ return { ...p, i18n: { ...p.i18n, messages } };
216
+ }
217
+ /** 编辑距离(按码点)。 */
218
+ function distance(a, b) {
219
+ const x = [...a], y = [...b];
220
+ let prev = Array.from({ length: y.length + 1 }, (_, j) => j);
221
+ for (let i = 1; i <= x.length; i++) {
222
+ const cur = [i];
223
+ for (let j = 1; j <= y.length; j++)
224
+ cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (x[i - 1] === y[j - 1] ? 0 : 1));
225
+ prev = cur;
226
+ }
227
+ return prev[y.length];
228
+ }
229
+ /** 最接近的旧条目(原文改过时给 check 提示):编辑距离不超过较长一方的一半;没有时为 null。 */
230
+ export function nearestKey(text, candidates) {
231
+ let best = null;
232
+ let bestD = Infinity;
233
+ for (const c of candidates) {
234
+ const d = distance(text, c);
235
+ const limit = Math.max([...text].length, [...c].length) / 2;
236
+ if (d <= limit && d < bestD) {
237
+ best = c;
238
+ bestD = d;
239
+ }
240
+ }
241
+ return best;
242
+ }