@principal-ai/subsystems-react 0.56.15 → 0.56.16

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.
Files changed (44) hide show
  1. package/dist/index.d.ts +4 -3
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +2 -1
  4. package/dist/index.js.map +1 -1
  5. package/dist/subsystem/C4Graph.d.ts +17 -0
  6. package/dist/subsystem/C4Graph.d.ts.map +1 -1
  7. package/dist/subsystem/C4Graph.js +128 -61
  8. package/dist/subsystem/C4Graph.js.map +1 -1
  9. package/dist/subsystem/C4NodeCard.d.ts.map +1 -1
  10. package/dist/subsystem/C4NodeCard.js +7 -2
  11. package/dist/subsystem/C4NodeCard.js.map +1 -1
  12. package/dist/subsystem/DecorationPanel.d.ts +32 -3
  13. package/dist/subsystem/DecorationPanel.d.ts.map +1 -1
  14. package/dist/subsystem/DecorationPanel.js +162 -89
  15. package/dist/subsystem/DecorationPanel.js.map +1 -1
  16. package/dist/subsystem/SubsystemComponentGraph.d.ts +2 -0
  17. package/dist/subsystem/SubsystemComponentGraph.d.ts.map +1 -1
  18. package/dist/subsystem/SubsystemComponentGraph.js +1 -1
  19. package/dist/subsystem/SubsystemComponentGraph.js.map +1 -1
  20. package/dist/subsystem/c4.d.ts +2 -0
  21. package/dist/subsystem/c4.d.ts.map +1 -1
  22. package/dist/subsystem/c4.js.map +1 -1
  23. package/dist/subsystem/decoration.d.ts +19 -0
  24. package/dist/subsystem/decoration.d.ts.map +1 -1
  25. package/dist/subsystem/decoration.js.map +1 -1
  26. package/dist/subsystem/decorationC4.d.ts +9 -0
  27. package/dist/subsystem/decorationC4.d.ts.map +1 -0
  28. package/dist/subsystem/decorationC4.js +55 -0
  29. package/dist/subsystem/decorationC4.js.map +1 -0
  30. package/package.json +1 -1
  31. package/src/index.ts +6 -1
  32. package/src/stories/Components/DecorationPanel.stories.tsx +344 -36
  33. package/src/subsystem/C4Graph.groups.test.ts +46 -0
  34. package/src/subsystem/C4Graph.tsx +96 -16
  35. package/src/subsystem/C4NodeCard.test.ts +35 -1
  36. package/src/subsystem/C4NodeCard.tsx +7 -2
  37. package/src/subsystem/DecorationPanel.test.tsx +228 -4
  38. package/src/subsystem/DecorationPanel.tsx +248 -82
  39. package/src/subsystem/SubsystemComponentGraph.sidebar.test.tsx +11 -0
  40. package/src/subsystem/SubsystemComponentGraph.tsx +4 -1
  41. package/src/subsystem/c4.ts +2 -0
  42. package/src/subsystem/decoration.ts +25 -0
  43. package/src/subsystem/decorationC4.test.ts +134 -0
  44. package/src/subsystem/decorationC4.ts +60 -0
@@ -11,14 +11,16 @@
11
11
  * Nothing here writes: the first prototype is read-only plus an on/off toggle.
12
12
  */
13
13
 
14
- import type { CSSProperties } from 'react';
14
+ import type { CSSProperties, ReactNode } from 'react';
15
15
  import { useTheme } from '@principal-ade/industry-theme';
16
16
  import { Box, Eye, EyeOff, Network, Route, Sparkles } from 'lucide-react';
17
17
  import { IndustryMarkdownSlide } from 'themed-markdown';
18
+ import type { C4Edge } from './c4';
18
19
  import {
19
20
  decorationTrailId,
20
21
  groupDecorationTrailsByModel,
21
22
  type DecorationDraftComponent,
23
+ type DecorationDraftC4Element,
22
24
  type DecorationTrailRef,
23
25
  type SubsystemDecoration,
24
26
  } from './decoration';
@@ -28,15 +30,28 @@ export interface DecorationPanelTrailMeta {
28
30
  stepCount?: number;
29
31
  }
30
32
 
33
+ export type DecorationPanelSelection =
34
+ | { kind: 'c4'; id: string }
35
+ | { kind: 'c4-edge'; id: string }
36
+ | { kind: 'component'; alias: string };
37
+
31
38
  export interface DecorationPanelProps {
32
39
  decoration: SubsystemDecoration;
33
40
  /** Whether the decoration overlay is currently on. */
34
41
  active: boolean;
35
42
  onToggleActive: (active: boolean) => void;
43
+ /** Hide when the host renders DecorationHeader above the sidebar and graph. */
44
+ hideHeader?: boolean;
36
45
  /** Click a trail row. The host focuses the owning model/trail. */
37
46
  onSelectTrail?: (ref: DecorationTrailRef) => void;
38
47
  /** Click a draft component. Omit to render the draft list read-only. */
39
48
  onSelectDraftComponent?: (component: DecorationDraftComponent) => void;
49
+ /** Click a draft C4 box. The host can open its container and focus it. */
50
+ onSelectDraftC4Element?: (element: DecorationDraftC4Element) => void;
51
+ /** Click a draft C4 relationship. The host reveals its endpoints and selects the line. */
52
+ onSelectDraftC4Edge?: (edge: C4Edge) => void;
53
+ /** Controlled row selection, shared with the host's graph focus. */
54
+ selectedDraftItem?: DecorationPanelSelection | null;
40
55
  /**
41
56
  * Resolve a base trail's display title/step count from its owning model.
42
57
  * Draft trails carry their content inline and need no resolver.
@@ -44,25 +59,110 @@ export interface DecorationPanelProps {
44
59
  resolveTrail?: (ref: DecorationTrailRef) => DecorationPanelTrailMeta | undefined;
45
60
  /** Friendly model names, keyed by `modelId`. Falls back to the id. */
46
61
  modelLabels?: ReadonlyMap<string, string>;
62
+ /** Friendly names for existing C4 endpoints. Draft elements resolve from the decoration. */
63
+ c4ElementLabels?: ReadonlyMap<string, string>;
64
+ }
65
+
66
+ export interface DecorationHeaderProps {
67
+ decoration: Pick<SubsystemDecoration, 'title'>;
68
+ active: boolean;
69
+ onToggleActive: (active: boolean) => void;
70
+ actions?: ReactNode;
71
+ }
72
+
73
+ /** Shared title and toggle, usable above the whole canvas or within the panel. */
74
+ export function DecorationHeader({
75
+ decoration,
76
+ active,
77
+ onToggleActive,
78
+ actions,
79
+ }: DecorationHeaderProps) {
80
+ const { theme } = useTheme();
81
+ const muted = theme.colors.textMuted ?? theme.colors.textSecondary;
82
+ const accent = theme.colors.accent ?? theme.colors.primary ?? theme.colors.text;
83
+ return (
84
+ <header
85
+ style={{
86
+ flexShrink: 0,
87
+ display: 'flex',
88
+ alignItems: 'center',
89
+ gap: 12,
90
+ padding: '12px 16px',
91
+ background: theme.colors.background,
92
+ color: theme.colors.text,
93
+ borderBottom: `1px solid ${theme.colors.border}`,
94
+ }}
95
+ >
96
+ <Sparkles size={15} strokeWidth={2} color={accent} aria-hidden />
97
+ <h2
98
+ style={{
99
+ flex: 1,
100
+ minWidth: 0,
101
+ margin: 0,
102
+ overflowWrap: 'anywhere',
103
+ fontFamily: theme.fonts.monospace,
104
+ fontSize: theme.fontSizes[2],
105
+ fontWeight: theme.fontWeights.semibold,
106
+ }}
107
+ >
108
+ {decoration.title}
109
+ </h2>
110
+ {actions}
111
+ <button
112
+ type="button"
113
+ aria-pressed={active}
114
+ aria-label={active ? 'Turn decoration off' : 'Turn decoration on'}
115
+ title={active ? 'Turn decoration off' : 'Turn decoration on'}
116
+ onClick={() => onToggleActive(!active)}
117
+ style={{
118
+ display: 'inline-flex',
119
+ alignItems: 'center',
120
+ gap: 4,
121
+ flexShrink: 0,
122
+ padding: '3px 8px',
123
+ borderRadius: 4,
124
+ border: `1px solid ${active ? accent : theme.colors.border}`,
125
+ background: active ? `${accent}18` : 'transparent',
126
+ color: active ? accent : muted,
127
+ fontFamily: theme.fonts.monospace,
128
+ fontSize: theme.fontSizes[0],
129
+ cursor: 'pointer',
130
+ }}
131
+ >
132
+ {active ? <Eye size={12} strokeWidth={2} /> : <EyeOff size={12} strokeWidth={2} />}
133
+ {active ? 'On' : 'Off'}
134
+ </button>
135
+ </header>
136
+ );
47
137
  }
48
138
 
49
139
  export function DecorationPanel({
50
140
  decoration,
51
141
  active,
52
142
  onToggleActive,
143
+ hideHeader = false,
53
144
  onSelectTrail,
54
145
  onSelectDraftComponent,
146
+ onSelectDraftC4Element,
147
+ onSelectDraftC4Edge,
148
+ selectedDraftItem,
55
149
  resolveTrail,
56
150
  modelLabels,
151
+ c4ElementLabels,
57
152
  }: DecorationPanelProps) {
58
153
  const { theme } = useTheme();
59
154
  const muted = theme.colors.textMuted ?? theme.colors.textSecondary;
60
155
  const secondary = theme.colors.textSecondary ?? muted;
61
156
  const warning = theme.colors.warning ?? secondary;
62
157
  const accent = theme.colors.accent ?? theme.colors.primary ?? theme.colors.text;
63
- const groups = groupDecorationTrailsByModel(decoration.trails);
158
+ const proposedTrails = decoration.trails.filter((ref) => ref.kind === 'draft');
159
+ const contextTrails = decoration.trails.filter((ref) => ref.kind === 'base');
64
160
  const draftComponents = decoration.draft?.components ?? [];
65
161
  const draftEdges = decoration.draft?.edges ?? [];
162
+ const draftC4Elements = decoration.draft?.c4?.elements ?? [];
163
+ const draftC4Edges = decoration.draft?.c4?.edges ?? [];
164
+ const c4Labels = new Map(c4ElementLabels);
165
+ for (const element of draftC4Elements) c4Labels.set(element.id, element.label);
66
166
  const sectionLabel: CSSProperties = {
67
167
  fontFamily: theme.fonts.monospace,
68
168
  fontSize: theme.fontSizes[0],
@@ -71,85 +171,23 @@ export function DecorationPanel({
71
171
  textTransform: 'uppercase',
72
172
  };
73
173
 
74
- return (
75
- <div
76
- style={{
77
- display: 'flex',
78
- flexDirection: 'column',
79
- width: '100%',
80
- height: '100%',
81
- minHeight: 0,
82
- background: theme.colors.background,
83
- color: theme.colors.text,
84
- }}
85
- >
86
- <header
87
- style={{
88
- flexShrink: 0,
89
- padding: '14px 16px 10px',
90
- borderBottom: `1px solid ${theme.colors.border}`,
91
- }}
92
- >
93
- <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
94
- <Sparkles size={15} strokeWidth={2} color={accent} aria-hidden />
95
- <h2
96
- style={{
97
- flex: 1,
98
- minWidth: 0,
99
- margin: 0,
100
- overflowWrap: 'anywhere',
101
- fontFamily: theme.fonts.monospace,
102
- fontSize: theme.fontSizes[2],
103
- fontWeight: theme.fontWeights.semibold,
104
- }}
105
- >
106
- {decoration.title}
107
- </h2>
108
- <button
109
- type="button"
110
- aria-pressed={active}
111
- aria-label={active ? 'Turn decoration off' : 'Turn decoration on'}
112
- title={active ? 'Turn decoration off' : 'Turn decoration on'}
113
- onClick={() => onToggleActive(!active)}
114
- style={{
115
- display: 'inline-flex',
116
- alignItems: 'center',
117
- gap: 4,
118
- flexShrink: 0,
119
- padding: '3px 8px',
120
- borderRadius: 4,
121
- border: `1px solid ${active ? accent : theme.colors.border}`,
122
- background: active ? `${accent}18` : 'transparent',
123
- color: active ? accent : muted,
124
- fontFamily: theme.fonts.monospace,
125
- fontSize: theme.fontSizes[0],
126
- cursor: 'pointer',
127
- }}
128
- >
129
- {active ? <Eye size={12} strokeWidth={2} /> : <EyeOff size={12} strokeWidth={2} />}
130
- {active ? 'On' : 'Off'}
131
- </button>
132
- </div>
133
- </header>
134
-
135
- <div style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '12px 16px 18px' }}>
136
- {decoration.description && (
137
- <div style={{ fontSize: theme.fontSizes[1], lineHeight: theme.lineHeights.body }}>
138
- <IndustryMarkdownSlide
139
- content={decoration.description}
140
- slideIdPrefix={`decoration-${decoration.id}`}
141
- slideIndex={0}
142
- isVisible={true}
143
- theme={theme}
144
- disableScroll={true}
145
- disableBasePadding
146
- enableKeyboardScrolling={false}
147
- autoFocusOnVisible={false}
148
- />
149
- </div>
150
- )}
174
+ function draftRowStyle(selected: boolean): CSSProperties {
175
+ return {
176
+ borderRadius: 4,
177
+ padding: '6px 8px',
178
+ background: selected ? theme.colors.backgroundSecondary : undefined,
179
+ color: selected ? accent : theme.colors.text,
180
+ fontWeight: selected ? theme.fontWeights.semibold : theme.fontWeights.body,
181
+ transition: 'background 120ms ease, color 120ms ease',
182
+ };
183
+ }
151
184
 
185
+ function renderTrails(title: string, trails: DecorationTrailRef[]) {
186
+ if (trails.length === 0) return null;
187
+ const groups = groupDecorationTrailsByModel(trails);
188
+ return (
152
189
  <section
190
+ aria-label={title}
153
191
  style={{
154
192
  marginTop: 16,
155
193
  paddingTop: 14,
@@ -157,7 +195,7 @@ export function DecorationPanel({
157
195
  }}
158
196
  >
159
197
  <div style={{ ...sectionLabel, color: secondary }}>
160
- Trails · {decoration.trails.length}
198
+ {title} · {trails.length}
161
199
  </div>
162
200
  {groups.map((group) => (
163
201
  <div key={group.modelId}>
@@ -260,16 +298,143 @@ export function DecorationPanel({
260
298
  </div>
261
299
  ))}
262
300
  </section>
301
+ );
302
+ }
263
303
 
264
- {(draftComponents.length > 0 || draftEdges.length > 0) && (
304
+ return (
305
+ <div
306
+ style={{
307
+ display: 'flex',
308
+ flexDirection: 'column',
309
+ width: '100%',
310
+ height: '100%',
311
+ minHeight: 0,
312
+ background: theme.colors.background,
313
+ color: theme.colors.text,
314
+ }}
315
+ >
316
+ {!hideHeader && (
317
+ <DecorationHeader decoration={decoration} active={active} onToggleActive={onToggleActive} />
318
+ )}
319
+ <style>{`
320
+ .subsystem-decoration-draft-row {
321
+ background: transparent;
322
+ }
323
+ .subsystem-decoration-draft-row:hover {
324
+ background: color-mix(in srgb, currentColor 8%, transparent);
325
+ }
326
+ `}</style>
327
+
328
+ <div style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '12px 16px 18px' }}>
329
+ {decoration.description && (
330
+ <div style={{ fontSize: theme.fontSizes[1], lineHeight: theme.lineHeights.body }}>
331
+ <IndustryMarkdownSlide
332
+ content={decoration.description}
333
+ slideIdPrefix={`decoration-${decoration.id}`}
334
+ slideIndex={0}
335
+ isVisible={true}
336
+ theme={theme}
337
+ disableScroll={true}
338
+ disableBasePadding
339
+ enableKeyboardScrolling={false}
340
+ autoFocusOnVisible={false}
341
+ />
342
+ </div>
343
+ )}
344
+
345
+ {renderTrails('Proposed flows', proposedTrails)}
346
+
347
+ {(draftComponents.length > 0 || draftEdges.length > 0 ||
348
+ draftC4Elements.length > 0 || draftC4Edges.length > 0) && (
265
349
  <section style={{ marginTop: 18 }}>
266
350
  <div style={{ ...sectionLabel, color: secondary }}>
267
351
  Draft structure · not verified
268
352
  </div>
353
+ {draftC4Elements.map((element) => (
354
+ <button
355
+ key={element.id}
356
+ className="subsystem-decoration-draft-row"
357
+ type="button"
358
+ aria-current={selectedDraftItem?.kind === 'c4' && selectedDraftItem.id === element.id ? 'true' : undefined}
359
+ onClick={() => onSelectDraftC4Element?.(element)}
360
+ style={{
361
+ display: 'flex',
362
+ alignItems: 'center',
363
+ gap: 8,
364
+ width: '100%',
365
+ padding: '6px 6px 6px 0',
366
+ border: 'none',
367
+ color: theme.colors.text,
368
+ textAlign: 'left',
369
+ fontFamily: theme.fonts.monospace,
370
+ fontSize: theme.fontSizes[1],
371
+ cursor: onSelectDraftC4Element ? 'pointer' : 'default',
372
+ ...draftRowStyle(selectedDraftItem?.kind === 'c4' && selectedDraftItem.id === element.id),
373
+ }}
374
+ >
375
+ <Network size={13} color={warning} aria-hidden />
376
+ <span style={{ flex: 1, minWidth: 0, overflowWrap: 'anywhere' }}>
377
+ {element.label}
378
+ </span>
379
+ <span style={{ color: secondary, fontSize: theme.fontSizes[0] }}>
380
+ C4 {element.kind}
381
+ </span>
382
+ </button>
383
+ ))}
384
+ {draftC4Edges.length > 0 && (
385
+ <div style={{ marginTop: 10 }}>
386
+ <div style={{ ...sectionLabel, color: secondary }}>
387
+ Draft C4 relationships · {draftC4Edges.length}
388
+ </div>
389
+ <ol
390
+ aria-label="Draft C4 relationships"
391
+ style={{
392
+ margin: '4px 0 8px',
393
+ paddingLeft: 22,
394
+ fontFamily: theme.fonts.monospace,
395
+ fontSize: theme.fontSizes[1],
396
+ color: theme.colors.text,
397
+ }}
398
+ >
399
+ {draftC4Edges.map((edge) => (
400
+ <li key={edge.id} style={{ padding: '2px 0', overflowWrap: 'anywhere' }}>
401
+ <button
402
+ type="button"
403
+ className="subsystem-decoration-draft-row"
404
+ aria-current={selectedDraftItem?.kind === 'c4-edge' && selectedDraftItem.id === edge.id ? 'true' : undefined}
405
+ onClick={() => onSelectDraftC4Edge?.(edge)}
406
+ style={{
407
+ display: 'flex',
408
+ flexDirection: 'column',
409
+ alignItems: 'stretch',
410
+ width: '100%',
411
+ border: 'none',
412
+ textAlign: 'left',
413
+ fontFamily: 'inherit',
414
+ fontSize: 'inherit',
415
+ overflowWrap: 'anywhere',
416
+ cursor: onSelectDraftC4Edge ? 'pointer' : 'default',
417
+ ...draftRowStyle(selectedDraftItem?.kind === 'c4-edge' && selectedDraftItem.id === edge.id),
418
+ }}
419
+ >
420
+ <span>{edge.label}</span>
421
+ <span style={{ marginTop: 3, fontSize: theme.fontSizes[0], color: secondary }}>
422
+ {c4Labels.get(edge.source) ?? edge.source}
423
+ {' → '}
424
+ {c4Labels.get(edge.target) ?? edge.target}
425
+ </span>
426
+ </button>
427
+ </li>
428
+ ))}
429
+ </ol>
430
+ </div>
431
+ )}
269
432
  {draftComponents.map((component) => (
270
433
  <button
271
434
  key={component.alias}
435
+ className="subsystem-decoration-draft-row"
272
436
  type="button"
437
+ aria-current={selectedDraftItem?.kind === 'component' && selectedDraftItem.alias === component.alias ? 'true' : undefined}
273
438
  onClick={() => onSelectDraftComponent?.(component)}
274
439
  style={{
275
440
  display: 'flex',
@@ -280,10 +445,10 @@ export function DecorationPanel({
280
445
  padding: '6px 6px 6px 0',
281
446
  border: 'none',
282
447
  borderRadius: 4,
283
- background: 'transparent',
284
448
  color: theme.colors.text,
285
449
  textAlign: 'left',
286
450
  cursor: onSelectDraftComponent ? 'pointer' : 'default',
451
+ ...draftRowStyle(selectedDraftItem?.kind === 'component' && selectedDraftItem.alias === component.alias),
287
452
  }}
288
453
  >
289
454
  <Box size={13} strokeWidth={2} color={muted} aria-hidden />
@@ -328,6 +493,7 @@ export function DecorationPanel({
328
493
  )}
329
494
  </section>
330
495
  )}
496
+ {renderTrails('Context trails', contextTrails)}
331
497
  </div>
332
498
  </div>
333
499
  );
@@ -38,6 +38,17 @@ function renderGraph(props: Partial<SubsystemComponentGraphProps> = {}) {
38
38
  }
39
39
 
40
40
  describe('subsystem graph sidebar', () => {
41
+ test('puts host actions on the right of the header, not above the description', () => {
42
+ const body = renderGraph({
43
+ headerActions: createElement('button', { type: 'button' }, 'C4 view'),
44
+ });
45
+ const header = body.querySelector('header');
46
+ expect(header?.lastElementChild?.textContent).toBe('C4 view');
47
+ expect(header?.querySelector('[aria-label="Sidebar view"]')).not.toBeNull();
48
+ expect(header?.nextElementSibling?.textContent).not.toContain('C4 view');
49
+ expect(header?.nextElementSibling?.textContent).toContain('Always visible description.');
50
+ });
51
+
41
52
  test('puts the name in a full-width header above the sidebar and graph', () => {
42
53
  const body = renderGraph();
43
54
  const header = body.querySelector('header');
@@ -327,6 +327,8 @@ export interface SubsystemComponentGraphProps {
327
327
  edgeView?: SubsystemEdgeView;
328
328
  /** Subsystem title displayed above the sidebar and graph. */
329
329
  title?: string;
330
+ /** Extra actions on the right side of the full-width graph header. */
331
+ headerActions?: ReactNode;
330
332
  /**
331
333
  * Suppresses the header and sidebar entirely (title, description,
332
334
  * trails) for graph-only embeds. Pair with `graphTitle` to keep the
@@ -3607,6 +3609,7 @@ export function SubsystemComponentGraph(props: SubsystemComponentGraphProps) {
3607
3609
  />
3608
3610
  )}
3609
3611
  </div>
3612
+ {props.headerActions}
3610
3613
  </header>
3611
3614
  )}
3612
3615
  <div ref={wrapRef} style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' }}>
@@ -3620,7 +3623,7 @@ export function SubsystemComponentGraph(props: SubsystemComponentGraphProps) {
3620
3623
  descriptionOpen={props.descriptionOpen}
3621
3624
  onDescriptionOpenChange={props.onDescriptionOpenChange}
3622
3625
  diagnostic={props.diagnostic}
3623
- sidebarExtra={props.sidebarExtra}
3626
+ sidebarExtra={props.headerActions ? <>{props.headerActions}{props.sidebarExtra}</> : props.sidebarExtra}
3624
3627
  sidebarAfterDescription={props.sidebarAfterDescription}
3625
3628
  renderFileViewer={props.renderFileViewer}
3626
3629
  onFileSelect={props.onFileSelect}
@@ -266,6 +266,8 @@ export interface C4Edge {
266
266
  label: string;
267
267
  /** The interaction's technology/protocol, e.g. `RPC`, `HTTP`, `stdin`. */
268
268
  protocol?: string;
269
+ /** Unverified decoration relationship, drawn with a segmented label border. */
270
+ draft?: boolean;
269
271
  /** Trail verbs that produced this line (`calls`, `writes`, …). */
270
272
  mechanisms: string[];
271
273
  /** How many underlying steps this line rolled up. */
@@ -21,6 +21,7 @@
21
21
  */
22
22
 
23
23
  import type { SubsystemTrail, SubsystemTrailMechanism } from './model';
24
+ import type { C4Component, C4Container, C4Edge, C4ExternalSystem, C4Person } from './c4';
24
25
 
25
26
  export interface DecorationStepAnchor {
26
27
  /** Claim fingerprint of the anchored step (see `stepClaimKey`). */
@@ -74,9 +75,33 @@ export interface DecorationDraftEdge {
74
75
  mechanism: SubsystemTrailMechanism;
75
76
  }
76
77
 
78
+ /**
79
+ * Authored C4 additions, not accepted architecture. The host projects these as
80
+ * `proposed`; a decoration cannot accept an element or change a base element.
81
+ * Containers claim a process; components name their container and member aliases,
82
+ * just like the base C4 contract. A component may belong to a base or draft container.
83
+ */
84
+ export type DecorationDraftC4Element =
85
+ | Omit<C4Container, 'state' | 'decidedAt'>
86
+ | Omit<C4Component, 'state' | 'decidedAt'>
87
+ | Omit<C4ExternalSystem, 'state' | 'decidedAt'>
88
+ | Omit<C4Person, 'state' | 'decidedAt'>;
89
+
90
+ export interface DecorationDraftC4 {
91
+ /**
92
+ * New elements only. Element ids and member aliases share the host's composed
93
+ * C4 namespace, so the host must qualify them when combining subsystem models.
94
+ * Omit a container's parentId to use the displayed system.
95
+ */
96
+ elements?: DecorationDraftC4Element[];
97
+ /** Authored relationships between existing or draft C4 element ids. */
98
+ edges?: C4Edge[];
99
+ }
100
+
77
101
  export interface DecorationDraft {
78
102
  components?: DecorationDraftComponent[];
79
103
  edges?: DecorationDraftEdge[];
104
+ c4?: DecorationDraftC4;
80
105
  }
81
106
 
82
107
  export interface DecorationProvenance {
@@ -0,0 +1,134 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import type { C4Model } from './c4';
3
+ import type { DecorationDraftC4, SubsystemDecoration } from './decoration';
4
+ import { applyDecorationC4 } from './decorationC4';
5
+
6
+ const base: C4Model = {
7
+ view: 'container',
8
+ system: { id: 'system:app', label: 'App' },
9
+ nodes: [{
10
+ kind: 'container', id: 'container:desktop', label: 'Desktop',
11
+ containerKind: 'application', technology: 'React', state: 'accepted',
12
+ }],
13
+ edges: [],
14
+ };
15
+
16
+ function decoration(c4?: DecorationDraftC4): SubsystemDecoration {
17
+ return {
18
+ version: 1, id: 'dec-sync', title: 'Sync', description: '', trails: [],
19
+ draft: { c4 },
20
+ provenance: { source: 'author', at: '2026-10-26T00:00:00.000Z' },
21
+ };
22
+ }
23
+
24
+ const c4: DecorationDraftC4 = {
25
+ elements: [
26
+ {
27
+ kind: 'component', id: 'component:sync', label: 'Sync coordinator',
28
+ container: 'container:desktop', technology: 'TypeScript', members: ['sync'],
29
+ },
30
+ {
31
+ kind: 'container', id: 'container:worker', label: 'Sync worker',
32
+ containerKind: 'application', technology: 'Bun', process: 'sync-worker',
33
+ },
34
+ {
35
+ kind: 'component', id: 'component:queue', label: 'Upload queue',
36
+ container: 'container:worker', technology: 'TypeScript', members: ['upload'],
37
+ },
38
+ ],
39
+ edges: [{
40
+ id: 'draft:dispatch', source: 'component:sync', target: 'component:queue',
41
+ label: 'Dispatches upload', protocol: 'RPC', mechanisms: ['calls'], count: 1,
42
+ }],
43
+ };
44
+
45
+ describe('applyDecorationC4', () => {
46
+ test('adds proposed containers, components in base/draft containers, and relationships', () => {
47
+ const before = JSON.stringify({ base, c4 });
48
+ const projected = applyDecorationC4(base, decoration(c4));
49
+ expect(projected.nodes).toHaveLength(4);
50
+ expect(projected.nodes[0]?.state).toBe('accepted');
51
+ expect(projected.nodes.slice(1).every((node) => node.state === 'proposed')).toBe(true);
52
+ expect(projected.nodes[2]?.parentId).toBe(base.system.id);
53
+ expect(projected.edges).toEqual(c4.edges!.map((edge) => ({ ...edge, draft: true })));
54
+ expect(projected.nodes[1]).toMatchObject({ container: 'container:desktop', members: ['sync'] });
55
+ expect(projected.nodes[3]).toMatchObject({ container: 'container:worker', members: ['upload'] });
56
+ expect(JSON.stringify({ base, c4 })).toBe(before);
57
+ });
58
+
59
+ test('turning the decoration off restores the original base projection', () => {
60
+ expect(applyDecorationC4(base, decoration(c4), false)).toBe(base);
61
+ expect(applyDecorationC4(base, decoration())).toBe(base);
62
+ });
63
+
64
+ test('can relate two existing elements without adding boxes', () => {
65
+ const existing: C4Model = {
66
+ ...base,
67
+ nodes: [
68
+ ...base.nodes,
69
+ { kind: 'external-system', id: 'external:remote', label: 'Remote', state: 'accepted' },
70
+ ],
71
+ };
72
+ const edges = [{
73
+ id: 'draft:upload', source: 'container:desktop', target: 'external:remote',
74
+ label: 'Uploads drawing', mechanisms: ['calls'], count: 1,
75
+ }];
76
+ expect(applyDecorationC4(existing, decoration({ edges })).edges)
77
+ .toEqual(edges.map((edge) => ({ ...edge, draft: true })));
78
+ });
79
+
80
+ test('marks only decoration relationships as draft without changing their text or the base', () => {
81
+ const baseEdge = {
82
+ id: 'base:flow', source: 'container:desktop', target: 'container:desktop',
83
+ label: 'Existing flow', protocol: 'event', mechanisms: ['produces'], count: 1,
84
+ };
85
+ const withBaseEdge = { ...base, edges: [baseEdge] };
86
+ const projected = applyDecorationC4(withBaseEdge, decoration(c4));
87
+ expect(projected.edges[0]).toBe(baseEdge);
88
+ expect(projected.edges[0]?.draft).toBeUndefined();
89
+ expect(projected.edges[1]).toMatchObject({ draft: true, label: 'Dispatches upload', protocol: 'RPC' });
90
+ expect(c4.edges![0]!.draft).toBeUndefined();
91
+ });
92
+
93
+ test('rejects ids that would replace base or draft elements', () => {
94
+ const duplicate = { ...c4.elements![1]!, id: 'container:desktop' };
95
+ expect(() => applyDecorationC4(base, decoration({ elements: [duplicate] })))
96
+ .toThrow('Duplicate C4 element id');
97
+ expect(() => applyDecorationC4(base, decoration({
98
+ elements: [c4.elements![1]!, c4.elements![1]!],
99
+ }))).toThrow('Duplicate C4 element id');
100
+ });
101
+
102
+ test('rejects missing containers and conflicting parents', () => {
103
+ expect(() => applyDecorationC4(base, decoration({ elements: [c4.elements![2]!] })))
104
+ .toThrow('Missing C4 container');
105
+ expect(() => applyDecorationC4(base, decoration({
106
+ elements: [{ ...c4.elements![0]!, parentId: 'container:other' }],
107
+ }))).toThrow('Conflicting C4 parent');
108
+ expect(() => applyDecorationC4(base, decoration({
109
+ elements: [{ ...c4.elements![1]!, parentId: 'system:other' }],
110
+ }))).toThrow('Unknown C4 system');
111
+ });
112
+
113
+ test('rejects missing edge endpoints and duplicate edge ids', () => {
114
+ expect(() => applyDecorationC4(base, decoration({ edges: c4.edges })))
115
+ .toThrow('Missing C4 endpoint');
116
+ const projected = applyDecorationC4(base, decoration(c4));
117
+ expect(() => applyDecorationC4(projected, decoration({ edges: c4.edges })))
118
+ .toThrow('Duplicate C4 edge id');
119
+ });
120
+
121
+ test('supports external systems and people outside the system boundary', () => {
122
+ const projected = applyDecorationC4(base, decoration({
123
+ elements: [
124
+ { kind: 'external-system', id: 'external:remote', label: 'Remote', members: ['remote'] },
125
+ { kind: 'person', id: 'person:author', label: 'Author' },
126
+ ],
127
+ }));
128
+ expect(projected.nodes.slice(1).every((node) => !node.parentId && node.state === 'proposed'))
129
+ .toBe(true);
130
+ expect(() => applyDecorationC4(base, decoration({
131
+ elements: [{ kind: 'person', id: 'person:author', label: 'Author', parentId: base.system.id }],
132
+ }))).toThrow('External C4 element cannot have a parent');
133
+ });
134
+ });