@joplo-app/plugin-viz 0.9.0 → 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.
package/dist/catalog.js CHANGED
@@ -12,7 +12,7 @@ export const COMPONENT_TYPES = [
12
12
  ];
13
13
  export const COMPONENT_DOCS = {
14
14
  DeltaBar: 'items: [{ id?, label, sub?, baseline?, value, deltaLabel?, note?, color?, lowerIsBetter? }], variant="ghost"|"paired", domain?, unit?="%", lowerIsBetter?, ticks?, title?, subtitle?. Before-vs-after metric comparison with ghost baseline outline, curtain-uncover retract animation, and direct delta pills. Supports pinBaseline() and focusDatum().',
15
- BarChart: 'data: [{ id?, [dataKey], [series], locked?, lockedLabel?, deltaBadge?, note?, color? }], dataKey, series: [{ name, label?, color? }], orientation="vertical"|"horizontal", layout="grouped"|"stacked", scale="linear"|"log", unit?, referenceLine?, directLabels?=true, withLegend?, h?. Zero-stretch labels and invariant lock pins.',
15
+ BarChart: 'data: [{ id?, [dataKey], [series], locked?, lockedLabel?, deltaBadge?, note?, color? }], dataKey, series: [{ name, label?, color? }], orientation="vertical"|"horizontal", layout="grouped"|"stacked", scale="linear"|"log", domain?=[min, max], unit?, referenceLine?, directLabels?=true, withLegend?, h?. Zero-stretch labels, fixed-domain scaling, and invariant lock pins.',
16
16
  RatioBar: 'total, left, optional right or segments: [{ id?, label?, value, color? }], threshold?, labels?, remainderLabel?, thresholdLabel?, colors?, unit?, height?, showDenominator?=false. Part-of-a-whole ratio and threshold bar; clean single-value formatting by default.',
17
17
  LineChart: 'data: [{ id?, [dataKey], [series] }], dataKey, series: [{ name, label?, color?, area?, dashed? }], unit?, yDomain?, curve="linear"|"monotone", referenceLine?, referenceBand?, revealTo?, directLabels?=true, withLegend?, h?. Crisp SVG paths with zero-stretch HTML labels, progressive revealTo(), and addressable points.',
18
18
  TimeLanes: 'domain: [min, max], spans: [{ id, lane, start, end, label?, shortLabel?, rangeLabel?, status?, color? }], unit?="ms", ticks?, cursor?, cursorLabel?, spanIds?, compact?. Full tick gridlines, animated playhead via setCursor(), focusDatum() lane dimming, and automatic external labels for narrow bars.',
@@ -35,6 +35,8 @@ export type BarChartProps = JoploProps & {
35
35
  orientation?: 'vertical' | 'horizontal';
36
36
  layout?: 'grouped' | 'stacked';
37
37
  scale?: 'linear' | 'log';
38
+ /** Optional explicit numeric axis domain [min, max] so invariant bars stay pixel-identical across states. */
39
+ domain?: readonly [number, number];
38
40
  unit?: string;
39
41
  referenceLine?: {
40
42
  value: number;
package/dist/guide.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  export declare const skill = "# Narrative Data Visualization: viz\n\nUse `@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`.\n\n## Choose the right chart (never abuse RatioBar or hand-roll div bars)\n- **Qualitative UI / prose A-vs-B switching** \u2192 stay in `@joplo-app/plugin-ui` (`<Compare>`).\n- **Before \u2192 After metric gain / reduction** (e.g., CPU \u221270%, Memory \u221280%, latency drop) \u2192 **`<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.\n- **Category magnitude, stacked composition, or invariant locking** \u2192 **`<BarChart>`** (`orientation=\"vertical\"|\"horizontal\"`, `layout=\"grouped\"|\"stacked\"`, row `locked: true` pins an invariant bar while other bars scale).\n- **Part-of-a-whole split or pass threshold** (e.g., 98% test pass vs 25% prod match against a 99% bar) \u2192 **`<RatioBar>`** (clean single-value display by default; set `showDenominator` only when explicit `x / total` is needed).\n- **Trend over time / scaling curve / cliff inflection** \u2192 **`<LineChart>`** (zero-stretch HTML labels + crisp SVG curve + `revealTo()` progressive draw + `referenceLine` / `referenceBand`).\n- **Time intervals / Gantt / concurrent waterfall** \u2192 **`<TimeLanes>`** (full tick gridlines, animated `setCursor()` playhead, `focusDatum()` lane dimming, and automatic external labels so narrow bars never clip text).\n- **2D trade-off / cost-vs-accuracy Pareto frontier** \u2192 **`<ScatterPlot pareto=\"top-left\">`** (auto-computes and strokes the Pareto frontier polyline, optional quadrant tint).\n- **2D matrix density / attention weights / confusion matrix** \u2192 **`<Heatmap>`** (high-contrast auto-white text on dark cells, row/col/cell `focusDatum()`).\n- **Proportional multi-stage flow / funnel conservation** \u2192 **`<Sankey>`** (`d3-sankey` curved cubic-Bezier ribbons tapering from wide to narrow, single-path `focusDatum()`).\n- **Step-by-step positive/negative attribution** (how 100% dropped to 30%) \u2192 **`<Waterfall>`** (cumulative floating steps + dashed stair connectors + `revealTo()`).\n- **Multi-dimension profile comparison** (4\u20137 axes) \u2192 **`<Radar>`** (polygonal spiderweb rings + translucent series overlays + direct axis/delta scores).\n\n## Narrative step effects (deterministic compile-time snapshots)\nImport `focusDatum`, `revealTo`, `pinBaseline`, and `setCursor` from `@joplo-app/plugin-viz`:\n- `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.\n- `revealTo(chartId, cutoff | null)`: reveal a `LineChart` up to an X label or index, or a `Waterfall` up to a step id or index.\n- `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.)\n- `setCursor(chartId, value | null, { label? })`: slide a vertical playhead across `TimeLanes` or `LineChart`.\n\n## Addressable anchors & silent observation windows\n- 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.\n- 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.\n\n## Verify & pitfalls\n- Run `npx joplo check`: fix `VIZ_DATA_INVALID`, `VIZ_CHART_UNKNOWN`, `RATIO_BAR_INVALID`, or `TIME_LANES_INVALID` before rendering.\n- Never wrap charts inside redundant bordered cards with duplicate titles when `title` / `subtitle` props already live on the chart.\n- 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.\n- Read `npx joplo skill viz/components` for full prop tables and `npx joplo skill viz/recipes` for animation and framing patterns.\n\nRelated topics: components, authoring, focus, check, plugins\n";
2
- export declare const recipes = "# Narrative DataViz recipes and pitfalls\n\n## 1. Before-vs-after payoff without spoiling the reveal (DeltaBar)\nStart 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:\n```tsx\n<DeltaBar\n id=\"payoff\"\n title=\"\u5355\u8BF7\u6C42\u5B9E\u6D4B\u8D44\u6E90\u4E0E\u5EF6\u8FDF\"\n unit=\"%\"\n lowerIsBetter\n items={[\n { id: 'delta_cpu', label: '\u5355\u8BF7\u6C42 CPU', baseline: 100, value: $.ui.cpuRust, deltaLabel: '\u221270%' },\n { id: 'delta_mem', label: '\u5355\u8BF7\u6C42\u5185\u5B58', baseline: 100, value: $.ui.memRust, deltaLabel: '\u221280%+' },\n { id: 'delta_ttft', label: '\u4E2D\u4F4D TTFT', baseline: 100, value: $.ui.ttftRust, deltaLabel: '\u221220%' },\n ]}\n/>\n```\nIn the flow:\n1. Show Python baseline (`cpuRust: 100, memRust: 100, ttftRust: 100`) \u2014 clean solid bars, zero premature savings text.\n2. Drop values (`cpuRust: 30, memRust: 20, ttftRust: 80`) with `narrate(false)` + `hold(2.2)` \u2014 bars retract smoothly with row stagger, uncovering the dashed ghost baseline and emerald savings band.\n3. Add `focusDatum('payoff', 'delta_mem')` + `callout('delta_mem', '\u5185\u5B58\u76F4\u964D\u516B\u6210+')` to spotlight one metric.\n\n## 2. Invariant-locked comparison (BarChart)\nMark constant rows with `locked: true` (`lockedLabel: 'LOCKED \u00B7 \u4E0D\u53D8\u91CF'`). When toggling a knob (like loop depth 1\u00D7 \u2192 2\u00D7 \u2192 4\u00D7), viewers immediately see which bar stays frozen while other bars grow.\n\n## 3. Progressive trend & inflection callout (LineChart)\nUse `revealTo('trend', '5 \u6708')` to hold suspense on an early plateau, then `revealTo('trend', '9 \u6708')` in a silent observation step, followed by `callout('pt_june', '6 \u6708\u89C4\u5219\u6C89\u6DC0 \u2192 \u65AD\u5D16\u6536\u655B')` anchored directly on the point id.\n\n## 4. Narrow bars in TimeLanes\nIf a span occupies less than ~24% of `domain`, pass `shortLabel` (e.g., `shortLabel: '\u96F6\u505C\u670D\u5207\u6D41'`, `label: '\u516C\u5F00\u6D41\u91CF\u5206\u6279\u5207\u5165 Rust'`). `TimeLanes` centers `shortLabel` inside the bar and floats the full `label` into the adjacent open track so text is never truncated.\n\n## 5. Single-path storytelling in Sankey & Heatmap\n- `Sankey`: use `focusDatum('flow', ['diff', 'gate'])` to dim quiet baseline traffic while illuminating the anomalous cascade.\n- `Heatmap`: pass `cellAnchors={{ '4:2': 'cell_rust_code' }}` and use `focusDatum('attn', 'row:Rust')` + `callout('cell_rust_code', '\u6700\u9AD8\u6743\u91CD 0.46')` to walk viewers through one row at a time.\n";
2
+ export declare const recipes = "# Narrative DataViz recipes and pitfalls\n\n## 1. Before-vs-after payoff without spoiling the reveal (DeltaBar)\nStart 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:\n```tsx\n<DeltaBar\n id=\"payoff\"\n title=\"\u5355\u8BF7\u6C42\u5B9E\u6D4B\u8D44\u6E90\u4E0E\u5EF6\u8FDF\"\n unit=\"%\"\n lowerIsBetter\n items={[\n { id: 'delta_cpu', label: '\u5355\u8BF7\u6C42 CPU', baseline: 100, value: $.ui.cpuRust, deltaLabel: '\u221270%' },\n { id: 'delta_mem', label: '\u5355\u8BF7\u6C42\u5185\u5B58', baseline: 100, value: $.ui.memRust, deltaLabel: '\u221280%+' },\n { id: 'delta_ttft', label: '\u4E2D\u4F4D TTFT', baseline: 100, value: $.ui.ttftRust, deltaLabel: '\u221220%' },\n ]}\n/>\n```\nIn the flow:\n1. Show Python baseline (`cpuRust: 100, memRust: 100, ttftRust: 100`) \u2014 clean solid bars, zero premature savings text.\n2. Drop values (`cpuRust: 30, memRust: 20, ttftRust: 80`) with `narrate(false)` + `hold(2.2)` \u2014 bars retract smoothly with row stagger, uncovering the dashed ghost baseline and emerald savings band.\n3. Add `focusDatum('payoff', 'delta_mem')` + `callout('delta_mem', '\u5185\u5B58\u76F4\u964D\u516B\u6210+')` to spotlight one metric.\n\n## 2. Invariant-locked comparison (BarChart)\nMark constant rows with `locked: true` (`lockedLabel: 'LOCKED \u00B7 \u4E0D\u53D8\u91CF'`) 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\u00D7` bar shrinking from 100% \u2192 50% \u2192 33% as another bar grows 1 \u2192 2 \u2192 3).\n\n## 3. Progressive trend & inflection callout (LineChart)\nUse `revealTo('trend', '5 \u6708')` to hold suspense on an early plateau, then `revealTo('trend', '9 \u6708')` in a silent observation step, followed by `callout('pt_june', '6 \u6708\u89C4\u5219\u6C89\u6DC0 \u2192 \u65AD\u5D16\u6536\u655B')` anchored directly on the point id.\n\n## 4. Narrow bars in TimeLanes\nIf a span occupies less than ~24% of `domain`, pass `shortLabel` (e.g., `shortLabel: '\u96F6\u505C\u670D\u5207\u6D41'`, `label: '\u516C\u5F00\u6D41\u91CF\u5206\u6279\u5207\u5165 Rust'`). `TimeLanes` centers `shortLabel` inside the bar and floats the full `label` into the adjacent open track so text is never truncated.\n\n## 5. Single-path storytelling in Sankey & Heatmap\n- `Sankey`: use `focusDatum('flow', ['diff', 'gate'])` to dim quiet baseline traffic while illuminating the anomalous cascade.\n- `Heatmap`: pass `cellAnchors={{ '4:2': 'cell_rust_code' }}` and use `focusDatum('attn', 'row:Rust')` + `callout('cell_rust_code', '\u6700\u9AD8\u6743\u91CD 0.46')` to walk viewers through one row at a time.\n";
3
3
  export declare function componentGuide(): string;
package/dist/guide.js CHANGED
@@ -58,7 +58,7 @@ In the flow:
58
58
  3. Add \`focusDatum('payoff', 'delta_mem')\` + \`callout('delta_mem', '内存直降八成+')\` to spotlight one metric.
59
59
 
60
60
  ## 2. Invariant-locked comparison (BarChart)
61
- Mark constant rows with \`locked: true\` (\`lockedLabel: 'LOCKED · 不变量'\`). When toggling a knob (like loop depth 1× → 2× → 4×), viewers immediately see which bar stays frozen while other bars grow.
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
62
 
63
63
  ## 3. Progressive trend & inflection callout (LineChart)
64
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.
@@ -104,7 +104,7 @@ function BarItemHorizontal({ row, idx, id, label, series, stacked, scale, unit,
104
104
  }
105
105
  export function BarChartView({ ctx }) {
106
106
  const { node, p, animate, anchors, isDimmed } = useVizChart(ctx);
107
- const { title, subtitle, data: rawData, dataKey, series: rawSeries, orientation, layout, scale: scaleMode, unit: rawUnit, referenceLine, directLabels, withLegend, itemIds: _ids, w, h, ...rest } = p;
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
108
  const H = num(h, 280);
109
109
  const root = useRoot(node, rest, {
110
110
  style: {
@@ -133,13 +133,24 @@ export function BarChartView({ ctx }) {
133
133
  const refObj = referenceLine && typeof referenceLine === 'object' && typeof referenceLine.value === 'number'
134
134
  ? referenceLine
135
135
  : null;
136
- const peak = Math.max(1, refObj?.value ?? 0, ...rows.map((r) => {
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) => {
137
146
  const vals = series.map((s) => (typeof r[s.name] === 'number' && Number.isFinite(r[s.name]) ? Math.max(0, r[s.name]) : 0));
138
147
  return stacked ? vals.reduce((a, b) => a + b, 0) : Math.max(0, ...vals);
139
148
  }));
149
+ const domainMin = explicitDomain ? explicitDomain[0] : 0;
150
+ const peak = explicitDomain ? explicitDomain[1] : autoPeak;
140
151
  // Horizontal mode (supports invariant-locked bars + zero-stretch labels)
141
152
  if (horizontal) {
142
- const scale = scaleLinear().domain([0, peak]).range([0, 100]).clamp(true);
153
+ const scale = scaleLinear().domain([domainMin, peak]).range([0, 100]).clamp(true);
143
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) => {
144
155
  const label = str(row[key]);
145
156
  const id = typeof row.id === 'string' ? row.id : undefined;
@@ -149,8 +160,8 @@ export function BarChartView({ ctx }) {
149
160
  // Vertical mode (grouped & stacked, linear or log scale, crisp HTML axis & direct labels)
150
161
  const plotH = Math.max(140, H - (showLegend ? 72 : 46));
151
162
  const rawScale = scaleMode === 'log'
152
- ? scaleLog().domain([1, Math.max(10, peak)]).range([14, plotH - 42]).clamp(true)
153
- : scaleLinear().domain([0, peak]).range([0, plotH - 42]).clamp(true);
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);
154
165
  const scaleFn = (v) => (v <= 0 ? 0 : rawScale(scaleMode === 'log' ? Math.max(1, v) : v));
155
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: {
156
167
  position: 'relative',
package/dist/version.json CHANGED
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": "0.9.0"
2
+ "version": "0.10.0"
3
3
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joplo-app/plugin-viz",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "type": "module",
5
5
  "joplo": {
6
6
  "api": 2
@@ -33,7 +33,7 @@
33
33
  "./package.json": "./package.json"
34
34
  },
35
35
  "dependencies": {
36
- "@joplo-app/kit": "0.9.0",
36
+ "@joplo-app/kit": "0.10.0",
37
37
  "d3-array": "^3.2.4",
38
38
  "d3-sankey": "^0.12.3",
39
39
  "d3-scale": "^4.0.2",