@juspay/svelte-ui-components 2.59.0 → 2.61.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.
@@ -6,7 +6,7 @@
6
6
  import { arcPath } from '../_chart/paths';
7
7
  import { computePieLayout } from '../_chart/geometry';
8
8
  import { getColor } from '../_chart/colors';
9
- import { formatNumber, formatPercent } from '../_chart/format';
9
+ import { formatNumber } from '../_chart/format';
10
10
  import type { LegendItem } from '../_chart/types';
11
11
 
12
12
  // ── Props ──────────────────────────────────────────────────────
@@ -20,7 +20,7 @@
20
20
  labelPosition = 'outside',
21
21
  showLegend = false,
22
22
  startAngle = -Math.PI / 2,
23
- aspectRatio = 1,
23
+ aspectRatio,
24
24
  valueFormat,
25
25
  tooltipSnippet,
26
26
  center,
@@ -28,7 +28,10 @@
28
28
  onsliceclick,
29
29
  onslicehover,
30
30
  testId,
31
- classes
31
+ classes,
32
+ semiCircle = false,
33
+ legendShowValues = false,
34
+ percentDecimals = 0
32
35
  }: PieChartProperties = $props();
33
36
 
34
37
  // ── State ──────────────────────────────────────────────────────
@@ -40,32 +43,93 @@
40
43
  let mouseX = $state(0);
41
44
  let mouseY = $state(0);
42
45
 
46
+ // Aspect ratio read from --piechart-semi-aspect-ratio CSS variable.
47
+ // Uses $effect so it re-reads whenever containerEl binds or semiCircle changes
48
+ // (e.g. media-query theme switch), not just on initial mount.
49
+ let semiAspectRatioCssVar = $state(2);
50
+
51
+ // eslint-disable-next-line no-restricted-syntax
52
+ $effect(() => {
53
+ // Track semiCircle and containerEl so the effect re-runs when either changes.
54
+ void semiCircle;
55
+ void containerEl;
56
+ if (typeof window === 'undefined' || containerEl === null) {
57
+ return;
58
+ }
59
+ const rawValue = getComputedStyle(containerEl)
60
+ .getPropertyValue('--piechart-semi-aspect-ratio')
61
+ .trim();
62
+ const parsed = parseFloat(rawValue);
63
+ if (!Number.isNaN(parsed) && parsed > 0) {
64
+ semiAspectRatioCssVar = parsed;
65
+ }
66
+ });
67
+
43
68
  // ── Layout ─────────────────────────────────────────────────────
44
69
 
45
70
  let format = $derived(valueFormat ?? formatNumber);
46
71
  let total = $derived(data.reduce((sum, d) => sum + Math.max(0, d.value), 0));
72
+ let pctFormat = $derived.by(
73
+ () =>
74
+ (v: number): string =>
75
+ total === 0 ? '0%' : ((v / total) * 100).toFixed(percentDecimals) + '%'
76
+ );
47
77
  let isEmpty = $derived(data.length === 0 || total === 0);
48
78
 
79
+ // When semiCircle is true the effective aspect ratio is driven by:
80
+ // 1. The explicit `aspectRatio` prop (highest priority — always wins).
81
+ // 2. The `--piechart-semi-aspect-ratio` CSS variable (consumer CSS override).
82
+ // 3. The hardcoded default of 2 (width:height = 2:1).
83
+ // For a full circle the caller-provided `aspectRatio` or a square (1:1) default is used.
84
+ let effectiveAspectRatio = $derived(aspectRatio ?? (semiCircle ? semiAspectRatioCssVar : 1));
85
+
49
86
  let cx = $derived(chartWidth / 2);
50
- let cy = $derived(chartHeight / 2);
87
+ // For a half-donut the SVG origin sits at the bottom of the drawing area so
88
+ // arcs radiate upward into the top half of the viewBox.
89
+ let cy = $derived(semiCircle ? chartHeight : chartHeight / 2);
51
90
  let outerR = $derived(
52
- Math.max(10, Math.min(cx, cy) - (showLabels && labelPosition === 'outside' ? 40 : 10))
91
+ semiCircle
92
+ ? Math.max(10, chartWidth / 2 - (showLabels && labelPosition === 'outside' ? 40 : 10))
93
+ : Math.max(10, Math.min(cx, cy) - (showLabels && labelPosition === 'outside' ? 40 : 10))
53
94
  );
54
95
  let innerR = $derived(innerRadius > 0 ? outerR * Math.min(0.95, innerRadius) : 0);
55
96
 
56
- let slices = $derived(
57
- computePieLayout(data, startAngle, padAngle).map((s) => {
97
+ let slices = $derived.by(() => {
98
+ // For a full circle layout start at the caller-provided startAngle.
99
+ // For semi-circle: compute a full-circle layout anchored at -PI/2, then
100
+ // remap each angle so the entire sweep is compressed into PI radians
101
+ // (the top-half arc from -PI/2 to PI/2).
102
+ const layoutStartAngle = semiCircle ? -Math.PI / 2 : startAngle;
103
+ const rawSlices = computePieLayout(data, layoutStartAngle, padAngle);
104
+
105
+ return rawSlices.map((s) => {
106
+ let mappedStart = s.startAngle;
107
+ let mappedEnd = s.endAngle;
108
+ let mappedMid = s.midAngle;
109
+
110
+ if (semiCircle) {
111
+ // The raw layout spans [-PI/2, -PI/2 + 2*PI]. We compress it to
112
+ // [-PI/2, PI/2] by halving the angular distance from -PI/2.
113
+ const origin = -Math.PI / 2;
114
+ mappedStart = origin + (s.startAngle - origin) / 2;
115
+ mappedEnd = origin + (s.endAngle - origin) / 2;
116
+ mappedMid = origin + (s.midAngle - origin) / 2;
117
+ }
118
+
58
119
  const color = s.color ?? data[s.index]?.color ?? getColor(s.index);
59
120
  const labelR = labelPosition === 'outside' ? outerR + 16 : (innerR + outerR) / 2;
60
121
  return {
61
122
  ...s,
123
+ startAngle: mappedStart,
124
+ endAngle: mappedEnd,
125
+ midAngle: mappedMid,
62
126
  color,
63
- path: arcPath(0, 0, innerR, outerR, s.startAngle, s.endAngle),
64
- labelX: labelR * Math.cos(s.midAngle),
65
- labelY: labelR * Math.sin(s.midAngle)
127
+ path: arcPath(0, 0, innerR, outerR, mappedStart, mappedEnd),
128
+ labelX: labelR * Math.cos(mappedMid),
129
+ labelY: labelR * Math.sin(mappedMid)
66
130
  };
67
- })
68
- );
131
+ });
132
+ });
69
133
 
70
134
  let legendItems = $derived<LegendItem[]>(
71
135
  data.map((d, i) => ({ label: d.label, color: d.color ?? getColor(i) }))
@@ -73,6 +137,13 @@
73
137
 
74
138
  let centerBoxSize = $derived(innerR > 0 ? Math.max(0, innerR * 1.3) : 0);
75
139
 
140
+ // The foreignObject for the center snippet is positioned relative to the <g>
141
+ // origin (which is at cx, cy in SVG space). The box is always centred on
142
+ // the translated origin: for a full circle that is the geometric centre, and
143
+ // for a semiCircle the <g> origin sits at the chord line (bottom of the arc),
144
+ // so the snippet is centred on the chord as specified.
145
+ let centerFOY = $derived(-centerBoxSize / 2);
146
+
76
147
  // ── Tooltip ────────────────────────────────────────────────────
77
148
 
78
149
  let tooltipData = $derived.by(() => {
@@ -85,7 +156,7 @@
85
156
  items: [
86
157
  {
87
158
  label: s.label,
88
- value: `${format(s.value)} (${formatPercent(s.value, total)})`,
159
+ value: `${format(s.value)} (${pctFormat(s.value)})`,
89
160
  color: s.color
90
161
  }
91
162
  ]
@@ -123,11 +194,15 @@
123
194
  {#if isEmpty && typeof empty === 'function'}
124
195
  <div class="chart-empty">{@render empty()}</div>
125
196
  {:else}
126
- {#if showLegend}
197
+ {#if showLegend && !legendShowValues}
127
198
  <Legend items={legendItems} position="top" />
128
199
  {/if}
129
200
 
130
- <ChartContainer bind:width={chartWidth} bind:height={chartHeight} {aspectRatio}>
201
+ <ChartContainer
202
+ bind:width={chartWidth}
203
+ bind:height={chartHeight}
204
+ aspectRatio={effectiveAspectRatio}
205
+ >
131
206
  <g transform="translate({cx}, {cy})">
132
207
  {#each slices as slice (slice.index)}
133
208
  <!-- svelte-ignore a11y_no_static_element_interactions -->
@@ -155,7 +230,7 @@
155
230
  >
156
231
  {#if showLabels}{slice.label}{/if}
157
232
  {#if showValues}
158
- {formatPercent(slice.value, total)}{/if}
233
+ {pctFormat(slice.value)}{/if}
159
234
  </text>
160
235
  {/if}
161
236
  {/each}
@@ -163,7 +238,7 @@
163
238
  {#if innerR > 0 && typeof center === 'function' && centerBoxSize > 0}
164
239
  <foreignObject
165
240
  x={-centerBoxSize / 2}
166
- y={-centerBoxSize / 2}
241
+ y={centerFOY}
167
242
  width={centerBoxSize}
168
243
  height={centerBoxSize}
169
244
  >
@@ -175,6 +250,20 @@
175
250
  </g>
176
251
  </ChartContainer>
177
252
 
253
+ {#if showLegend && legendShowValues}
254
+ <ul class="pie-legend-values">
255
+ {#each data as d, i (i)}
256
+ <li class="pie-legend-row">
257
+ <span class="pie-legend-swatch" style="background: {d.color ?? getColor(i)}"></span>
258
+ <span class="pie-legend-label">{d.label}</span>
259
+ <span class="pie-legend-value">
260
+ {format(d.value)}&nbsp;{pctFormat(d.value)}
261
+ </span>
262
+ </li>
263
+ {/each}
264
+ </ul>
265
+ {/if}
266
+
178
267
  {#if typeof tooltipSnippet === 'function' && hoveredIndex !== null && data[hoveredIndex]}
179
268
  <div class="chart-tooltip-slot" style="left: {mouseX + 12}px; top: {mouseY - 12}px;">
180
269
  {@render tooltipSnippet(data[hoveredIndex], hoveredIndex)}
@@ -233,4 +322,37 @@
233
322
  color: var(--chart-empty-color, #9ca3af);
234
323
  text-align: center;
235
324
  }
325
+ .pie-legend-values {
326
+ display: flex;
327
+ flex-direction: column;
328
+ gap: var(--piechart-legend-gap, 8px);
329
+ padding: var(--piechart-legend-padding, 12px 0 0 0);
330
+ font-family: var(--chart-font-family, inherit);
331
+ list-style: none;
332
+ margin: 0;
333
+ }
334
+ .pie-legend-row {
335
+ display: flex;
336
+ align-items: center;
337
+ gap: var(--piechart-legend-row-gap, 6px);
338
+ }
339
+ .pie-legend-swatch {
340
+ display: inline-block;
341
+ width: var(--chart-legend-swatch-size, 12px);
342
+ height: var(--chart-legend-swatch-size, 12px);
343
+ border-radius: var(--piechart-legend-swatch-radius, 2px);
344
+ flex-shrink: 0;
345
+ }
346
+ .pie-legend-label {
347
+ font-size: var(--chart-legend-font-size, 12px);
348
+ color: var(--chart-legend-color, #333);
349
+ min-width: var(--piechart-legend-label-min-width, 120px);
350
+ }
351
+ .pie-legend-value {
352
+ margin-left: auto;
353
+ font-size: var(--piechart-legend-value-font-size, 12px);
354
+ color: var(--piechart-legend-value-color, #333);
355
+ min-width: var(--piechart-legend-value-min-width, 60px);
356
+ text-align: right;
357
+ }
236
358
  </style>
@@ -23,6 +23,9 @@ export type OptionalPieChartProperties = {
23
23
  empty?: Snippet;
24
24
  testId?: string;
25
25
  classes?: string;
26
+ semiCircle?: boolean;
27
+ legendShowValues?: boolean;
28
+ percentDecimals?: number;
26
29
  };
27
30
  export type PieChartEventProperties = {
28
31
  onsliceclick?: (event: {
@@ -13,22 +13,36 @@
13
13
  }: ChartContainerProperties = $props();
14
14
 
15
15
  let containerEl: HTMLDivElement | null = $state(null);
16
+ let isMounted = false;
16
17
 
17
- onMount(() => {
18
+ function measure() {
18
19
  if (containerEl === null) {
19
20
  return;
20
21
  }
22
+ const rect = containerEl.getBoundingClientRect();
23
+ const w = Math.round(rect.width);
24
+ width = w;
25
+ height = Math.max(minHeight, Math.round(w / aspectRatio));
26
+ }
27
+
28
+ // Re-measure whenever aspectRatio changes at runtime (e.g. semiCircle toggled).
29
+ // isMounted guards against running after the onMount cleanup has disconnected
30
+ // the ResizeObserver and the component is being torn down.
31
+ // eslint-disable-next-line no-restricted-syntax
32
+ $effect(() => {
33
+ // Reading aspectRatio here makes this effect re-run whenever it changes.
34
+ void aspectRatio;
35
+ if (isMounted) {
36
+ measure();
37
+ }
38
+ });
21
39
 
22
- function measure() {
23
- if (containerEl === null) {
24
- return;
25
- }
26
- const rect = containerEl.getBoundingClientRect();
27
- const w = Math.round(rect.width);
28
- width = w;
29
- height = Math.max(minHeight, Math.round(w / aspectRatio));
40
+ onMount(() => {
41
+ if (containerEl === null) {
42
+ return;
30
43
  }
31
44
 
45
+ isMounted = true;
32
46
  measure();
33
47
 
34
48
  // Coalesce bursts of resize events into a single measure per frame, always
@@ -41,6 +55,7 @@
41
55
  observer.observe(containerEl);
42
56
 
43
57
  return () => {
58
+ isMounted = false;
44
59
  cancelAnimationFrame(frame);
45
60
  observer.disconnect();
46
61
  };
@@ -1,3 +1,4 @@
1
1
  export declare function formatNumber(value: number): string;
2
2
  export declare function formatPercent(value: number, total: number): string;
3
3
  export declare function defaultTickFormat(value: number | string): string;
4
+ export declare function formatNumberIndian(value: number): string;
@@ -26,3 +26,16 @@ export function defaultTickFormat(value) {
26
26
  }
27
27
  return formatNumber(value);
28
28
  }
29
+ export function formatNumberIndian(value) {
30
+ const abs = Math.abs(value);
31
+ if (abs >= 1e7) {
32
+ return (value / 1e7).toFixed(2).replace(/\.?0+$/, '') + 'Cr';
33
+ }
34
+ if (abs >= 1e5) {
35
+ return (value / 1e5).toFixed(2).replace(/\.?0+$/, '') + 'L';
36
+ }
37
+ if (abs >= 1e3) {
38
+ return (value / 1e3).toFixed(2).replace(/\.?0+$/, '') + 'K';
39
+ }
40
+ return value.toLocaleString('en-IN');
41
+ }
package/dist/index.d.ts CHANGED
@@ -126,3 +126,4 @@ export type * from './BarChart/properties';
126
126
  export type * from './PieChart/properties';
127
127
  export type * from './SankeyChart/properties';
128
128
  export { validateInput } from './utils';
129
+ export { formatNumberIndian } from './_chart/format';
package/dist/index.js CHANGED
@@ -65,3 +65,4 @@ export { default as BarChart } from './BarChart/BarChart.svelte';
65
65
  export { default as PieChart } from './PieChart/PieChart.svelte';
66
66
  export { default as SankeyChart } from './SankeyChart/SankeyChart.svelte';
67
67
  export { validateInput } from './utils';
68
+ export { formatNumberIndian } from './_chart/format';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juspay/svelte-ui-components",
3
- "version": "2.59.0",
3
+ "version": "2.61.0",
4
4
  "description": "A themeable Svelte 5 UI component library with CSS custom property driven styling",
5
5
  "keywords": [
6
6
  "svelte",