@joplo-app/plugin-viz 0.0.0-stage → 0.10.0

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 (43) hide show
  1. package/LICENSE +97 -0
  2. package/dist/catalog.d.ts +8 -0
  3. package/dist/catalog.js +178 -0
  4. package/dist/components.d.ts +236 -0
  5. package/dist/components.js +55 -0
  6. package/dist/effects.d.ts +27 -0
  7. package/dist/effects.js +32 -0
  8. package/dist/guide.d.ts +3 -0
  9. package/dist/guide.js +79 -0
  10. package/dist/labels.json +12 -0
  11. package/dist/plugin.d.ts +6 -0
  12. package/dist/plugin.js +312 -0
  13. package/dist/runtime/bar-chart.d.ts +4 -0
  14. package/dist/runtime/bar-chart.js +204 -0
  15. package/dist/runtime/delta-bar.d.ts +4 -0
  16. package/dist/runtime/delta-bar.js +165 -0
  17. package/dist/runtime/heatmap.d.ts +4 -0
  18. package/dist/runtime/heatmap.js +138 -0
  19. package/dist/runtime/hooks.d.ts +36 -0
  20. package/dist/runtime/hooks.js +54 -0
  21. package/dist/runtime/line-chart.d.ts +4 -0
  22. package/dist/runtime/line-chart.js +197 -0
  23. package/dist/runtime/radar.d.ts +4 -0
  24. package/dist/runtime/radar.js +101 -0
  25. package/dist/runtime/ratio-bar.d.ts +4 -0
  26. package/dist/runtime/ratio-bar.js +77 -0
  27. package/dist/runtime/sankey.d.ts +4 -0
  28. package/dist/runtime/sankey.js +171 -0
  29. package/dist/runtime/scatter-plot.d.ts +4 -0
  30. package/dist/runtime/scatter-plot.js +202 -0
  31. package/dist/runtime/time-lanes.d.ts +4 -0
  32. package/dist/runtime/time-lanes.js +179 -0
  33. package/dist/runtime/tokens.d.ts +11 -0
  34. package/dist/runtime/tokens.js +51 -0
  35. package/dist/runtime/waterfall.d.ts +4 -0
  36. package/dist/runtime/waterfall.js +119 -0
  37. package/dist/runtime.d.ts +2 -0
  38. package/dist/runtime.js +26 -0
  39. package/dist/schema.d.ts +202 -0
  40. package/dist/schema.js +255 -0
  41. package/dist/version.json +3 -0
  42. package/package.json +67 -3
  43. package/README.md +0 -3
package/dist/guide.js ADDED
@@ -0,0 +1,79 @@
1
+ import { COMPONENT_DOCS, COMPONENT_EXAMPLES } from "./catalog.js";
2
+ export const skill = `# Narrative Data Visualization: viz
3
+
4
+ Use \`@joplo-app/plugin-viz\` for all quantitative comparisons, magnitudes, part-to-whole ratios, trends, timelines, Pareto trade-offs, matrices, flows, attributions, and multi-axis profiles. Install \`@joplo-app/plugin-viz\`, default-import \`viz\`, add \`viz\` to \`config.plugins\`, and run \`npx joplo skill install\`.
5
+
6
+ ## Choose the right chart (never abuse RatioBar or hand-roll div bars)
7
+ - **Qualitative UI / prose A-vs-B switching** → stay in \`@joplo-app/plugin-ui\` (\`<Compare>\`).
8
+ - **Before → After metric gain / reduction** (e.g., CPU −70%, Memory −80%, latency drop) → **\`<DeltaBar>\`** (default \`variant="ghost"\` keeps a dashed ghost baseline in place and uncovers a tinted savings band as the bar retracts; \`variant="paired"\` renders stacked old/new bars). Never abuse \`<RatioBar>\` for before/after comparisons.
9
+ - **Category magnitude, stacked composition, or invariant locking** → **\`<BarChart>\`** (\`orientation="vertical"|"horizontal"\`, \`layout="grouped"|"stacked"\`, row \`locked: true\` pins an invariant bar while other bars scale).
10
+ - **Part-of-a-whole split or pass threshold** (e.g., 98% test pass vs 25% prod match against a 99% bar) → **\`<RatioBar>\`** (clean single-value display by default; set \`showDenominator\` only when explicit \`x / total\` is needed).
11
+ - **Trend over time / scaling curve / cliff inflection** → **\`<LineChart>\`** (zero-stretch HTML labels + crisp SVG curve + \`revealTo()\` progressive draw + \`referenceLine\` / \`referenceBand\`).
12
+ - **Time intervals / Gantt / concurrent waterfall** → **\`<TimeLanes>\`** (full tick gridlines, animated \`setCursor()\` playhead, \`focusDatum()\` lane dimming, and automatic external labels so narrow bars never clip text).
13
+ - **2D trade-off / cost-vs-accuracy Pareto frontier** → **\`<ScatterPlot pareto="top-left">\`** (auto-computes and strokes the Pareto frontier polyline, optional quadrant tint).
14
+ - **2D matrix density / attention weights / confusion matrix** → **\`<Heatmap>\`** (high-contrast auto-white text on dark cells, row/col/cell \`focusDatum()\`).
15
+ - **Proportional multi-stage flow / funnel conservation** → **\`<Sankey>\`** (\`d3-sankey\` curved cubic-Bezier ribbons tapering from wide to narrow, single-path \`focusDatum()\`).
16
+ - **Step-by-step positive/negative attribution** (how 100% dropped to 30%) → **\`<Waterfall>\`** (cumulative floating steps + dashed stair connectors + \`revealTo()\`).
17
+ - **Multi-dimension profile comparison** (4–7 axes) → **\`<Radar>\`** (polygonal spiderweb rings + translucent series overlays + direct axis/delta scores).
18
+
19
+ ## Narrative step effects (deterministic compile-time snapshots)
20
+ Import \`focusDatum\`, \`revealTo\`, \`pinBaseline\`, and \`setCursor\` from \`@joplo-app/plugin-viz\`:
21
+ - \`focusDatum(chartId, targetId | targetIds | null)\`: dim unrelated bars/points/lanes/rows/nodes while spotlighting the active datum. For Heatmap, pass \`'row:<name>'\`, \`'col:<name>'\`, \`'cell:<r>:<c>'\`, or a \`cellAnchors\` id.
22
+ - \`revealTo(chartId, cutoff | null)\`: reveal a \`LineChart\` up to an X label or index, or a \`Waterfall\` up to a step id or index.
23
+ - \`pinBaseline(chartId)\`: lock the chart's current numeric values as the remembered baseline in \`step.ext.viz.baselines\`. (Step 0 values are also captured automatically when \`baseline\` is omitted.)
24
+ - \`setCursor(chartId, value | null, { label? })\`: slide a vertical playhead across \`TimeLanes\` or \`LineChart\`.
25
+
26
+ ## Addressable anchors & silent observation windows
27
+ - Give every important item/point/span/node/step an \`id\` (or pass \`itemIds\` / \`spanIds\` / \`pointIds\` / \`cellAnchors\` when data comes from state bindings). Every registered id receives a DOM \`data-jid\` anchor so \`camera()\`, \`callout()\`, \`highlight()\`, \`spotlight()\`, and Alt-click review inspection land directly on the bar, point, or cell.
28
+ - Pair big quantitative transitions (e.g., \`DeltaBar\` retract, \`LineChart\` \`revealTo\`, \`TimeLanes\` \`setCursor\`) with a brief silent observation beat (\`narrate(false)\` + \`hold(2.0)\`) so viewers watch the motion without competing audio.
29
+
30
+ ## Verify & pitfalls
31
+ - Run \`npx joplo check\`: fix \`VIZ_DATA_INVALID\`, \`VIZ_CHART_UNKNOWN\`, \`RATIO_BAR_INVALID\`, or \`TIME_LANES_INVALID\` before rendering.
32
+ - Never wrap charts inside redundant bordered cards with duplicate titles when \`title\` / \`subtitle\` props already live on the chart.
33
+ - Give narrow \`TimeLanes\` spans (\`< 24%\` of domain) a concise \`shortLabel\` so the bar carries the short pill while the full \`label\` floats cleanly beside the bar without clipping.
34
+ - Read \`npx joplo skill viz/components\` for full prop tables and \`npx joplo skill viz/recipes\` for animation and framing patterns.
35
+
36
+ Related topics: components, authoring, focus, check, plugins
37
+ `;
38
+ export const recipes = `# Narrative DataViz recipes and pitfalls
39
+
40
+ ## 1. Before-vs-after payoff without spoiling the reveal (DeltaBar)
41
+ Start at the baseline step with \`value === baseline\` (so no savings badge spoils the twist early), then update the bound state in a silent observation beat:
42
+ \`\`\`tsx
43
+ <DeltaBar
44
+ id="payoff"
45
+ title="单请求实测资源与延迟"
46
+ unit="%"
47
+ lowerIsBetter
48
+ items={[
49
+ { id: 'delta_cpu', label: '单请求 CPU', baseline: 100, value: $.ui.cpuRust, deltaLabel: '−70%' },
50
+ { id: 'delta_mem', label: '单请求内存', baseline: 100, value: $.ui.memRust, deltaLabel: '−80%+' },
51
+ { id: 'delta_ttft', label: '中位 TTFT', baseline: 100, value: $.ui.ttftRust, deltaLabel: '−20%' },
52
+ ]}
53
+ />
54
+ \`\`\`
55
+ In the flow:
56
+ 1. Show Python baseline (\`cpuRust: 100, memRust: 100, ttftRust: 100\`) — clean solid bars, zero premature savings text.
57
+ 2. Drop values (\`cpuRust: 30, memRust: 20, ttftRust: 80\`) with \`narrate(false)\` + \`hold(2.2)\` — bars retract smoothly with row stagger, uncovering the dashed ghost baseline and emerald savings band.
58
+ 3. Add \`focusDatum('payoff', 'delta_mem')\` + \`callout('delta_mem', '内存直降八成+')\` to spotlight one metric.
59
+
60
+ ## 2. Invariant-locked comparison (BarChart)
61
+ Mark constant rows with \`locked: true\` (\`lockedLabel: 'LOCKED · 不变量'\`) AND pass a shared fixed \`domain={[0, maxValue]}\` (and keep the same chart/row IDs across states). Without an explicit \`domain\`, auto-scaling shrinks an invariant bar whenever another bar grows (e.g. a constant \`1×\` bar shrinking from 100% → 50% → 33% as another bar grows 1 → 2 → 3).
62
+
63
+ ## 3. Progressive trend & inflection callout (LineChart)
64
+ Use \`revealTo('trend', '5 月')\` to hold suspense on an early plateau, then \`revealTo('trend', '9 月')\` in a silent observation step, followed by \`callout('pt_june', '6 月规则沉淀 → 断崖收敛')\` anchored directly on the point id.
65
+
66
+ ## 4. Narrow bars in TimeLanes
67
+ If a span occupies less than ~24% of \`domain\`, pass \`shortLabel\` (e.g., \`shortLabel: '零停服切流'\`, \`label: '公开流量分批切入 Rust'\`). \`TimeLanes\` centers \`shortLabel\` inside the bar and floats the full \`label\` into the adjacent open track so text is never truncated.
68
+
69
+ ## 5. Single-path storytelling in Sankey & Heatmap
70
+ - \`Sankey\`: use \`focusDatum('flow', ['diff', 'gate'])\` to dim quiet baseline traffic while illuminating the anomalous cascade.
71
+ - \`Heatmap\`: pass \`cellAnchors={{ '4:2': 'cell_rust_code' }}\` and use \`focusDatum('attn', 'row:Rust')\` + \`callout('cell_rust_code', '最高权重 0.46')\` to walk viewers through one row at a time.
72
+ `;
73
+ export function componentGuide() {
74
+ return [
75
+ '# Data Visualization component catalog (@joplo-app/plugin-viz)',
76
+ 'Import these markers and effects (`focusDatum`, `revealTo`, `pinBaseline`, `setCursor`) from `@joplo-app/plugin-viz`; enable `viz` in `config.plugins`.',
77
+ ...Object.entries(COMPONENT_DOCS).map(([name, doc]) => ['## ' + name, doc, ...(COMPONENT_EXAMPLES[name] ? ['', '```tsx', COMPONENT_EXAMPLES[name], '```'] : [])].join('\n')),
78
+ ].join('\n\n');
79
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "DeltaBar": { "en": "Delta bar", "zh-CN": "前后变化对比条" },
3
+ "BarChart": { "en": "Bar chart", "zh-CN": "柱状图" },
4
+ "RatioBar": { "en": "Ratio bar", "zh-CN": "占比阈值条" },
5
+ "LineChart": { "en": "Line chart", "zh-CN": "趋势折线图" },
6
+ "TimeLanes": { "en": "Time lanes", "zh-CN": "时间泳道图" },
7
+ "ScatterPlot": { "en": "Scatter & Pareto plot", "zh-CN": "散点 / 帕累托图" },
8
+ "Heatmap": { "en": "Heatmap matrix", "zh-CN": "二维热力矩阵" },
9
+ "Sankey": { "en": "Sankey flow", "zh-CN": "桑基流向图" },
10
+ "Waterfall": { "en": "Waterfall attribution", "zh-CN": "瀑布归因图" },
11
+ "Radar": { "en": "Radar profile", "zh-CN": "多维雷达图" }
12
+ }
@@ -0,0 +1,6 @@
1
+ export * from './components.js';
2
+ export * from './effects.js';
3
+ export { computeParetoFrontier, computeWaterfall, formatDeltaPercent, layoutTimeLanes, ratioError, ratioParts, readTimeLanes, } from './schema.js';
4
+ export type { DeltaBarItemInput, ParetoCorner, RatioSegment, TimeSpan, VizChartSnapshot, VizFrame, VizOp, WaterfallBar, WaterfallStepInput, } from './schema.js';
5
+ declare const _default: import("@joplo-app/kit").PluginDef;
6
+ export default _default;
package/dist/plugin.js ADDED
@@ -0,0 +1,312 @@
1
+ import { isBind } from '@joplo-app/kit/node';
2
+ import { definePlugin, } from '@joplo-app/kit/plugin';
3
+ import packageInfo from './version.json' with { type: 'json' };
4
+ import labels from './labels.json' with { type: 'json' };
5
+ import { COMPONENT_DOCS, COMPONENT_EXAMPLES, COMPONENT_TYPES, INSPECT_FIELDS, TEXT_PATHS, TEXT_PROPS, } from "./catalog.js";
6
+ import { componentGuide, recipes, skill } from "./guide.js";
7
+ import { ratioError, readTimeLanes, StepDataS, validateChartArray, } from "./schema.js";
8
+ export * from "./components.js";
9
+ export * from "./effects.js";
10
+ export { computeParetoFrontier, computeWaterfall, formatDeltaPercent, layoutTimeLanes, ratioError, ratioParts, readTimeLanes, } from "./schema.js";
11
+ const allNodes = (n) => [n, ...(n.children ?? []).flatMap(allNodes)];
12
+ const isVizChart = (n) => n.type.startsWith('viz:');
13
+ const vizChartsIn = (roots) => roots.flatMap(allNodes).filter(isVizChart);
14
+ function extractBaselineMap(node, resolvedProps) {
15
+ if (node.type === 'viz:DeltaBar' && Array.isArray(resolvedProps.items)) {
16
+ const out = {};
17
+ for (const [i, raw] of resolvedProps.items.entries()) {
18
+ if (!raw || typeof raw !== 'object')
19
+ continue;
20
+ const item = raw;
21
+ const key = typeof item.id === 'string' && item.id ? item.id : String(i);
22
+ const val = typeof item.baseline === 'number' && Number.isFinite(item.baseline)
23
+ ? item.baseline
24
+ : typeof item.value === 'number' && Number.isFinite(item.value)
25
+ ? item.value
26
+ : undefined;
27
+ if (val !== undefined)
28
+ out[key] = val;
29
+ }
30
+ return Object.keys(out).length ? out : undefined;
31
+ }
32
+ return undefined;
33
+ }
34
+ function captureCurrentValues(node, resolvedProps) {
35
+ if (node.type === 'viz:DeltaBar' && Array.isArray(resolvedProps.items)) {
36
+ const out = {};
37
+ for (const [i, raw] of resolvedProps.items.entries()) {
38
+ if (!raw || typeof raw !== 'object')
39
+ continue;
40
+ const item = raw;
41
+ const key = typeof item.id === 'string' && item.id ? item.id : String(i);
42
+ if (typeof item.value === 'number' && Number.isFinite(item.value))
43
+ out[key] = item.value;
44
+ }
45
+ return Object.keys(out).length ? out : undefined;
46
+ }
47
+ return undefined;
48
+ }
49
+ const hooks = {
50
+ node(n, { report }) {
51
+ const props = n.props ?? {};
52
+ switch (n.type) {
53
+ case 'viz:RatioBar': {
54
+ const err = ratioError(props, isBind);
55
+ if (err)
56
+ report('RATIO_BAR_INVALID', `<RatioBar> ${err}`, n.source);
57
+ return;
58
+ }
59
+ case 'viz:TimeLanes': {
60
+ const { domain, spans, spanIds } = props;
61
+ if (spanIds !== undefined &&
62
+ !(Array.isArray(spanIds) && spanIds.every((id) => typeof id === 'string' && id.trim()) && new Set(spanIds).size === spanIds.length)) {
63
+ report('TIME_LANES_INVALID', '<TimeLanes spanIds> expects unique, nonempty target ids.', n.source);
64
+ }
65
+ const result = readTimeLanes({
66
+ ...props,
67
+ domain: isBind(domain) ? [-Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER] : domain,
68
+ spans: isBind(spans) ? [] : spans,
69
+ });
70
+ if (result.error)
71
+ report('TIME_LANES_INVALID', `<TimeLanes> ${result.error}`, n.source);
72
+ return;
73
+ }
74
+ case 'viz:DeltaBar': {
75
+ const err = validateChartArray('DeltaBar', 'items', props.items, isBind);
76
+ if (err)
77
+ report('VIZ_DATA_INVALID', err, n.source);
78
+ if (props.variant !== undefined && !isBind(props.variant) && props.variant !== 'ghost' && props.variant !== 'paired') {
79
+ report('VIZ_DATA_INVALID', '<DeltaBar variant> must be "ghost" or "paired"', n.source);
80
+ }
81
+ return;
82
+ }
83
+ case 'viz:BarChart': {
84
+ const e1 = validateChartArray('BarChart', 'data', props.data, isBind);
85
+ const e2 = validateChartArray('BarChart', 'series', props.series, isBind);
86
+ if (e1)
87
+ report('VIZ_DATA_INVALID', e1, n.source);
88
+ if (e2)
89
+ report('VIZ_DATA_INVALID', e2, n.source);
90
+ if (typeof props.dataKey !== 'string' || !props.dataKey) {
91
+ report('VIZ_DATA_INVALID', '<BarChart> requires a non-empty string dataKey', n.source);
92
+ }
93
+ return;
94
+ }
95
+ case 'viz:LineChart': {
96
+ const e1 = validateChartArray('LineChart', 'data', props.data, isBind);
97
+ const e2 = validateChartArray('LineChart', 'series', props.series, isBind);
98
+ if (e1)
99
+ report('VIZ_DATA_INVALID', e1, n.source);
100
+ if (e2)
101
+ report('VIZ_DATA_INVALID', e2, n.source);
102
+ if (typeof props.dataKey !== 'string' || !props.dataKey) {
103
+ report('VIZ_DATA_INVALID', '<LineChart> requires a non-empty string dataKey', n.source);
104
+ }
105
+ return;
106
+ }
107
+ case 'viz:ScatterPlot': {
108
+ const err = validateChartArray('ScatterPlot', 'points', props.points, isBind);
109
+ if (err)
110
+ report('VIZ_DATA_INVALID', err, n.source);
111
+ return;
112
+ }
113
+ case 'viz:Heatmap': {
114
+ const e1 = validateChartArray('Heatmap', 'rows', props.rows, isBind);
115
+ const e2 = validateChartArray('Heatmap', 'cols', props.cols, isBind);
116
+ const e3 = validateChartArray('Heatmap', 'values', props.values, isBind);
117
+ if (e1)
118
+ report('VIZ_DATA_INVALID', e1, n.source);
119
+ if (e2)
120
+ report('VIZ_DATA_INVALID', e2, n.source);
121
+ if (e3)
122
+ report('VIZ_DATA_INVALID', e3, n.source);
123
+ return;
124
+ }
125
+ case 'viz:Sankey': {
126
+ const e1 = validateChartArray('Sankey', 'nodes', props.nodes, isBind);
127
+ const e2 = validateChartArray('Sankey', 'links', props.links, isBind);
128
+ if (e1)
129
+ report('VIZ_DATA_INVALID', e1, n.source);
130
+ if (e2)
131
+ report('VIZ_DATA_INVALID', e2, n.source);
132
+ return;
133
+ }
134
+ case 'viz:Waterfall': {
135
+ const err = validateChartArray('Waterfall', 'steps', props.steps, isBind);
136
+ if (err)
137
+ report('VIZ_DATA_INVALID', err, n.source);
138
+ return;
139
+ }
140
+ case 'viz:Radar': {
141
+ const e1 = validateChartArray('Radar', 'axes', props.axes, isBind);
142
+ const e2 = validateChartArray('Radar', 'series', props.series, isBind);
143
+ if (e1)
144
+ report('VIZ_DATA_INVALID', e1, n.source);
145
+ if (e2)
146
+ report('VIZ_DATA_INVALID', e2, n.source);
147
+ return;
148
+ }
149
+ }
150
+ },
151
+ derive(node) {
152
+ if (!isVizChart(node))
153
+ return;
154
+ return {
155
+ framing: Object.fromEntries(allNodes(node).map((child) => [child.id, { kind: child === node ? 'root' : 'content' }])),
156
+ };
157
+ },
158
+ effect(effect, ctx) {
159
+ const p = (effect.payload ?? {});
160
+ const chart = typeof p.chart === 'string' ? p.chart : '';
161
+ const charts = vizChartsIn(ctx.roots);
162
+ const targetNode = charts.find((n) => n.id === chart);
163
+ if (!targetNode) {
164
+ ctx.report('VIZ_CHART_UNKNOWN', `${effect.name}("${chart}"): no viz chart with id="${chart}" on this step`, ctx.source);
165
+ return;
166
+ }
167
+ const ops = [...(ctx.data?.ops ?? [])];
168
+ const refs = new Set([chart]);
169
+ if (effect.name === 'focus') {
170
+ const raw = p.targets;
171
+ if (raw !== null && !(Array.isArray(raw) && raw.every((x) => typeof x === 'string' && x.trim()))) {
172
+ ctx.report('VIZ_EFFECT_INVALID', 'focusDatum(chart, targets) expects a string, string[], or null', ctx.source);
173
+ return;
174
+ }
175
+ const targets = raw === null ? null : raw;
176
+ ops.push({ kind: 'focus', chart, targets });
177
+ if (targets) {
178
+ const anchorIds = new Set((targetNode.children ?? []).map((c) => c.id));
179
+ for (const t of targets)
180
+ if (anchorIds.has(t))
181
+ refs.add(t);
182
+ }
183
+ }
184
+ else if (effect.name === 'reveal') {
185
+ const cutoff = p.cutoff;
186
+ if (cutoff !== null && typeof cutoff !== 'string' && !(typeof cutoff === 'number' && Number.isFinite(cutoff))) {
187
+ ctx.report('VIZ_EFFECT_INVALID', 'revealTo(chart, cutoff) expects a finite number, string, or null', ctx.source);
188
+ return;
189
+ }
190
+ ops.push({ kind: 'reveal', chart, cutoff: cutoff });
191
+ }
192
+ else if (effect.name === 'pinBaseline') {
193
+ ops.push({ kind: 'pinBaseline', chart });
194
+ }
195
+ else if (effect.name === 'cursor') {
196
+ const val = p.value;
197
+ if (val !== null && typeof val !== 'string' && !(typeof val === 'number' && Number.isFinite(val))) {
198
+ ctx.report('VIZ_EFFECT_INVALID', 'setCursor(chart, value) expects a finite number, string, or null', ctx.source);
199
+ return;
200
+ }
201
+ const label = typeof p.label === 'string' ? p.label : undefined;
202
+ ops.push({ kind: 'cursor', chart, value: val, ...(label !== undefined ? { label } : {}) });
203
+ }
204
+ else {
205
+ ctx.report('PLUGIN_EFFECT_UNKNOWN', `Unknown viz effect ${effect.name}`, ctx.source);
206
+ return;
207
+ }
208
+ return { data: { ops }, references: [...refs] };
209
+ },
210
+ frame(ctx) {
211
+ // Validate dynamically bound TimeLanes intervals and cross-element ID collisions at every step position.
212
+ for (const scene of ctx.scenes) {
213
+ const nodes = allNodes(scene.root);
214
+ const bound = nodes.filter((n) => n.type === 'viz:TimeLanes' && (typeof n.props?.spans === 'string' || typeof n.props?.domain === 'string'));
215
+ if (!bound.length)
216
+ continue;
217
+ const used = new Set(nodes.map((n) => n.id));
218
+ for (const node of bound) {
219
+ const chart = readTimeLanes(ctx.resolveProps(node));
220
+ const at = `<TimeLanes id="${node.id}"> at position ${ctx.position}`;
221
+ if (!chart.data) {
222
+ ctx.report('TIME_LANES_INVALID', `${at}: ${chart.error}`, node.source);
223
+ continue;
224
+ }
225
+ const declared = new Set(node.children?.map((child) => child.id));
226
+ for (const { id } of chart.data.spans) {
227
+ if (!declared.has(id) && used.has(id)) {
228
+ ctx.report('TIME_LANES_INVALID', `${at}: span id "${id}" already belongs to another element on this stage.`, node.source);
229
+ }
230
+ used.add(id);
231
+ }
232
+ }
233
+ }
234
+ const charts = vizChartsIn(ctx.roots);
235
+ if (!charts.length)
236
+ return;
237
+ const prev = ctx.previousData?.charts ?? {};
238
+ const ops = ctx.data?.ops ?? [];
239
+ const out = {};
240
+ for (const node of charts) {
241
+ if (out[node.id])
242
+ continue;
243
+ const resolved = ctx.resolveProps(node);
244
+ const base = prev[node.id] ? { ...prev[node.id] } : {};
245
+ // Auto-capture Step 0 baselines for DeltaBar so later steps know original footprints deterministically.
246
+ if (!base.baselines) {
247
+ const initial = extractBaselineMap(node, resolved);
248
+ if (initial)
249
+ base.baselines = initial;
250
+ }
251
+ const mine = ops.filter((op) => op.chart === node.id);
252
+ for (const op of mine) {
253
+ if (op.kind === 'focus')
254
+ base.focus = op.targets;
255
+ else if (op.kind === 'reveal')
256
+ base.reveal = op.cutoff;
257
+ else if (op.kind === 'cursor') {
258
+ base.cursor = op.value === null ? null : { value: op.value, ...(op.label !== undefined ? { label: op.label } : {}) };
259
+ }
260
+ else if (op.kind === 'pinBaseline') {
261
+ const captured = captureCurrentValues(node, resolved);
262
+ if (captured)
263
+ base.baselines = captured;
264
+ }
265
+ }
266
+ out[node.id] = base;
267
+ }
268
+ return { charts: out };
269
+ },
270
+ };
271
+ const components = Object.fromEntries(COMPONENT_TYPES.map((name) => [
272
+ name,
273
+ {
274
+ ...(labels[name] ? { label: labels[name] } : {}),
275
+ ...(INSPECT_FIELDS[name] ? { inspect: INSPECT_FIELDS[name] } : {}),
276
+ role: 'chart',
277
+ doc: COMPONENT_DOCS[name],
278
+ example: COMPONENT_EXAMPLES[name],
279
+ selfEvident: true,
280
+ traits: {
281
+ selfEvident: true,
282
+ text: ['aria-label', ...TEXT_PROPS[name]],
283
+ ...(TEXT_PATHS[name] ? { textPaths: TEXT_PATHS[name] } : {}),
284
+ },
285
+ },
286
+ ]));
287
+ export default definePlugin({
288
+ packageName: '@joplo-app/plugin-viz',
289
+ id: 'viz',
290
+ title: 'Narrative Data Visualization',
291
+ version: packageInfo.version,
292
+ bestFor: 'Narrative quantitative comparisons (DeltaBar), bars/ratios/trends, timelines with playhead cursor (TimeLanes), Pareto trade-offs (ScatterPlot), matrices (Heatmap), flow ribbons (Sankey), attribution bridges (Waterfall), and multi-axis profiles (Radar)',
293
+ pairsWith: [
294
+ { with: 'content', packageName: '@joplo-app/plugin-content', how: 'Place each chart in its own spacious content:Canvas zone and steer camera() across narrative chapters; use focusDatum()/revealTo()/setCursor() for deterministic step transitions.' },
295
+ { with: 'ui', packageName: '@joplo-app/plugin-ui', how: 'Pair viz charts with ui KPI Stat cards, qualitative Compare panels, or Terminal logs inside the same dashboard or story.' },
296
+ { with: 'diagram', packageName: '@joplo-app/plugin-diagram', how: 'Follow a diagram architecture or sequence explanation with a viz DeltaBar, TimeLanes, or Waterfall zone to back up structural claims with measurements.' },
297
+ ],
298
+ runtime: new URL(import.meta.url.endsWith('.ts') ? './runtime.tsx' : './runtime.js', import.meta.url),
299
+ skill,
300
+ skillTopics: {
301
+ components: { description: 'Prop tables and author examples for all 10 viz components', body: componentGuide() },
302
+ recipes: { description: 'Narrative data visualization patterns, transitions, and pitfalls', body: recipes },
303
+ },
304
+ components,
305
+ schemas: { step: StepDataS },
306
+ data: {
307
+ step: {
308
+ scope: [{ path: ['charts'], kind: 'map', domain: 'element' }],
309
+ },
310
+ },
311
+ compile: hooks,
312
+ });
@@ -0,0 +1,4 @@
1
+ import type { ComponentCtx } from '@joplo-app/kit/plugin';
2
+ export declare function BarChartView({ ctx }: {
3
+ ctx: ComponentCtx;
4
+ }): import("react").JSX.Element;
@@ -0,0 +1,204 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { scaleLinear, scaleLog } from 'd3-scale';
3
+ import { motion, useRoot } from '@joplo-app/kit/renderer';
4
+ import { ChartHeader, useAnchorAttrs, useVizChart } from "./hooks.js";
5
+ import { DIMMED, EASE_OUT_EXPO, INK, LINE, LINE_STRONG, MONO, OK, SUBTLE, VIZ_FONT_SANS, arr, dim, formatNumber, num, str, tint, vizColor, } from "./tokens.js";
6
+ function BarItemVertical({ row, id, label, series, stacked, scale, plotH, unit, directLabels, animate, dimmed, anchors, }) {
7
+ const anchorProps = useAnchorAttrs(anchors, id, label);
8
+ const vals = series.map((s) => {
9
+ const raw = row[s.name];
10
+ return typeof raw === 'number' && Number.isFinite(raw) ? Math.max(0, raw) : 0;
11
+ });
12
+ const total = vals.reduce((a, b) => a + b, 0);
13
+ const transition = animate ? { duration: 0.62, ease: EASE_OUT_EXPO } : { duration: 0 };
14
+ return (_jsxs("div", { ...anchorProps, style: {
15
+ flex: 1,
16
+ minWidth: 0,
17
+ display: 'flex',
18
+ flexDirection: 'column',
19
+ alignItems: 'center',
20
+ height: '100%',
21
+ justifyContent: 'flex-end',
22
+ opacity: dimmed ? 0.25 : 1,
23
+ transition: animate ? 'opacity 260ms ease' : undefined,
24
+ }, children: [row.deltaBadge && (_jsx("span", { style: {
25
+ marginBottom: 4,
26
+ padding: '2px 8px',
27
+ borderRadius: 999,
28
+ background: tint(OK, 14),
29
+ color: OK,
30
+ fontFamily: MONO,
31
+ fontSize: 11.5,
32
+ fontWeight: 850,
33
+ whiteSpace: 'nowrap',
34
+ }, children: row.deltaBadge })), directLabels && stacked && (_jsx("span", { style: { marginBottom: 6, fontFamily: MONO, fontSize: 13.5, fontWeight: 850, color: row.color ? vizColor(row.color) : INK }, children: formatNumber(total, unit) })), stacked ? (_jsx("div", { style: {
35
+ width: 'min(86px, 72%)',
36
+ display: 'flex',
37
+ flexDirection: 'column-reverse',
38
+ gap: 2,
39
+ }, children: series.map((s, si) => {
40
+ const v = vals[si];
41
+ if (v <= 0)
42
+ return null;
43
+ const totalH = Math.max(6, scale(total));
44
+ const segH = total > 0 ? Math.max(10, (v / total) * totalH) : 0;
45
+ const c = si === 0 && row.color ? vizColor(row.color) : s.color;
46
+ return (_jsx(motion.div, { initial: false, animate: { height: segH }, transition: transition, "data-jbar": `${s.name}:${label}`, style: {
47
+ width: '100%',
48
+ borderRadius: si === series.length - 1 || vals.slice(si + 1).every((x) => x <= 0) ? '7px 7px 2px 2px' : 2,
49
+ background: c,
50
+ display: 'flex',
51
+ alignItems: 'center',
52
+ justifyContent: 'center',
53
+ overflow: 'hidden',
54
+ }, children: segH >= 18 && series.filter((_, j) => vals[j] > 0).length > 1 && (_jsx("span", { style: { fontFamily: MONO, fontSize: 10.5, fontWeight: 800, color: '#fff', whiteSpace: 'nowrap' }, children: formatNumber(v) })) }, s.name));
55
+ }) })) : (_jsx("div", { style: { display: 'flex', alignItems: 'flex-end', justifyContent: 'center', gap: 6, width: '100%', height: plotH }, children: series.map((s, si) => {
56
+ const v = vals[si];
57
+ const barH = Math.max(v > 0 ? 6 : 0, scale(v));
58
+ const c = series.length === 1 && row.color ? vizColor(row.color) : s.color;
59
+ return (_jsxs("div", { style: { display: 'flex', flexDirection: 'column', alignItems: 'center', flex: '0 1 68px', width: series.length === 1 ? 'min(82px, 70%)' : undefined }, children: [directLabels && (_jsx("span", { style: { marginBottom: 5, fontFamily: MONO, fontSize: 12.5, fontWeight: 800, color: c, whiteSpace: 'nowrap' }, children: formatNumber(v, unit) })), _jsx(motion.div, { initial: false, animate: { height: barH }, transition: transition, "data-jbar": `${s.name}:${label}`, style: {
60
+ width: '100%',
61
+ borderRadius: '7px 7px 0 0',
62
+ background: c,
63
+ } })] }, s.name));
64
+ }) }))] }));
65
+ }
66
+ function BarItemHorizontal({ row, idx, id, label, series, stacked, scale, unit, showDirect, refObj, animate, dimmed, anchors, }) {
67
+ const anchorProps = useAnchorAttrs(anchors, id, label);
68
+ const locked = row.locked === true;
69
+ const vals = series.map((s) => (typeof row[s.name] === 'number' && Number.isFinite(row[s.name]) ? Math.max(0, row[s.name]) : 0));
70
+ const total = vals.reduce((a, b) => a + b, 0);
71
+ const primaryColor = row.color ? vizColor(row.color) : locked ? OK : series[0].color;
72
+ const transition = animate ? { duration: 0.68, delay: idx * 0.08, ease: EASE_OUT_EXPO } : { duration: 0 };
73
+ return (_jsxs("div", { ...anchorProps, style: {
74
+ display: 'flex',
75
+ flexDirection: 'column',
76
+ gap: 7,
77
+ opacity: dimmed ? 0.26 : 1,
78
+ transition: animate ? 'opacity 260ms ease' : undefined,
79
+ }, children: [_jsxs("div", { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10 }, children: [_jsxs("div", { style: { display: 'flex', alignItems: 'center', gap: 8 }, children: [_jsx("span", { style: { fontSize: 14, fontWeight: 800, color: INK }, children: label }), locked && (_jsx("span", { style: {
80
+ padding: '2px 8px',
81
+ borderRadius: 999,
82
+ background: tint(OK, 14),
83
+ color: OK,
84
+ fontSize: 11,
85
+ fontWeight: 850,
86
+ letterSpacing: 0.2,
87
+ }, children: typeof row.lockedLabel === 'string' ? row.lockedLabel : 'LOCKED · 不变量' }))] }), showDirect && (_jsx("span", { style: { fontFamily: MONO, fontSize: 14, fontWeight: 850, color: primaryColor }, children: typeof row.note === 'string' ? row.note : formatNumber(stacked ? total : vals[0], unit) }))] }), _jsxs("div", { style: { position: 'relative', height: 26, borderRadius: 7, background: SUBTLE }, children: [stacked ? (_jsx("div", { style: { display: 'flex', height: '100%', width: '100%', borderRadius: 7, overflow: 'hidden' }, children: series.map((s, si) => (_jsx(motion.div, { initial: false, animate: { width: `${scale(vals[si])}%` }, transition: transition, "data-jbar": `${s.name}:${idx}`, style: { height: '100%', background: si === 0 && row.color ? vizColor(row.color) : s.color } }, s.name))) })) : (_jsx(motion.div, { initial: false, animate: { width: `${scale(vals[0])}%` }, transition: transition, "data-jbar": `${series[0].name}:${idx}`, style: {
88
+ height: '100%',
89
+ borderRadius: 7,
90
+ background: primaryColor,
91
+ } })), locked && (_jsx("div", { style: {
92
+ position: 'absolute',
93
+ left: `${scale(vals[0])}%`,
94
+ top: -5,
95
+ bottom: -5,
96
+ borderLeft: `2px solid ${OK}`,
97
+ } })), refObj && (_jsx("div", { style: {
98
+ position: 'absolute',
99
+ left: `${scale(refObj.value)}%`,
100
+ top: -4,
101
+ bottom: -4,
102
+ borderLeft: `1.5px dashed ${refObj.color ? vizColor(refObj.color) : LINE_STRONG}`,
103
+ } }))] })] }));
104
+ }
105
+ export function BarChartView({ ctx }) {
106
+ const { node, p, animate, anchors, isDimmed } = useVizChart(ctx);
107
+ const { title, subtitle, data: rawData, dataKey, series: rawSeries, orientation, layout, scale: scaleMode, domain: rawDomain, unit: rawUnit, referenceLine, directLabels, withLegend, itemIds: _ids, w, h, ...rest } = p;
108
+ const H = num(h, 280);
109
+ const root = useRoot(node, rest, {
110
+ style: {
111
+ width: dim(w) ?? '100%',
112
+ minWidth: 0,
113
+ fontFamily: VIZ_FONT_SANS,
114
+ color: INK,
115
+ },
116
+ });
117
+ const rows = arr(rawData).filter((r) => !!r && typeof r === 'object');
118
+ const key = str(dataKey);
119
+ const series = arr(rawSeries)
120
+ .filter((s) => !!s && typeof s === 'object' && typeof s.name === 'string')
121
+ .map((s, i) => ({
122
+ name: s.name,
123
+ label: s.label ?? s.name,
124
+ color: vizColor(s.color, i),
125
+ }));
126
+ if (!rows.length || !series.length)
127
+ return _jsx("div", { ...root, role: "status", children: "BarChart \u00B7 no data" });
128
+ const stacked = layout === 'stacked';
129
+ const horizontal = orientation === 'horizontal';
130
+ const unit = str(rawUnit);
131
+ const showDirect = directLabels !== false;
132
+ const showLegend = withLegend === true || (withLegend !== false && series.length > 1 && !horizontal);
133
+ const refObj = referenceLine && typeof referenceLine === 'object' && typeof referenceLine.value === 'number'
134
+ ? referenceLine
135
+ : null;
136
+ const explicitDomain = Array.isArray(rawDomain) &&
137
+ rawDomain.length === 2 &&
138
+ typeof rawDomain[0] === 'number' &&
139
+ typeof rawDomain[1] === 'number' &&
140
+ Number.isFinite(rawDomain[0]) &&
141
+ Number.isFinite(rawDomain[1]) &&
142
+ rawDomain[1] > rawDomain[0]
143
+ ? [rawDomain[0], rawDomain[1]]
144
+ : null;
145
+ const autoPeak = Math.max(1, refObj?.value ?? 0, ...rows.map((r) => {
146
+ const vals = series.map((s) => (typeof r[s.name] === 'number' && Number.isFinite(r[s.name]) ? Math.max(0, r[s.name]) : 0));
147
+ return stacked ? vals.reduce((a, b) => a + b, 0) : Math.max(0, ...vals);
148
+ }));
149
+ const domainMin = explicitDomain ? explicitDomain[0] : 0;
150
+ const peak = explicitDomain ? explicitDomain[1] : autoPeak;
151
+ // Horizontal mode (supports invariant-locked bars + zero-stretch labels)
152
+ if (horizontal) {
153
+ const scale = scaleLinear().domain([domainMin, peak]).range([0, 100]).clamp(true);
154
+ return (_jsxs("figure", { ...root, style: { ...root.style, margin: 0 }, "aria-label": typeof title === 'string' ? title : 'BarChart', children: [_jsx(ChartHeader, { title: typeof title === 'string' ? title : undefined, subtitle: typeof subtitle === 'string' ? subtitle : undefined }), _jsx("div", { style: { display: 'flex', flexDirection: 'column', gap: 18 }, children: rows.map((row, idx) => {
155
+ const label = str(row[key]);
156
+ const id = typeof row.id === 'string' ? row.id : undefined;
157
+ return (_jsx(BarItemHorizontal, { row: row, idx: idx, id: id, label: label, series: series, stacked: stacked, scale: scale, unit: unit, showDirect: showDirect, refObj: refObj, animate: animate, dimmed: isDimmed(id, label), anchors: anchors }, id ?? `${label}_${idx}`));
158
+ }) })] }));
159
+ }
160
+ // Vertical mode (grouped & stacked, linear or log scale, crisp HTML axis & direct labels)
161
+ const plotH = Math.max(140, H - (showLegend ? 72 : 46));
162
+ const rawScale = scaleMode === 'log'
163
+ ? scaleLog().domain([Math.max(1, domainMin), Math.max(10, peak)]).range([14, plotH - 42]).clamp(true)
164
+ : scaleLinear().domain([domainMin, peak]).range([0, plotH - 42]).clamp(true);
165
+ const scaleFn = (v) => (v <= 0 ? 0 : rawScale(scaleMode === 'log' ? Math.max(1, v) : v));
166
+ return (_jsxs("figure", { ...root, style: { ...root.style, margin: 0 }, "aria-label": typeof title === 'string' ? title : 'BarChart', children: [_jsx(ChartHeader, { title: typeof title === 'string' ? title : undefined, subtitle: typeof subtitle === 'string' ? subtitle : undefined }), _jsxs("div", { style: {
167
+ position: 'relative',
168
+ height: plotH,
169
+ display: 'flex',
170
+ alignItems: 'flex-end',
171
+ gap: 16,
172
+ padding: '0 10px',
173
+ borderBottom: `1.5px solid ${LINE_STRONG}`,
174
+ }, children: [[0.33, 0.66, 1].map((frac) => (_jsx("div", { style: {
175
+ position: 'absolute',
176
+ left: 0,
177
+ right: 0,
178
+ bottom: (plotH - 42) * frac,
179
+ borderTop: `1px solid ${LINE}`,
180
+ pointerEvents: 'none',
181
+ } }, frac))), refObj && (_jsx("div", { style: {
182
+ position: 'absolute',
183
+ left: 0,
184
+ right: 0,
185
+ bottom: scaleFn(refObj.value),
186
+ borderTop: `1.5px dashed ${refObj.color ? vizColor(refObj.color) : LINE_STRONG}`,
187
+ pointerEvents: 'none',
188
+ }, children: refObj.label && (_jsx("span", { style: {
189
+ position: 'absolute',
190
+ right: 2,
191
+ top: -18,
192
+ fontSize: 11,
193
+ fontWeight: 800,
194
+ fontFamily: MONO,
195
+ color: refObj.color ? vizColor(refObj.color) : DIMMED,
196
+ }, children: refObj.label })) })), rows.map((row, idx) => {
197
+ const label = str(row[key]);
198
+ const id = typeof row.id === 'string' ? row.id : undefined;
199
+ return (_jsx(BarItemVertical, { row: row, id: id, label: label, series: series, stacked: stacked, scale: scaleFn, plotH: plotH, unit: unit, directLabels: showDirect, animate: animate, dimmed: isDimmed(id, label), anchors: anchors }, id ?? `${label}_${idx}`));
200
+ })] }), _jsx("div", { style: { display: 'flex', gap: 16, padding: '8px 10px 0' }, children: rows.map((row, idx) => {
201
+ const label = str(row[key]);
202
+ return (_jsxs("div", { style: { flex: 1, minWidth: 0, textAlign: 'center', display: 'flex', flexDirection: 'column', gap: 2 }, children: [_jsx("span", { style: { fontSize: 13, fontWeight: 750, color: INK }, children: label }), typeof row.note === 'string' && _jsx("span", { style: { fontSize: 11.5, color: DIMMED }, children: row.note })] }, idx));
203
+ }) }), showLegend && (_jsx("div", { style: { display: 'flex', flexWrap: 'wrap', gap: 14, justifyContent: 'center', marginTop: 12, fontSize: 12, color: DIMMED }, children: series.map((s) => (_jsxs("span", { style: { display: 'inline-flex', alignItems: 'center', gap: 6 }, children: [_jsx("span", { "aria-hidden": true, style: { width: 10, height: 10, borderRadius: 2, background: s.color } }), s.label] }, s.name))) }))] }));
204
+ }
@@ -0,0 +1,4 @@
1
+ import type { ComponentCtx } from '@joplo-app/kit/plugin';
2
+ export declare function DeltaBarView({ ctx }: {
3
+ ctx: ComponentCtx;
4
+ }): import("react").JSX.Element;