@joplo-app/core 0.2.7 → 0.2.8

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
@@ -9,13 +9,15 @@
9
9
  */
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
+ import { HOLD_MAX_SECONDS, HOLD_MIN_SECONDS, inShotFrame } from "./focus.js";
12
13
  import { choicesOf, commonPrefix } from "./player.js";
13
- import { LAYER_ICONS, Project, SCHEMA_VERSION } from "./schema.js";
14
+ import { CALLOUT_SIDES, LAYER_ICONS, Project, SCHEMA_VERSION } from "./schema.js";
14
15
  import { schemaDiagnostics } from "./schema-issues.js";
16
+ 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";
15
17
  const KNOWN = new Set(COMPONENT_TYPES);
16
18
  const OVERLAY = 'overlay';
17
19
  const MOCK_LABEL = { success: 'Mock success', failure: 'Mock failure', denied: 'Mock permission denied', other: 'Mock' };
18
- export function compile(src, mode) {
20
+ export function compile(src, mode, opts = {}) {
19
21
  /** 所有方案都参与(dev、review);创作侧信息要去掉(publish、review)。 */
20
22
  const allOpts = mode !== 'publish';
21
23
  const strip = mode !== 'dev';
@@ -23,11 +25,24 @@ export function compile(src, mode) {
23
25
  const rel = (s) => (s ? relSource(src.root, s) : undefined);
24
26
  const err = (code, message, at, ref) => diags.push({ severity: 'error', code, message, source: 'reference', ...(at ? { at: rel(at) } : {}), ...(ref ? { ref } : {}) });
25
27
  const warn = (code, message, at, ref) => diags.push({ severity: 'warning', code, message, source: 'structure', ...(at ? { at: rel(at) } : {}), ...(ref ? { ref } : {}) });
28
+ /** 元素树里的诊断:同一份 JSX 展开到多个画面时,提示类(warning / info)只报一次。 */
29
+ const seenHints = new Set();
30
+ const report = (code, message, at, severity = 'error') => {
31
+ if (severity === 'error')
32
+ return err(code, message, at);
33
+ const key = `${code}|${at}|${message}`;
34
+ if (seenHints.has(key))
35
+ return;
36
+ seenHints.add(key);
37
+ diags.push({ severity, code, message, source: 'structure', ...(at ? { at: rel(at) } : {}) });
38
+ };
26
39
  const out = {
27
40
  schemaVersion: SCHEMA_VERSION,
28
41
  name: src.config.name,
29
42
  description: src.config.description ?? '',
30
43
  theme: src.config.theme ?? 'sketch',
44
+ // 默认焦点行为(D70):只有作者写了才进 IR(缺省 = 开启),不用这个开关的项目 IR 不变
45
+ ...(typeof src.config.autoFocus === 'boolean' ? { autoFocus: src.config.autoFocus } : {}),
31
46
  themes: { ...(src.themes ?? {}) },
32
47
  mode,
33
48
  routes: {},
@@ -187,9 +202,11 @@ export function compile(src, mode) {
187
202
  const base = tree;
188
203
  const rootJ = { ...base, type: base.type === '#fragment' ? 'div' : base.type, children: [...base.children, ...overlays] };
189
204
  const ids = new Map();
190
- const root = toSceneNode(rootJ, 'root', ids, (code, msg, at) => err(code, msg, at), rel);
205
+ const root = toSceneNode(rootJ, 'root', ids, report, rel);
191
206
  return { id: sceneId, optionId: ctx?.qid ?? null, route: route.path, name: `${page.title}${ctx ? ` · ${ctx.def.name}` : ''}`, viewport: page.viewport ?? 'desktop', root };
192
207
  };
208
+ if (src.config.autoFocus !== undefined && typeof src.config.autoFocus !== 'boolean')
209
+ 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`);
193
210
  // 主题(D51):config.theme 必须是内置主题或 themes/<name>.css
194
211
  {
195
212
  const t = src.config.theme ?? 'sketch';
@@ -252,7 +269,7 @@ export function compile(src, mode) {
252
269
  }
253
270
  const rootJ = nodes.length === 1 ? nodes[0] : { ...nodes[0], type: 'div', props: {}, children: nodes };
254
271
  const ids = new Map();
255
- const root = toSceneNode(rootJ, `layer_${lk}`, ids, (code, msg, where) => err(code, msg, where), rel);
272
+ const root = toSceneNode(rootJ, `layer_${lk}`, ids, report, rel);
256
273
  const sceneId = `${qid}~${lk}`;
257
274
  const scene = { id: sceneId, optionId: qid, route: layerRoute, name: `${ld.title} · ${def.name}`, viewport: ld.viewport ?? 'desktop', root, layer: lk };
258
275
  addScene(scene);
@@ -281,7 +298,7 @@ export function compile(src, mode) {
281
298
  const d = diagrams.find((x) => ids.every((t) => has(x, t)));
282
299
  if (!d) {
283
300
  const missing = ids.find((t) => !diagrams.some((x) => has(x, t)));
284
- err('TRACE_UNKNOWN', missing ? `${shown} contains "${missing}", which is not a node or edge id in any Diagram` : `${shown} has nodes from different Diagrams`, at);
301
+ err('TRACE_UNKNOWN', missing ? `${shown} contains "${missing}", which is not a node, group, edge, state, transition, actor or message id in any Diagram / StateMachine / Sequence` : `${shown} mixes elements from different diagrams; trace one diagram at a time`, at);
285
302
  return null;
286
303
  }
287
304
  const nodes = [];
@@ -290,6 +307,25 @@ export function compile(src, mode) {
290
307
  if (!nodes.includes(n))
291
308
  nodes.push(n);
292
309
  };
310
+ /** 节点(或分组)自己是分组时连同它算进去,再加上它的各级父分组。 */
311
+ const groupsOfNode = (n) => [...(d.groupIds.has(n) ? [n] : []), ...(d.groupsOf.get(n) ?? [])];
312
+ const finishTrace = () => {
313
+ if (tmode === 'skip')
314
+ return { mode: tmode, nodes, edges, ...(d.type === 'Sequence' ? { targets: [] } : {}) };
315
+ const all = [...new Set(nodes.flatMap(groupsOfNode))];
316
+ const last = nodes[nodes.length - 1];
317
+ // 失败只标红终点所在的最内层分组(终点本身是分组时就是它);外层分组照常 active,不把整个云账号都标红
318
+ const errorGroups = tmode === 'fail' && last ? groupsOfNode(last).slice(0, 1) : [];
319
+ return {
320
+ mode: tmode,
321
+ nodes,
322
+ edges,
323
+ ...(all.some((g) => !errorGroups.includes(g)) ? { groups: all.filter((g) => !errorGroups.includes(g)) } : {}),
324
+ ...(errorGroups.length ? { errorGroups } : {}),
325
+ // 时序图的镜头对准消息所在的行(参与者头部在最上面,对准它们会把镜头拉离正在讲的那一行)
326
+ ...(d.type === 'Sequence' ? { targets: edges.map((e) => e.id) } : {}),
327
+ };
328
+ };
293
329
  // trace.skip 标记“这次没被调用”的一组元素,不是路径:节点和连线各自 dim,不要求彼此相连
294
330
  if (tmode === 'skip') {
295
331
  for (const t of ids) {
@@ -298,15 +334,16 @@ export function compile(src, mode) {
298
334
  else
299
335
  edges.push({ id: t, reverse: false });
300
336
  }
301
- return { mode: tmode, nodes, edges };
337
+ return finishTrace();
302
338
  }
339
+ const kind = d.type === 'Sequence' ? 'Sequence.Message' : d.type === 'StateMachine' ? 'StateMachine.Transition' : 'Diagram.Edge';
303
340
  let prev = null;
304
341
  for (const t of ids) {
305
342
  const edge = d.edges.find((e) => e.id === t);
306
343
  if (edge) {
307
- // 写连线 id:方向由上一个节点决定(从 to 端接上时逆向走)
344
+ // 写连线 id:方向由上一个节点决定(从 to 端接上时逆向走);时序图的消息各自独立,连续写几条消息 id 不要求首尾相接
308
345
  const reverse = prev !== null && prev === edge.to && prev !== edge.from;
309
- if (prev !== null && prev !== edge.from && prev !== edge.to) {
346
+ if (d.type !== 'Sequence' && prev !== null && prev !== edge.from && prev !== edge.to) {
310
347
  err('TRACE_UNKNOWN', `${shown}: edge "${t}"(${edge.from} → ${edge.to}) is not connected to the previous node "${prev}"`, at);
311
348
  return null;
312
349
  }
@@ -322,11 +359,11 @@ export function compile(src, mode) {
322
359
  const back = d.edges.filter((e) => e.from === t && e.to === prev);
323
360
  const pick = fwd.length ? fwd : back;
324
361
  if (pick.length > 1) {
325
- err('TRACE_AMBIGUOUS', `${shown}: "${prev}" and "${t}" have ${pick.length} edges (${pick.map((e) => e.id).join(', ')}), use an edge id instead, for example trace('${pick[0].id}')`, at);
362
+ err('TRACE_AMBIGUOUS', `${shown}: "${prev}" and "${t}" have ${pick.length} ${d.type === 'Sequence' ? 'messages' : 'edges'} (${pick.map((e) => e.id).join(', ')}), use an id instead, for example trace('${pick[0].id}')`, at);
326
363
  return null;
327
364
  }
328
365
  if (!pick.length) {
329
- err('TRACE_UNKNOWN', `${shown}: "${prev}" and "${t}" have no connecting edge (each segment needs a Diagram.Edge in the same Diagram; either direction is allowed)`, at);
366
+ err('TRACE_UNKNOWN', `${shown}: "${prev}" and "${t}" have no connecting ${kind} (each segment needs one in the same diagram; either direction is allowed)`, at);
330
367
  return null;
331
368
  }
332
369
  edges.push({ id: pick[0].id, reverse: !fwd.length });
@@ -334,7 +371,7 @@ export function compile(src, mode) {
334
371
  addNode(t);
335
372
  prev = t;
336
373
  }
337
- return { mode: tmode, nodes, edges };
374
+ return finishTrace();
338
375
  };
339
376
  const scenarioIds = {};
340
377
  for (const [skey, fl] of Object.entries(def.scenarios ?? {})) {
@@ -350,6 +387,9 @@ export function compile(src, mode) {
350
387
  else
351
388
  (scenarioIds[c] ??= []).push(sid);
352
389
  }
390
+ // 镜头状态(与 player.cameraAt 同一规则,逐步累积):判断焦点提示的目标在不在当前镜头里(D70)
391
+ const frame = new Map();
392
+ let director = hasLayers ? Object.keys(layers)[0] : PAGE_LAYER;
353
393
  const steps = fl.steps.map((st, i) => {
354
394
  const effects = [];
355
395
  const ruleIds = [];
@@ -378,8 +418,8 @@ export function compile(src, mode) {
378
418
  effects.push({ type: 'stream', path: e.path, value: e.value });
379
419
  else if (e.type === 'toast')
380
420
  effects.push({ type: 'toast', text: e.text, tone: e.tone });
381
- else if (e.type === 'shot' || e.type === 'mark' || e.type === 'fork')
382
- continue; // 镜头不是状态变化,下面单独归类
421
+ else if (e.type === 'shot' || e.type === 'mark' || e.type === 'fork' || e.type === 'cue' || e.type === 'callout' || e.type === 'hold')
422
+ continue; // 镜头与焦点提示不是状态变化,下面单独归类
383
423
  else if (e.type === 'explain') {
384
424
  if (e.text.trim())
385
425
  explains.push(e.text.trim());
@@ -390,7 +430,7 @@ export function compile(src, mode) {
390
430
  traces.push(t);
391
431
  // trace 相当于一个 shot(trace.skip 只标记没被调用,不移动镜头)
392
432
  if (t.mode !== 'skip')
393
- traceTargets.set(e, t.nodes);
433
+ traceTargets.set(e, t.targets ?? t.nodes);
394
434
  }
395
435
  }
396
436
  else
@@ -414,6 +454,56 @@ export function compile(src, mode) {
414
454
  marks.push({ target: e.target, kind: e.kindOf, ...(e.note ? { note: e.note } : {}) });
415
455
  }
416
456
  }
457
+ // 焦点提示(D70):spotlight / highlight / numbered / callout / hold。目标与 mark 同样解析:有层级时在任一层,否则在这一步的路径页面
458
+ const focusLayers = (id) => (hasLayers ? layersWith(id) : sceneAfter && findIn(sceneAfter.root, id) ? [PAGE_LAYER] : []);
459
+ const where = hasLayers ? 'any layer' : 'the stage for this step';
460
+ const cueMap = new Map();
461
+ const callouts = [];
462
+ /** 焦点提示的目标(按效果顺序):决定导演层,并判断要不要退回整层镜头。 */
463
+ const focusTargets = [];
464
+ let holdMs;
465
+ const CUE_FN = { spotlight: 'spotlight', highlight: 'highlight', number: 'numbered' };
466
+ for (const e of st.effects) {
467
+ if (e.type === 'cue') {
468
+ const fn = CUE_FN[e.cue] ?? e.cue;
469
+ if (!e.targets.length)
470
+ err('FOCUS_UNKNOWN', `${fn}() requires at least one element id, for example ${fn}('quota_alert')`, st.source);
471
+ for (const id of e.targets) {
472
+ if (!focusLayers(id).length) {
473
+ err('FOCUS_UNKNOWN', `${fn}("${id}") target is not in ${where}`, st.source);
474
+ continue;
475
+ }
476
+ const list = cueMap.get(e.cue) ?? [];
477
+ if (!list.includes(id))
478
+ list.push(id);
479
+ cueMap.set(e.cue, list);
480
+ if (!focusTargets.includes(id))
481
+ focusTargets.push(id);
482
+ }
483
+ }
484
+ else if (e.type === 'callout') {
485
+ const text = typeof e.text === 'string' ? e.text.trim() : '';
486
+ if (!focusLayers(e.target).length)
487
+ err('FOCUS_UNKNOWN', `callout("${e.target}", …) target is not in ${where}`, st.source);
488
+ else if (!text)
489
+ err('CALLOUT_EMPTY', `callout("${e.target}", …) needs one short sentence, for example callout('${e.target}', 'Share after generation')`, st.source);
490
+ else if (e.side !== undefined && !CALLOUT_SIDES.includes(e.side))
491
+ err('CALLOUT_SIDE_INVALID', `callout("${e.target}", …, { side: ${JSON.stringify(e.side)} }) must be one of ${CALLOUT_SIDES.join(', ')}, or omitted to pick automatically`, st.source);
492
+ else {
493
+ callouts.push({ target: e.target, text, ...(e.side ? { side: e.side } : {}) });
494
+ if (!focusTargets.includes(e.target))
495
+ focusTargets.push(e.target);
496
+ }
497
+ }
498
+ else if (e.type === 'hold') {
499
+ const sec = e.seconds;
500
+ if (typeof sec !== 'number' || !Number.isFinite(sec) || sec < HOLD_MIN_SECONDS || sec > HOLD_MAX_SECONDS)
501
+ err('HOLD_INVALID', `hold(${String(sec)}) must be between ${HOLD_MIN_SECONDS} and ${HOLD_MAX_SECONDS} seconds`, st.source);
502
+ else
503
+ holdMs = Math.max(holdMs ?? 0, Math.round(sec * 1000));
504
+ }
505
+ }
506
+ const cues = [...cueMap].map(([kind, targets]) => ({ kind, targets }));
417
507
  // 镜头:每个 id 在包含它的层级里解析;第一个 shot 的第一个元素所在层级就是这一步的导演层。
418
508
  // 没有声明 layers 的方案:在路径页面里聚焦(伪层级 @page)。
419
509
  const perLayer = new Map();
@@ -446,6 +536,9 @@ export function compile(src, mode) {
446
536
  }
447
537
  }
448
538
  }
539
+ // 没写 shot、写了焦点提示(D70):导演切到第一个提示目标所在的层(提示要被看见)
540
+ if (hasLayers && !directorLayer && focusTargets.length)
541
+ directorLayer = layersWith(focusTargets[0])[0] ?? null;
449
542
  // 没写 shot 的操作步骤:导演切到操作目标所在的层(播放时观众看得到要点的东西)
450
543
  if (hasLayers && !directorLayer && actionTarget)
451
544
  directorLayer = layersWith(actionTarget)[0] ?? null;
@@ -457,7 +550,25 @@ export function compile(src, mode) {
457
550
  else if (hasLayers && !directorLayer)
458
551
  directorLayer = Object.entries(layers).find(([, l]) => l.role === r)?.[0] ?? null;
459
552
  }
553
+ // 焦点提示不推近镜头(D70):目标不在这一层当前镜头里(inShotFrame:镜头目标本身、它的子元素,或 D69 取景一定带上的
554
+ // 父分组 / 时序图两端参与者)时,这一步补一个整层镜头,
555
+ // 免得提示落在画面外;这一步自己写了这一层的 shot 时以 shot 为准(目标在 shot 外由 check 的 FOCUS_CONFLICT 提示)
556
+ const dirAfter = directorLayer ?? director;
557
+ for (const id of focusTargets) {
558
+ const ls = focusLayers(id);
559
+ const lk = ls.includes(dirAfter) ? dirAfter : ls[0];
560
+ if (!lk || perLayer.has(lk) || (perLayer.has(DIRECTOR_LAYER) && lk === dirAfter))
561
+ continue;
562
+ const now = frame.get(lk) ?? [];
563
+ const scene = hasLayers ? layerScenes.find((l) => l.key === lk)?.scene : sceneAfter;
564
+ if (now.length && !(scene && inShotFrame(scene.root, id, now)))
565
+ perLayer.set(lk, []);
566
+ }
460
567
  const shots = [...perLayer].map(([layer, targets]) => ({ layer, targets }));
568
+ if (directorLayer)
569
+ director = directorLayer;
570
+ for (const s of shots)
571
+ frame.set(s.layer === DIRECTOR_LAYER ? director : s.layer, [...s.targets]);
461
572
  const generated = st.caption === undefined ? autoCaption(st, (hasLayers && actionTarget ? layerSceneWith(actionTarget) : undefined) ?? sceneBefore) : null;
462
573
  return {
463
574
  id: `${sid}#${i + 1}`,
@@ -473,6 +584,9 @@ export function compile(src, mode) {
473
584
  traces,
474
585
  forks,
475
586
  marks,
587
+ ...(cues.length ? { cues } : {}),
588
+ ...(callouts.length ? { callouts } : {}),
589
+ ...(holdMs !== undefined ? { hold: holdMs } : {}),
476
590
  ...(st.source ? { source: rel(st.source) } : {}),
477
591
  };
478
592
  });
@@ -548,7 +662,18 @@ export function compile(src, mode) {
548
662
  err('UNKNOWN_CASE', `Rule "${r.text}" links unknown case ${c}`, r.source);
549
663
  }
550
664
  }
551
- // ---------- 7. 发布视图与评审版:去掉设计备注与源位置 ----------
665
+ // ---------- 7. 图表布局(D69):每张图在编译期布局一次,写进 IR;同一结构只算一次(引擎自带缓存) ----------
666
+ if (!diags.some((d) => d.severity === 'error')) {
667
+ const failed = new Set();
668
+ for (const sc of Object.values(out.scenes))
669
+ attachLayouts(sc.root, opts.layout, (n, m) => {
670
+ if (failed.has(`${n.source}|${n.id}`))
671
+ return;
672
+ failed.add(`${n.source}|${n.id}`);
673
+ warn('DIAGRAM_LAYOUT_FAILED', `<${n.type}> "${n.id}" could not be laid out (${m}); showing a simple grid instead. Check the edges and groups of this diagram`, n.source, { kind: 'element', id: n.id });
674
+ }, sc.viewport);
675
+ }
676
+ // ---------- 8. 发布视图与评审版:去掉设计备注与源位置 ----------
552
677
  if (strip) {
553
678
  for (const s of Object.values(out.scenes))
554
679
  stripNotes(s.root);
@@ -633,20 +758,31 @@ function tagFrom(n, from) {
633
758
  }
634
759
  /** JNode → IR 节点:展开 Fragment、文本变 #text、分离 Joplo 属性、生成非交互元素的 ID、检查 ID 唯一。 */
635
760
  function toSceneNode(n, fallbackId, ids, err, rel) {
761
+ if (n.type === 'Menu')
762
+ n = menuWithOpened(n);
636
763
  const children = flatten(n.children).map((c, i) => isNode(c) ? toSceneNode(c, `${fallbackId}_${i}`, ids, err, rel) : textNode(c, `${fallbackId}_${i}`));
637
- const { id: rawId, when, disabled, disabledReason, unmodeled, note, __from, ...rest } = n.props;
764
+ const { id: rawId, when, disabled, disabledReason, unmodeled, note, redact, __from, ...rest } = n.props;
638
765
  const at = n.source;
639
766
  if (!KNOWN.has(n.type))
640
767
  err('UNKNOWN_COMPONENT', `Component <${n.type}> is not in the catalog (use Mantine component names; run joplo skill components to list them; use <Custom kind="…"> as a placeholder for missing components)`, at);
641
768
  const interactive = INTERACTIVE_TYPES.has(n.type);
642
769
  if (interactive && typeof rawId !== 'string')
643
770
  err('MISSING_ID', `Interactive component <${n.type}> "${labelOf(n)}" requires an id for steps and selection`, at);
644
- if (n.type === 'Diagram.Node' && typeof rawId !== 'string')
645
- err('MISSING_ID', `Diagram node <Diagram.Node> "${labelOf(n)}" requires an id for edge from / to`, at);
646
- if (n.type === 'Diagram')
647
- checkDiagram(n, err);
648
- // 连线没写 id 时用「from->to」:⌥+单击检查与 rules 的 elements 都能引用它
649
- const edgeId = n.type === 'Diagram.Edge' && typeof rest.from === 'string' && typeof rest.to === 'string' ? `${rest.from}->${rest.to}` : null;
771
+ const needsId = n.type === 'Diagram.Node' ? 'Diagram node <Diagram.Node>' : n.type === 'StateMachine.State' ? 'State <StateMachine.State>' : n.type === 'Sequence.Actor' ? 'Participant <Sequence.Actor>' : null;
772
+ if (needsId && typeof rawId !== 'string')
773
+ err('MISSING_ID', `${needsId} "${labelOf(n)}" requires an id for edge from / to and trace`, at);
774
+ if (isDiagramRoot(n.type))
775
+ checkDiagramRoot(n, err);
776
+ // 连线没写 id 时用「from->to」:⌥+单击检查与 rules 的 elements 都能引用它。
777
+ // 状态机的转换与时序图的消息常有同一对端点的多条(请求、重试、回复),重复的依次加「~2」「~3」。
778
+ const linkLike = n.type === 'Diagram.Edge' || n.type === 'StateMachine.Transition' || n.type === 'Sequence.Message';
779
+ let edgeId = linkLike && typeof rest.from === 'string' && typeof rest.to === 'string' ? `${rest.from}->${rest.to}` : null;
780
+ if (edgeId && n.type !== 'Diagram.Edge' && ids.has(edgeId)) {
781
+ let k = 2;
782
+ while (ids.has(`${edgeId}~${k}`))
783
+ k++;
784
+ edgeId = `${edgeId}~${k}`;
785
+ }
650
786
  const id = typeof rawId === 'string' ? rawId : (edgeId ?? `_${fallbackId}`);
651
787
  if (ids.has(id))
652
788
  err('DUPLICATE_ID', `Duplicate id "${id}" in the same stage (other location: ${rel(ids.get(id)) ?? 'unknown'})`, at);
@@ -683,6 +819,13 @@ function toSceneNode(n, fallbackId, ids, err, rel) {
683
819
  err('INVALID_DISABLED_REASON', `<${n.type}> "${labelOf(n)}" disabledReason must be a string or a state binding, got ${typeof disabledReason === 'object' ? 'an object' : typeof disabledReason}. Write disabledReason="Only admins can invite" or disabledReason={$.ui.sendHint}; for text that changes during the demo, set() it into state and bind it`, at);
684
820
  if (unmodeled === true)
685
821
  node.unmodeled = true;
822
+ // 敏感信息(D70):布尔或条件(和 disabled 一样),渲染时模糊;其他值报错并给出写法
823
+ if (typeof redact === 'boolean')
824
+ node.redact = redact;
825
+ else if (isBind(redact) || (redact && typeof redact === 'object' && '$cond' in redact))
826
+ node.redact = toCondition(redact);
827
+ else if (redact !== undefined && redact !== null)
828
+ err('INVALID_REDACT', `<${n.type}> "${labelOf(n)}" redact must be true / false or a condition, for example redact or redact={not($.ui.revealed)}; got ${typeof redact}`, at);
686
829
  if (typeof note === 'string')
687
830
  node.note = note;
688
831
  if (typeof __from === 'string')
@@ -693,31 +836,188 @@ function toSceneNode(n, fallbackId, ids, err, rel) {
693
836
  return node;
694
837
  }
695
838
  /**
696
- * 架构图校验:Diagram.Edge 的 from / to 必须是同一个 Diagram 里(含嵌套分组)存在的 Diagram.Node id。
697
- * 嵌套的另一个 Diagram 自成一体,不参与本图的校验。
839
+ * Menu(D68):opened 写在 Menu 上(与 Mantine 一致),可见性由 Menu.Dropdown 门控(GATED_CONTAINERS)。
840
+ * 把 Menu 的 opened 抄到它自己的 Menu.Dropdown 上(不进嵌套的另一个 Menu;Dropdown 自己写了 opened 时不覆盖)。
841
+ * Menu 没写 opened 时下拉保持关闭。
842
+ */
843
+ function menuWithOpened(menu) {
844
+ const opened = menu.props.opened;
845
+ if (opened === undefined)
846
+ return menu;
847
+ const visit = (c) => {
848
+ if (Array.isArray(c))
849
+ return c.map(visit);
850
+ if (!isNode(c) || c.type === 'Menu')
851
+ return c;
852
+ if (c.type === 'Menu.Dropdown')
853
+ return c.props.opened === undefined ? { ...c, props: { ...c.props, opened } } : c;
854
+ return { ...c, children: c.children.map(visit) };
855
+ };
856
+ return { ...menu, children: menu.children.map(visit) };
857
+ }
858
+ /**
859
+ * 关系类图表的校验(D69):在作者元素上报错,带源位置。
860
+ * - Diagram / StateMachine:连线两端必须是同一张图里的节点或(有 id 的)分组;group="…" 必须引用存在的分组、与嵌套不矛盾、不成环;
861
+ * 连线不能连到包含它端点的分组;icon / tone / pin 取预设值。节点多却没有分组时给一条 info(D69:按业务域分组)。
862
+ * - Sequence:消息两端必须是参与者;Sequence.Group 里只放参与者,Sequence.Block 里只放消息或片段。
863
+ * 嵌套的另一张图表自成一体,不参与本图的校验。
698
864
  */
699
- function checkDiagram(d, err) {
865
+ function checkDiagramRoot(d, err) {
866
+ const type = d.type;
867
+ const strOf = (v) => (typeof v === 'string' ? v : String(v));
868
+ const oneOf = (el, prop, allowed, severity = 'error') => {
869
+ const v = el.props[prop];
870
+ if (v !== undefined && (typeof v !== 'string' || !allowed.includes(v)))
871
+ err(prop === 'icon' ? 'ICON_UNKNOWN' : 'INVALID_DIAGRAM_PROP', `<${el.type}> ${prop}="${strOf(v)}" is not supported (available: ${allowed.join(', ')})${severity === 'warning' ? '; it is drawn as the default' : ''}`, el.source, severity);
872
+ };
873
+ if (type === 'Sequence') {
874
+ const actors = new Set();
875
+ const messages = [];
876
+ const walk = (cs, inside) => {
877
+ for (const c of flatten(cs)) {
878
+ if (!isNode(c) || isDiagramRoot(c.type))
879
+ continue;
880
+ if (c.type === SEQUENCE_FAMILY.actor) {
881
+ if (inside === 'block')
882
+ err('INVALID_DIAGRAM_CHILD', `<Sequence.Actor> "${labelOf(c)}" cannot be inside <Sequence.Block>; declare participants at the top (optionally in <Sequence.Group>) and put messages in blocks`, c.source);
883
+ if (typeof c.props.id === 'string')
884
+ actors.add(c.props.id);
885
+ }
886
+ else if (c.type === SEQUENCE_FAMILY.message) {
887
+ if (inside === 'group')
888
+ err('INVALID_DIAGRAM_CHILD', '<Sequence.Message> cannot be inside <Sequence.Group> (a group boxes participants); put it after the participants, or in a <Sequence.Block>', c.source);
889
+ messages.push(c);
890
+ }
891
+ else if (c.type === SEQUENCE_FAMILY.group) {
892
+ if (inside !== 'root')
893
+ err('INVALID_DIAGRAM_CHILD', '<Sequence.Group> must be a direct child of <Sequence>', c.source);
894
+ oneOf(c, 'icon', DIAGRAM_GROUP_ICONS);
895
+ walk(c.children, 'group');
896
+ }
897
+ else if (c.type === SEQUENCE_FAMILY.block) {
898
+ if (inside === 'group')
899
+ err('INVALID_DIAGRAM_CHILD', '<Sequence.Block> cannot be inside <Sequence.Group>', c.source);
900
+ oneOf(c, 'kind', SEQUENCE_BLOCK_KINDS);
901
+ walk(c.children, 'block');
902
+ }
903
+ else if (c.type.startsWith('Diagram.') || c.type.startsWith('StateMachine.')) {
904
+ err('INVALID_DIAGRAM_CHILD', `<${c.type}> cannot be used inside <Sequence>; use Sequence.Actor / Sequence.Message / Sequence.Group / Sequence.Block`, c.source);
905
+ }
906
+ }
907
+ };
908
+ walk(d.children, 'root');
909
+ const known = [...actors].join(', ') || '(no participants)';
910
+ for (const m of messages)
911
+ for (const k of ['from', 'to']) {
912
+ const v = m.props[k];
913
+ if (typeof v !== 'string' || !actors.has(v))
914
+ err('UNKNOWN_DIAGRAM_NODE', `<Sequence.Message> ${k} "${strOf(v)}" is not a participant id in this Sequence (available: ${known})`, m.source);
915
+ }
916
+ return;
917
+ }
918
+ const fam = GRAPH_FAMILY[type];
700
919
  const nodes = new Set();
920
+ const groups = new Map();
921
+ /** 元素 → 它的父分组(嵌套或 group= 引用);记录嵌套父分组,用来查冲突。 */
922
+ const parentOf = new Map();
701
923
  const edges = [];
702
- const walk = (cs) => {
924
+ const refs = [];
925
+ let nodeCount = 0;
926
+ const walk = (cs, nested) => {
703
927
  for (const c of flatten(cs)) {
704
- if (!isNode(c) || c.type === 'Diagram')
928
+ if (!isNode(c) || isDiagramRoot(c.type))
705
929
  continue;
706
- if (c.type === 'Diagram.Node' && typeof c.props.id === 'string')
707
- nodes.add(c.props.id);
708
- if (c.type === 'Diagram.Edge')
930
+ const id = typeof c.props.id === 'string' ? c.props.id : null;
931
+ const ref = typeof c.props.group === 'string' ? c.props.group : null;
932
+ if (c.props.group !== undefined && ref === null)
933
+ err('UNKNOWN_DIAGRAM_GROUP', `<${c.type}> group must be a group id string`, c.source);
934
+ if (c.type === fam.node) {
935
+ nodeCount++;
936
+ if (id) {
937
+ nodes.add(id);
938
+ parentOf.set(id, ref ?? nested);
939
+ }
940
+ if (ref)
941
+ refs.push({ el: c, ref, nested });
942
+ oneOf(c, 'pin', DIAGRAM_PINS);
943
+ // kind 以前没有校验(未知值画成 service):保持兼容,只给 warning
944
+ if (type === 'Diagram')
945
+ oneOf(c, 'kind', DIAGRAM_NODE_KINDS, 'warning');
946
+ }
947
+ else if (c.type === fam.group) {
948
+ if (id) {
949
+ groups.set(id, c);
950
+ parentOf.set(id, ref ?? nested);
951
+ }
952
+ if (ref)
953
+ refs.push({ el: c, ref, nested });
954
+ oneOf(c, 'icon', DIAGRAM_GROUP_ICONS);
955
+ oneOf(c, 'tone', DIAGRAM_TONES);
956
+ oneOf(c, 'pin', DIAGRAM_PINS);
957
+ walk(c.children, id ?? nested);
958
+ }
959
+ else if (c.type === fam.edge) {
709
960
  edges.push(c);
710
- walk(c.children);
961
+ }
962
+ else if (c.type.startsWith('Diagram.') || c.type.startsWith('StateMachine.') || c.type.startsWith('Sequence.')) {
963
+ err('INVALID_DIAGRAM_CHILD', `<${c.type}> cannot be used inside <${type}>; use ${fam.node} / ${fam.edge} / ${fam.group}`, c.source);
964
+ }
711
965
  }
712
966
  };
713
- walk(d.children);
714
- const known = [...nodes].join(', ') || '(no nodes)';
967
+ walk(d.children, null);
968
+ const groupList = [...groups.keys()].join(', ') || '(no groups with an id)';
969
+ for (const { el, ref, nested } of refs) {
970
+ if (!groups.has(ref))
971
+ err('UNKNOWN_DIAGRAM_GROUP', `<${el.type}> group="${ref}" is not a ${fam.group} id in this ${type} (available: ${groupList})`, el.source);
972
+ else if (nested && nested !== ref)
973
+ err('DIAGRAM_GROUP_CONFLICT', `<${el.type}> is nested in group "${nested}" but declares group="${ref}"; use one of the two`, el.source);
974
+ }
975
+ // 分组成环(只可能来自 group= 引用)
976
+ const reported = new Set();
977
+ for (const gid of groups.keys()) {
978
+ const seen = [gid];
979
+ for (let q = parentOf.get(gid) ?? null; q && groups.has(q); q = parentOf.get(q) ?? null) {
980
+ if (seen.includes(q)) {
981
+ const cycle = seen.slice(seen.indexOf(q));
982
+ const key = [...cycle].sort().join(',');
983
+ if (!reported.has(key)) {
984
+ reported.add(key);
985
+ err('DIAGRAM_GROUP_CYCLE', `Groups ${[...cycle, q].map((x) => `"${x}"`).join(' → ')} contain each other; remove one group= reference`, groups.get(gid).source);
986
+ }
987
+ break;
988
+ }
989
+ seen.push(q);
990
+ }
991
+ }
992
+ const ancestors = (id) => {
993
+ const out = [];
994
+ for (let q = parentOf.get(id) ?? null; q && !out.includes(q); q = parentOf.get(q) ?? null)
995
+ out.push(q);
996
+ return out;
997
+ };
998
+ const known = [...nodes, ...groups.keys()].join(', ') || '(no nodes)';
715
999
  for (const e of edges) {
1000
+ let ok = true;
716
1001
  for (const k of ['from', 'to']) {
717
1002
  const v = e.props[k];
718
- if (typeof v !== 'string' || !nodes.has(v))
719
- err('UNKNOWN_DIAGRAM_NODE', `<Diagram.Edge> ${k} "${typeof v === 'string' ? v : String(v)}" is not a node id in this Diagram (available: ${known})`, e.source);
1003
+ if (typeof v !== 'string' || (!nodes.has(v) && !groups.has(v))) {
1004
+ ok = false;
1005
+ err('UNKNOWN_DIAGRAM_NODE', `<${fam.edge}> ${k} "${strOf(v)}" is not a ${type === 'StateMachine' ? 'state' : 'node'} or group id in this ${type} (available: ${known})`, e.source);
1006
+ }
720
1007
  }
1008
+ if (!ok)
1009
+ continue;
1010
+ const from = e.props.from;
1011
+ const to = e.props.to;
1012
+ if (ancestors(from).includes(to) || ancestors(to).includes(from))
1013
+ err('DIAGRAM_EDGE_INTO_OWN_GROUP', `<${fam.edge}> ${from} → ${to} connects an element to a group that contains it; connect to another element inside the group, or to a group outside`, e.source);
1014
+ }
1015
+ // 按业务域分组的提示:节点多,却没有分组(或只有一个把所有节点都包起来的分组)
1016
+ if (type === 'Diagram' && nodeCount >= 6) {
1017
+ const top = [...groups.values()].filter((g) => !parentOf.get(String(g.props.id)));
1018
+ const allInOne = groups.size === 1 && top.length === 1 && [...nodes].every((n) => parentOf.get(n) === String(top[0].props.id));
1019
+ if (groups.size === 0 || allInOne)
1020
+ err('DIAGRAM_UNGROUPED', `<Diagram> has ${nodeCount} nodes but ${groups.size === 0 ? 'no groups' : 'a single group around all of them'}; group nodes by business domain (gateway, runtime, storage…) with <Diagram.Group label icon> so viewers can tell what belongs where. See npx joplo skill diagram`, d.source, 'info');
721
1021
  }
722
1022
  }
723
1023
  /** 展开数组与 Fragment(含插槽展开后的 Fragment),丢弃 null/布尔。 */
@@ -776,6 +1076,7 @@ function stepRouteBefore(steps, i, start) {
776
1076
  }
777
1077
  return route;
778
1078
  }
1079
+ /** id 是 frameId 本身或它的子孙(在同一棵树里)。 */
779
1080
  function findIn(node, id) {
780
1081
  if (node.id === id)
781
1082
  return node;
@@ -826,28 +1127,3 @@ function stripNotes(n) {
826
1127
  for (const c of n.children ?? [])
827
1128
  stripNotes(c);
828
1129
  }
829
- function diagramsIn(root) {
830
- const out = [];
831
- const visit = (n) => {
832
- if (n.type === 'Diagram') {
833
- const d = { id: n.id, nodes: new Set(), edges: [] };
834
- const walk = (c) => {
835
- if (c.type === 'Diagram')
836
- return; // 嵌套的 Diagram 自成一图
837
- if (c.type === 'Diagram.Node')
838
- d.nodes.add(c.id);
839
- if (c.type === 'Diagram.Edge')
840
- d.edges.push({ id: c.id, from: String(c.props?.from ?? ''), to: String(c.props?.to ?? '') });
841
- for (const k of c.children ?? [])
842
- walk(k);
843
- };
844
- for (const k of n.children ?? [])
845
- walk(k);
846
- out.push(d);
847
- }
848
- for (const c of n.children ?? [])
849
- visit(c);
850
- };
851
- visit(root);
852
- return out;
853
- }
@@ -0,0 +1,6 @@
1
+ import { type ElkRun, type LayoutGoal } from './graph-layout.js';
2
+ import { type GraphLayout, type GraphStructure } from './model.js';
3
+ /** 同步运行一次 ELK 布局;ELK 报错时抛出 Error。 */
4
+ export declare const runElk: ElkRun;
5
+ /** 编译期的图表布局引擎:传给 compile(src, mode, { layout: elkLayout })。goal = 目标外框比例(舞台比例)。 */
6
+ export declare function elkLayout(s: GraphStructure, goal?: LayoutGoal): GraphLayout;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * 仅限 Node:同步运行 elkjs(Eclipse Layout Kernel 的 JS 版,EPL-2.0),给编译期的图表布局用(D69)。
3
+ *
4
+ * elkjs 的公开 API 是异步的(Web Worker 或 setTimeout 模拟的 FakeWorker),但它的 Dispatcher 本身是同步的:
5
+ * 直接调用 FakeWorker.dispatcher.saveDispatch,回调在同一个调用栈里返回结果。这样 compile() 保持同步,
6
+ * check、dev、build 的调用方式都不变。elkjs 固定版本(package.json 精确版本),这个内部接口由测试守住。
7
+ *
8
+ * elkjs 只在这里加载:浏览器端(看板、发布站)不打包它,发布站只读 IR 里写好的坐标。
9
+ */
10
+ import { createRequire } from 'node:module';
11
+ import { DEFAULT_ASPECT, layoutGraph } from "./graph-layout.js";
12
+ import { structureKey } from "./model.js";
13
+ let worker = null;
14
+ function elkWorker() {
15
+ if (worker)
16
+ return worker;
17
+ const require = createRequire(import.meta.url);
18
+ const mod = require('elkjs/lib/elk-worker.min.js');
19
+ const w = new mod.Worker();
20
+ w.onmessage = () => { };
21
+ w.dispatcher.saveDispatch({ data: { id: 0, cmd: 'register', algorithms: ['layered'] } });
22
+ worker = w;
23
+ return w;
24
+ }
25
+ /** 同步运行一次 ELK 布局;ELK 报错时抛出 Error。 */
26
+ export const runElk = (graph) => {
27
+ const w = elkWorker();
28
+ let out = null;
29
+ w.onmessage = (e) => {
30
+ out = e.data;
31
+ };
32
+ w.dispatcher.saveDispatch({ data: { id: 1, cmd: 'layout', graph, layoutOptions: {}, options: {} } });
33
+ const res = out;
34
+ if (!res)
35
+ throw new Error('ELK did not return a layout');
36
+ if (res.error) {
37
+ const e = res.error;
38
+ throw new Error(String(e.message ?? e.g ?? e).split('\n')[0].slice(0, 300));
39
+ }
40
+ return res.data;
41
+ };
42
+ /** 按结构缓存(dev 每次保存都重新编译,结构没变的图不再跑 ELK)。 */
43
+ const cache = new Map();
44
+ const CACHE_MAX = 300;
45
+ /** 编译期的图表布局引擎:传给 compile(src, mode, { layout: elkLayout })。goal = 目标外框比例(舞台比例)。 */
46
+ export function elkLayout(s, goal = { aspect: DEFAULT_ASPECT }) {
47
+ const key = `${goal.aspect.toFixed(3)}|${goal.width ?? ''}|${goal.height ?? ''}|${structureKey(s)}`;
48
+ const hit = cache.get(key);
49
+ if (hit)
50
+ return structuredClone(hit);
51
+ const l = layoutGraph(structuredClone(s), runElk, goal);
52
+ cache.set(key, l);
53
+ if (cache.size > CACHE_MAX)
54
+ cache.delete(cache.keys().next().value);
55
+ return structuredClone(l);
56
+ }