@ruckc/truss-chart 1.18.3 → 1.20.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.
@@ -3,7 +3,7 @@
3
3
  import Tooltip from './Tooltip.svelte';
4
4
  import { watchFill } from './fill.js';
5
5
  import type { Series, Band, ReferenceLine } from './types.js';
6
- import { fmtAxis, fmtValue, fmtX, isPos, linear, logLinear, logTicks, niceTicks, seriesColor, str, spreadLabels, MAX_SERIES } from './util.js';
6
+ import { fmtAxis, fmtValue, fmtX, isPos, linear, logLinear, logTicks, niceTicks, seriesColor, str, spreadLabels, labelGap, labelsFit, isDisplaced, estimateLabelWidth, MAX_SERIES } from './util.js';
7
7
 
8
8
  let {
9
9
  x,
@@ -14,7 +14,7 @@
14
14
  area = false,
15
15
  stacked = false,
16
16
  zeroBaseline = false,
17
- directLabels = true,
17
+ directLabels = 'auto',
18
18
  yFormat = fmtValue,
19
19
  xFormat,
20
20
  band,
@@ -39,8 +39,14 @@
39
39
  stacked?: boolean | 'percent';
40
40
  /** Ensures 0 is inside the y-domain. It does not draw a line at 0: add `referenceLines={[{ value: 0 }]}` for that. */
41
41
  zeroBaseline?: boolean;
42
- /** Name labels at line ends when ≤ 4 series. */
43
- directLabels?: boolean;
42
+ /**
43
+ * Name labels at the line ends (2 to 4 series; never for 1 or more than 4). `'auto'` (default) spaces the labels
44
+ * by their rendered line height, reserves a right margin as wide as the widest label, draws a leader line for
45
+ * any label moved away from its line end, and falls back to the legend alone when the labels cannot fit the
46
+ * plot height or would take too much of the width. `true` always draws them (no fallback). `false` is
47
+ * legend-only. The label text uses a text token; a series-colour marker links it to its line.
48
+ */
49
+ directLabels?: boolean | 'auto';
44
50
  yFormat?: (n: number) => string;
45
51
  /** Formats x values (a Date when `x` holds Dates) for axis ticks, tooltip and table. Default: number or date-aware short format. */
46
52
  xFormat?: (x: number | Date) => string;
@@ -122,7 +128,25 @@
122
128
  const tipName = (name: string, i: number, k: number) => `${name}${percent && vis[k].values[i] != null ? ` · ${fmtValue(share(i, k))}%` : ''}`;
123
129
  const cellText = (s: (typeof all)[number], i: number) =>
124
130
  `${s.values[i] == null ? '—' : str(yFormat(s.values[i]!))}${percent && s.values[i] != null && !hidden.includes(s.name) ? ` (${fmtValue(share(i, vis.indexOf(s)))}%)` : ''}`;
125
- const labelled = $derived(directLabels && all.length > 1 && all.length <= 4);
131
+ /** Direct labels are possible: not switched off, and 2 to 4 series. */
132
+ const cand = $derived(directLabels !== false && all.length > 1 && all.length <= 4);
133
+ let svgEl = $state<SVGSVGElement>();
134
+ /** Rendered label metrics; null until measured (server render, first client paint), when estimates stand in. */
135
+ let meas = $state<{ lh: number; w: Record<string, number> } | null>(null);
136
+ $effect(() => {
137
+ if (!cand || !svgEl) return;
138
+ const el = svgEl, names = all.map((s) => s.name);
139
+ let live = true;
140
+ const measure = () => {
141
+ if (!live) return;
142
+ const probes = [...el.querySelectorAll<SVGTextElement>('text.dprobe')];
143
+ const cs = getComputedStyle(probes[0]);
144
+ meas = { lh: parseFloat(cs.lineHeight) || parseFloat(cs.fontSize) * 1.4, w: Object.fromEntries(names.map((n, i) => [n, probes[i].getComputedTextLength()])) };
145
+ };
146
+ measure();
147
+ document.fonts.ready.then(measure);
148
+ return () => (live = false);
149
+ });
126
150
  const items = $derived(all.map((s) => ({ name: s.name, color: s.color, hidden: hidden.includes(s.name) })));
127
151
  const toggle = (n: string) => (hidden = hidden.includes(n) ? hidden.filter((h) => h !== n) : [...hidden, n]);
128
152
 
@@ -152,16 +176,23 @@
152
176
  <ChartFrame {title} {subtitle} {items} ontoggle={toggle}>
153
177
  {#snippet plot(w)}
154
178
  {@const height = H}
155
- {@const m = { top: 12, right: labelled ? 92 : 14, bottom: 26, left: 46 }}
179
+ {@const Y = (yLog ? logLinear : linear)(yDom.min, yDom.max, height - 26, 12)}
180
+ {@const ends = vis.map((s, si) => { const k = s.values.findLastIndex((v) => v != null); return k < 0 ? null : { s, xi: k, y: Y(bands[si][k]!.hi) }; }).filter((e) => !!e)}
181
+ {@const lh = meas?.lh ?? 20}
182
+ {@const gap = labelGap(lh)}
183
+ {@const labelLo = 12 + lh / 2}
184
+ {@const labelHi = height - 26 - lh / 2}
185
+ {@const widest = Math.max(0, ...ends.map((e) => meas?.w[e.s.name] ?? estimateLabelWidth(e.s.name)))}
186
+ {@const gutter = 24 + Math.ceil(widest) + 6}
187
+ {@const show = cand && (directLabels === true || (labelsFit(ends.length, gap, labelLo, labelHi) && gutter <= w * 0.4))}
188
+ {@const m = { top: 12, right: show ? gutter : 14, bottom: 26, left: 46 }}
156
189
  {@const X = (xLog ? logLinear : linear)(Math.min(...xs), Math.max(...xs), m.left, w - m.right)}
157
- {@const Y = (yLog ? logLinear : linear)(yDom.min, yDom.max, height - m.bottom, m.top)}
158
190
  {@const xTicks = xLog ? logTicks(Math.min(...xs), Math.max(...xs)).ticks.filter((t) => t >= Math.min(...xs) && t <= Math.max(...xs)) : xs.length <= 8 ? xs : niceTicks(Math.min(...xs), Math.max(...xs), Math.max(2, Math.floor(w / 100))).ticks.filter((t) => t >= Math.min(...xs) && t <= Math.max(...xs))}
159
- {@const ends = vis.map((s, si) => { const k = s.values.findLastIndex((v) => v != null); return k < 0 ? null : { s, y: Y(bands[si][k]!.hi) }; }).filter((e) => !!e)}
160
- {@const labelY = spreadLabels(ends.map((e) => e.y), 14, m.top + 4, height - m.bottom)}
191
+ {@const labelY = spreadLabels(ends.map((e) => e.y), gap, labelLo, labelHi)}
161
192
 
162
193
  <!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions -->
163
194
  <svg
164
- width={w} {height} role="group" tabindex="0"
195
+ bind:this={svgEl} width={w} {height} role="group" tabindex="0"
165
196
  aria-label="{title ?? 'Line chart'}. Use left and right arrow keys to read values.{refsText && ` Reference lines: ${refsText}.`}"
166
197
  onpointermove={(e) => {
167
198
  const px = e.clientX - e.currentTarget.getBoundingClientRect().left;
@@ -208,9 +239,18 @@
208
239
  {#if r.label}<text class="reflabel" x={m.left + 4} y={Y(r.value) - 4}>{r.label}</text>{/if}
209
240
  {/each}
210
241
 
211
- {#each ends as e, k}
212
- {#if labelled}<text class="direct" x={w - m.right + 8} y={labelY[k]} dominant-baseline="middle">{e.s.name}</text>{/if}
213
- {/each}
242
+ {#if cand}
243
+ <g class="probes" visibility="hidden" aria-hidden="true">{#each all as s}<text class="dprobe" x="0" y="0">{s.name}</text>{/each}</g>
244
+ {/if}
245
+ {#if show}
246
+ {#each ends as e, k}
247
+ {#if isDisplaced(e.y, labelY[k], lh / 3)}
248
+ <line class="leader" stroke={e.s.color} x1={X(xs[e.xi]) + 2} y1={e.y} x2={w - m.right + 12} y2={labelY[k]} />
249
+ {/if}
250
+ <circle class="dkey" fill={e.s.color} cx={w - m.right + 16} cy={labelY[k]} r="3.5" />
251
+ <text class="direct" x={w - m.right + 24} y={labelY[k]} dominant-baseline="middle">{e.s.name}</text>
252
+ {/each}
253
+ {/if}
214
254
 
215
255
  {#if hover != null}
216
256
  <line class="cross" x1={X(xs[hover])} x2={X(xs[hover])} y1={m.top} y2={height - m.bottom} />
@@ -270,7 +310,8 @@
270
310
  .reflabel { fill: var(--tr-on-surface); font-size: var(--tr-text-xs); font-weight: 600; }
271
311
  .band-key { width: 12px; height: 8px; border-radius: 2px; flex: none; opacity: 0.4; }
272
312
  .fillwrap { height: 100%; min-height: 0; overflow: hidden; }
273
- .direct { fill: var(--tr-on-surface-variant); font-size: var(--tr-text-sm); font-weight: 600; }
313
+ .leader { stroke-width: 1; stroke-opacity: 0.7; }
314
+ .direct, .dprobe { fill: var(--tr-on-surface-variant); font-size: var(--tr-text-sm); font-weight: 600; }
274
315
  .cross { stroke: var(--tr-outline); stroke-width: 1; stroke-dasharray: 3 3; }
275
316
  .dot { stroke: var(--tr-surface-container-low); stroke-width: 2; }
276
317
  .head { color: var(--tr-on-surface-variant); margin-bottom: 4px; }
@@ -17,8 +17,14 @@ type $$ComponentProps = {
17
17
  stacked?: boolean | 'percent';
18
18
  /** Ensures 0 is inside the y-domain. It does not draw a line at 0: add `referenceLines={[{ value: 0 }]}` for that. */
19
19
  zeroBaseline?: boolean;
20
- /** Name labels at line ends when ≤ 4 series. */
21
- directLabels?: boolean;
20
+ /**
21
+ * Name labels at the line ends (2 to 4 series; never for 1 or more than 4). `'auto'` (default) spaces the labels
22
+ * by their rendered line height, reserves a right margin as wide as the widest label, draws a leader line for
23
+ * any label moved away from its line end, and falls back to the legend alone when the labels cannot fit the
24
+ * plot height or would take too much of the width. `true` always draws them (no fallback). `false` is
25
+ * legend-only. The label text uses a text token; a series-colour marker links it to its line.
26
+ */
27
+ directLabels?: boolean | 'auto';
22
28
  yFormat?: (n: number) => string;
23
29
  /** Formats x values (a Date when `x` holds Dates) for axis ticks, tooltip and table. Default: number or date-aware short format. */
24
30
  xFormat?: (x: number | Date) => string;
package/dist/util.d.ts CHANGED
@@ -25,7 +25,18 @@ export declare const str: (v: unknown) => string;
25
25
  export declare const fmtAxis: (n: number) => string;
26
26
  export declare const fmtValue: (n: number) => string;
27
27
  export declare function fmtX(v: number, span: number, isDate: boolean): string;
28
- /** Spread label y-positions so they are at least `gap` apart, preserving order. */
28
+ /**
29
+ * Spread label y-positions so they are at least `gap` apart, preserving order, inside `[lo, hi]`.
30
+ * When `n` labels cannot fit (see `labelsFit`) the result overflows `hi`; callers should check first.
31
+ */
29
32
  export declare function spreadLabels(ys: number[], gap: number, lo: number, hi: number): number[];
33
+ /** Minimum centre-to-centre spacing for direct labels: the rendered line height plus a little padding. */
34
+ export declare const labelGap: (lineHeight: number, pad?: number) => number;
35
+ /** True when `n` labels spaced `gap` apart fit between `lo` and `hi`. */
36
+ export declare const labelsFit: (n: number, gap: number, lo: number, hi: number) => boolean;
37
+ /** True when a label moved from `y` to `placed` is far enough from its line end to need a leader line. */
38
+ export declare const isDisplaced: (y: number, placed: number, threshold: number) => boolean;
39
+ /** Rough label width (px) for server rendering and the first client paint, before the text can be measured. */
40
+ export declare const estimateLabelWidth: (name: string, fontPx?: number) => number;
30
41
  /** Bar with a rounded data-end, square against the baseline. `y0` is the baseline, `y1` the data end. */
31
42
  export declare function barPath(x: number, y0: number, y1: number, w: number, r: number, round?: boolean): string;
package/dist/util.js CHANGED
@@ -59,7 +59,10 @@ export function fmtX(v, span, isDate) {
59
59
  return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
60
60
  return d.toLocaleDateString('en-US', { month: 'short', year: 'numeric' });
61
61
  }
62
- /** Spread label y-positions so they are at least `gap` apart, preserving order. */
62
+ /**
63
+ * Spread label y-positions so they are at least `gap` apart, preserving order, inside `[lo, hi]`.
64
+ * When `n` labels cannot fit (see `labelsFit`) the result overflows `hi`; callers should check first.
65
+ */
63
66
  export function spreadLabels(ys, gap, lo, hi) {
64
67
  const idx = ys.map((_, i) => i).sort((a, b) => ys[a] - ys[b]);
65
68
  const out = [...ys];
@@ -73,6 +76,14 @@ export function spreadLabels(ys, gap, lo, hi) {
73
76
  }
74
77
  return out;
75
78
  }
79
+ /** Minimum centre-to-centre spacing for direct labels: the rendered line height plus a little padding. */
80
+ export const labelGap = (lineHeight, pad = 2) => lineHeight + pad;
81
+ /** True when `n` labels spaced `gap` apart fit between `lo` and `hi`. */
82
+ export const labelsFit = (n, gap, lo, hi) => (n - 1) * gap <= hi - lo;
83
+ /** True when a label moved from `y` to `placed` is far enough from its line end to need a leader line. */
84
+ export const isDisplaced = (y, placed, threshold) => Math.abs(placed - y) > threshold;
85
+ /** Rough label width (px) for server rendering and the first client paint, before the text can be measured. */
86
+ export const estimateLabelWidth = (name, fontPx = 14) => Math.ceil(name.length * fontPx * 0.56);
76
87
  /** Bar with a rounded data-end, square against the baseline. `y0` is the baseline, `y1` the data end. */
77
88
  export function barPath(x, y0, y1, w, r, round = true) {
78
89
  const top = Math.min(y0, y1), h = Math.abs(y1 - y0);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ruckc/truss-chart",
3
- "version": "1.18.3",
3
+ "version": "1.20.0",
4
4
  "description": "Zero-dependency SVG charts for Truss UI",
5
5
  "type": "module",
6
6
  "license": "MIT",