@aura-react-comp/charts 0.3.1 → 0.4.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 (68) hide show
  1. package/esm/charts/area-chart/index.js +27 -23
  2. package/esm/charts/bar-chart/index.js +17 -21
  3. package/esm/charts/candlestick-chart/index.js +242 -180
  4. package/esm/charts/combo-chart/index.js +8 -20
  5. package/esm/charts/funnel-chart/index.js +133 -108
  6. package/esm/charts/gauge-chart/index.js +102 -105
  7. package/esm/charts/graph-chart/index.js +154 -114
  8. package/esm/charts/heatmap-chart/index.js +179 -135
  9. package/esm/charts/line-chart/index.js +28 -24
  10. package/esm/charts/pie-chart/index.d.ts.map +1 -1
  11. package/esm/charts/pie-chart/index.js +198 -139
  12. package/esm/charts/radar-chart/index.d.ts.map +1 -1
  13. package/esm/charts/radar-chart/index.js +154 -128
  14. package/esm/charts/ring-progress/index.js +81 -82
  15. package/esm/charts/sankey-chart/index.js +171 -141
  16. package/esm/charts/scatter-chart/index.d.ts.map +1 -1
  17. package/esm/charts/scatter-chart/index.js +225 -159
  18. package/esm/charts/sparkline/index.js +81 -66
  19. package/esm/charts/tree-chart/index.js +128 -102
  20. package/esm/charts/treemap-chart/index.js +162 -141
  21. package/esm/charts/waterfall-chart/index.js +165 -121
  22. package/esm/components/Legend.d.ts +3 -2
  23. package/esm/components/Legend.d.ts.map +1 -1
  24. package/esm/components/Legend.js +79 -48
  25. package/esm/components/Tooltip.js +62 -71
  26. package/esm/components/chart/index.d.ts +4 -1
  27. package/esm/components/chart/index.d.ts.map +1 -1
  28. package/esm/components/chart/index.js +80 -102
  29. package/esm/components/chart.less +13 -0
  30. package/esm/core/animation.js +31 -43
  31. package/esm/core/export.d.ts +34 -0
  32. package/esm/core/export.d.ts.map +1 -0
  33. package/esm/core/export.js +390 -0
  34. package/esm/core/force.js +22 -45
  35. package/esm/core/format.js +48 -52
  36. package/esm/core/hierarchy.js +60 -92
  37. package/esm/core/layout.js +32 -50
  38. package/esm/core/sampling.js +30 -53
  39. package/esm/core/sankey.js +35 -55
  40. package/esm/core/scale.js +72 -86
  41. package/esm/core/shape.js +101 -133
  42. package/esm/core/sync.d.ts +41 -0
  43. package/esm/core/sync.d.ts.map +1 -0
  44. package/esm/core/sync.js +120 -0
  45. package/esm/hooks/useChartExport.d.ts +19 -0
  46. package/esm/hooks/useChartExport.d.ts.map +1 -0
  47. package/esm/hooks/useChartExport.js +35 -0
  48. package/esm/hooks/useChartTheme.js +17 -19
  49. package/esm/hooks/useChartTransition.js +58 -73
  50. package/esm/hooks/useElementSize.js +19 -28
  51. package/esm/hooks/usePlotPointer.d.ts +23 -0
  52. package/esm/hooks/usePlotPointer.d.ts.map +1 -0
  53. package/esm/hooks/usePlotPointer.js +94 -0
  54. package/esm/index.d.ts +6 -0
  55. package/esm/index.d.ts.map +1 -1
  56. package/esm/index.js +136 -47
  57. package/esm/internal/CartesianChart.d.ts.map +1 -1
  58. package/esm/internal/CartesianChart.js +666 -485
  59. package/esm/internal/model.js +44 -60
  60. package/esm/scene/canvas.js +100 -107
  61. package/esm/scene/svg.js +106 -99
  62. package/esm/scene/types.js +8 -15
  63. package/esm/style.css +10 -0
  64. package/esm/theme/index.js +143 -171
  65. package/esm/types.d.ts +4 -0
  66. package/esm/types.d.ts.map +1 -1
  67. package/esm/types.js +0 -1
  68. package/package.json +1 -1
@@ -0,0 +1,390 @@
1
+ 'use client';
2
+ // src/core/export.ts
3
+ import { detectDarkMode } from "../theme";
4
+ var SVG_NS = "http://www.w3.org/2000/svg";
5
+ var XLINK_NS = "http://www.w3.org/1999/xlink";
6
+ var VAR_RE = /var\(\s*(--[\w-]+)\s*(?:,\s*([^)]+))?\)/g;
7
+ var INLINE_ATTRS = [
8
+ "fill",
9
+ "stroke",
10
+ "color",
11
+ "stop-color",
12
+ "font-family",
13
+ "font-size"
14
+ ];
15
+ function isTransparent(value) {
16
+ if (!value)
17
+ return true;
18
+ const v = value.trim().toLowerCase();
19
+ return v === "" || v === "transparent" || v === "none" || v === "rgba(0, 0, 0, 0)" || v === "rgba(0,0,0,0)";
20
+ }
21
+ function resolveCssVars(value, el, depth = 0) {
22
+ if (depth > 4 || !value.includes("var(") || typeof window === "undefined") {
23
+ return value;
24
+ }
25
+ const computed = window.getComputedStyle(el);
26
+ const rootComputed = typeof document !== "undefined" && document.documentElement ? window.getComputedStyle(document.documentElement) : null;
27
+ const replaced = value.replace(
28
+ VAR_RE,
29
+ (match, name, fallback) => {
30
+ const resolved = computed.getPropertyValue(name).trim() || (rootComputed == null ? void 0 : rootComputed.getPropertyValue(name).trim()) || "";
31
+ if (resolved)
32
+ return resolved;
33
+ return fallback !== void 0 ? fallback.trim() : match;
34
+ }
35
+ );
36
+ return replaced !== value && replaced.includes("var(") ? resolveCssVars(replaced, el, depth + 1) : replaced;
37
+ }
38
+ function resolveBackground(container, explicit, forceOpaque = false) {
39
+ if (explicit !== void 0) {
40
+ if (!isTransparent(explicit)) {
41
+ return resolveCssVars(explicit, container);
42
+ }
43
+ if (!forceOpaque)
44
+ return null;
45
+ } else if (typeof window !== "undefined") {
46
+ const style = window.getComputedStyle(container);
47
+ if (!isTransparent(style.backgroundColor)) {
48
+ return style.backgroundColor;
49
+ }
50
+ const tokenBg = style.getPropertyValue("--aura-bg").trim() || window.getComputedStyle(document.documentElement).getPropertyValue("--aura-bg").trim();
51
+ if (!isTransparent(tokenBg))
52
+ return tokenBg;
53
+ }
54
+ if (forceOpaque) {
55
+ return detectDarkMode(container) ? "#111827" : "#ffffff";
56
+ }
57
+ return null;
58
+ }
59
+ function collectLayers(container) {
60
+ const scope = container.querySelector(".aura-chart__plot") ?? container;
61
+ const pick = (root) => Array.from(
62
+ root.querySelectorAll("canvas, svg")
63
+ ).filter((node) => !node.closest(".aura-chart__a11y"));
64
+ let layers = pick(scope);
65
+ if (layers.length === 0 && scope !== container) {
66
+ layers = pick(container);
67
+ }
68
+ return { scope, layers };
69
+ }
70
+ function measureBox(el) {
71
+ var _a;
72
+ const rect = el.getBoundingClientRect();
73
+ let width = rect.width;
74
+ let height = rect.height;
75
+ if (width <= 0 || height <= 0) {
76
+ const attrW = Number.parseFloat(el.getAttribute("width") ?? "");
77
+ const attrH = Number.parseFloat(el.getAttribute("height") ?? "");
78
+ if (width <= 0 && Number.isFinite(attrW) && attrW > 0)
79
+ width = attrW;
80
+ if (height <= 0 && Number.isFinite(attrH) && attrH > 0)
81
+ height = attrH;
82
+ }
83
+ if ((width <= 0 || height <= 0) && el instanceof HTMLCanvasElement) {
84
+ if (width <= 0)
85
+ width = el.clientWidth || el.width;
86
+ if (height <= 0)
87
+ height = el.clientHeight || el.height;
88
+ }
89
+ if ((width <= 0 || height <= 0) && el instanceof SVGSVGElement) {
90
+ const vb = (_a = el.getAttribute("viewBox")) == null ? void 0 : _a.trim().split(/[\s,]+/).map(Number);
91
+ if (vb && vb.length === 4) {
92
+ if (width <= 0 && Number.isFinite(vb[2]) && vb[2] > 0)
93
+ width = vb[2];
94
+ if (height <= 0 && Number.isFinite(vb[3]) && vb[3] > 0)
95
+ height = vb[3];
96
+ }
97
+ }
98
+ return { width: Math.max(0, width), height: Math.max(0, height) };
99
+ }
100
+ function buildStandaloneSvg(svg, container, background) {
101
+ const clone = svg.cloneNode(true);
102
+ const { width, height } = measureBox(svg);
103
+ clone.setAttribute("xmlns", SVG_NS);
104
+ if (width > 0)
105
+ clone.setAttribute("width", String(width));
106
+ if (height > 0)
107
+ clone.setAttribute("height", String(height));
108
+ if (!clone.getAttribute("viewBox") && width > 0 && height > 0) {
109
+ clone.setAttribute("viewBox", `0 0 ${width} ${height}`);
110
+ }
111
+ const origList = [svg, ...Array.from(svg.querySelectorAll("*"))];
112
+ const cloneList = [
113
+ clone,
114
+ ...Array.from(clone.querySelectorAll("*"))
115
+ ];
116
+ const hasComputed = typeof window !== "undefined";
117
+ const containerStyle = hasComputed ? window.getComputedStyle(container) : null;
118
+ let hasXlink = false;
119
+ for (let i = 0; i < origList.length; i += 1) {
120
+ const orig = origList[i];
121
+ const target = cloneList[i];
122
+ if (!target)
123
+ continue;
124
+ if (!hasXlink && target.hasAttribute("xlink:href")) {
125
+ hasXlink = true;
126
+ }
127
+ const computed = hasComputed ? window.getComputedStyle(orig) : null;
128
+ for (const attr of INLINE_ATTRS) {
129
+ const raw = target.getAttribute(attr);
130
+ if (!raw)
131
+ continue;
132
+ if (raw.includes("var(")) {
133
+ const resolved = resolveCssVars(raw, orig);
134
+ const fallback = computed == null ? void 0 : computed.getPropertyValue(attr).trim();
135
+ target.setAttribute(
136
+ attr,
137
+ resolved.includes("var(") && fallback ? fallback : resolved
138
+ );
139
+ } else if (raw === "currentColor" && (computed == null ? void 0 : computed.color)) {
140
+ target.setAttribute(attr, computed.color);
141
+ }
142
+ }
143
+ const inlineStyle = target.getAttribute("style");
144
+ if (inlineStyle && inlineStyle.includes("var(")) {
145
+ target.setAttribute("style", resolveCssVars(inlineStyle, orig));
146
+ }
147
+ const tag = orig.tagName.toLowerCase();
148
+ if (i === 0) {
149
+ const fontFamily = resolveCssVars(
150
+ (computed == null ? void 0 : computed.fontFamily) || (containerStyle == null ? void 0 : containerStyle.fontFamily) || "",
151
+ orig
152
+ ) || "sans-serif";
153
+ const color = resolveCssVars((computed == null ? void 0 : computed.color) || (containerStyle == null ? void 0 : containerStyle.color) || "", orig) || "#111827";
154
+ if (!target.getAttribute("font-family")) {
155
+ target.setAttribute("font-family", fontFamily);
156
+ }
157
+ if (!target.getAttribute("color")) {
158
+ target.setAttribute("color", color);
159
+ }
160
+ } else if (tag === "text" || tag === "tspan") {
161
+ if (!target.getAttribute("font-family")) {
162
+ const ff = resolveCssVars(
163
+ (computed == null ? void 0 : computed.fontFamily) || (containerStyle == null ? void 0 : containerStyle.fontFamily) || "",
164
+ orig
165
+ ) || "sans-serif";
166
+ target.setAttribute("font-family", ff);
167
+ }
168
+ if (!target.getAttribute("font-size") && (computed == null ? void 0 : computed.fontSize)) {
169
+ target.setAttribute("font-size", computed.fontSize);
170
+ }
171
+ if (!target.getAttribute("fill")) {
172
+ const fill = (computed == null ? void 0 : computed.fill) || (computed == null ? void 0 : computed.color) || (containerStyle == null ? void 0 : containerStyle.color);
173
+ if (fill)
174
+ target.setAttribute("fill", fill);
175
+ }
176
+ }
177
+ }
178
+ if (hasXlink) {
179
+ clone.setAttribute("xmlns:xlink", XLINK_NS);
180
+ }
181
+ if (background && !isTransparent(background)) {
182
+ const rect = document.createElementNS(SVG_NS, "rect");
183
+ rect.setAttribute("x", "0");
184
+ rect.setAttribute("y", "0");
185
+ rect.setAttribute("width", width > 0 ? String(width) : "100%");
186
+ rect.setAttribute("height", height > 0 ? String(height) : "100%");
187
+ rect.setAttribute("fill", background);
188
+ clone.insertBefore(rect, clone.firstChild);
189
+ }
190
+ const markup = typeof XMLSerializer !== "undefined" ? new XMLSerializer().serializeToString(clone) : clone.outerHTML;
191
+ return { markup, width, height };
192
+ }
193
+ function loadSvgImage(markup) {
194
+ return new Promise((resolve, reject) => {
195
+ const img = new Image();
196
+ let objectUrl = null;
197
+ const cleanup = () => {
198
+ if (objectUrl && typeof URL !== "undefined" && URL.revokeObjectURL) {
199
+ URL.revokeObjectURL(objectUrl);
200
+ objectUrl = null;
201
+ }
202
+ };
203
+ img.onload = () => {
204
+ cleanup();
205
+ resolve(img);
206
+ };
207
+ img.onerror = () => {
208
+ cleanup();
209
+ reject(new Error("SVG 图像加载失败,无法导出位图"));
210
+ };
211
+ if (typeof Blob !== "undefined" && typeof URL !== "undefined" && typeof URL.createObjectURL === "function") {
212
+ objectUrl = URL.createObjectURL(
213
+ new Blob([markup], { type: "image/svg+xml;charset=utf-8" })
214
+ );
215
+ img.src = objectUrl;
216
+ } else {
217
+ img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(markup)}`;
218
+ }
219
+ });
220
+ }
221
+ function dataUrlToBlob(dataUrl) {
222
+ if (typeof Blob === "undefined")
223
+ return null;
224
+ const comma = dataUrl.indexOf(",");
225
+ if (comma === -1)
226
+ return null;
227
+ const header = dataUrl.slice(0, comma);
228
+ const payload = dataUrl.slice(comma + 1);
229
+ const mimeMatch = /data:([^;,]+)/.exec(header);
230
+ const mime = mimeMatch ? mimeMatch[1] : "application/octet-stream";
231
+ if (header.includes(";base64") && typeof atob === "function") {
232
+ const binary = atob(payload);
233
+ const bytes = new Uint8Array(binary.length);
234
+ for (let i = 0; i < binary.length; i += 1) {
235
+ bytes[i] = binary.charCodeAt(i);
236
+ }
237
+ return new Blob([bytes], { type: mime });
238
+ }
239
+ return new Blob([decodeURIComponent(payload)], { type: mime });
240
+ }
241
+ function exportChartSvg(container, options) {
242
+ if (!container) {
243
+ throw new Error("图表导出失败:未提供有效的容器元素");
244
+ }
245
+ const { layers } = collectLayers(container);
246
+ const svg = layers.find(
247
+ (node) => node.tagName.toLowerCase() === "svg"
248
+ );
249
+ if (!svg) {
250
+ throw new Error("图表导出失败:未在容器中找到可导出的 SVG 元素");
251
+ }
252
+ const background = resolveBackground(container, options == null ? void 0 : options.backgroundColor);
253
+ return buildStandaloneSvg(svg, container, background).markup;
254
+ }
255
+ function exportChartDataUrl(container, options) {
256
+ if (!container) {
257
+ return Promise.reject(new Error("图表导出失败:未提供有效的容器元素"));
258
+ }
259
+ const format = (options == null ? void 0 : options.format) ?? "png";
260
+ const rawRatio = (options == null ? void 0 : options.pixelRatio) ?? 2;
261
+ const pixelRatio = typeof rawRatio === "number" && Number.isFinite(rawRatio) && rawRatio > 0 ? rawRatio : 2;
262
+ const quality = (options == null ? void 0 : options.quality) ?? 0.92;
263
+ const { scope, layers } = collectLayers(container);
264
+ if (layers.length === 0) {
265
+ return Promise.reject(
266
+ new Error("图表导出失败:未在容器中找到可导出的画布或 SVG 元素")
267
+ );
268
+ }
269
+ if (format === "svg") {
270
+ const hasSvg = layers.some((node) => node.tagName.toLowerCase() === "svg");
271
+ if (hasSvg) {
272
+ try {
273
+ const svgMarkup = exportChartSvg(container, options);
274
+ return Promise.resolve(
275
+ `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgMarkup)}`
276
+ );
277
+ } catch (error) {
278
+ return Promise.reject(error);
279
+ }
280
+ }
281
+ const canvas = layers[0];
282
+ const { width, height } = measureBox(canvas);
283
+ const w = width || canvas.width || 300;
284
+ const h = height || canvas.height || 150;
285
+ const bg2 = resolveBackground(container, options == null ? void 0 : options.backgroundColor);
286
+ const png = canvas.toDataURL("image/png");
287
+ const bgRect = bg2 ? `<rect x="0" y="0" width="${w}" height="${h}" fill="${bg2}"/>` : "";
288
+ const wrapped = `<svg xmlns="${SVG_NS}" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">${bgRect}<image href="${png}" width="${w}" height="${h}"/></svg>`;
289
+ return Promise.resolve(
290
+ `data:image/svg+xml;charset=utf-8,${encodeURIComponent(wrapped)}`
291
+ );
292
+ }
293
+ const scopeRect = scope.getBoundingClientRect();
294
+ const baseSize = scopeRect.width > 0 && scopeRect.height > 0 ? { width: scopeRect.width, height: scopeRect.height } : measureBox(layers[0]);
295
+ if (baseSize.width <= 0 || baseSize.height <= 0) {
296
+ return Promise.reject(new Error("图表导出失败:目标图表尺寸为 0"));
297
+ }
298
+ const offscreen = document.createElement("canvas");
299
+ offscreen.width = Math.max(1, Math.round(baseSize.width * pixelRatio));
300
+ offscreen.height = Math.max(1, Math.round(baseSize.height * pixelRatio));
301
+ const ctx = offscreen.getContext("2d");
302
+ if (!ctx) {
303
+ return Promise.reject(
304
+ new Error("图表导出失败:当前环境不支持 Canvas 2D 渲染上下文")
305
+ );
306
+ }
307
+ ctx.scale(pixelRatio, pixelRatio);
308
+ const bg = resolveBackground(
309
+ container,
310
+ options == null ? void 0 : options.backgroundColor,
311
+ format === "jpeg"
312
+ );
313
+ if (bg) {
314
+ ctx.fillStyle = bg;
315
+ ctx.fillRect(0, 0, baseSize.width, baseSize.height);
316
+ }
317
+ let chain = Promise.resolve();
318
+ for (const layer of layers) {
319
+ chain = chain.then(() => {
320
+ const layerRect = layer.getBoundingClientRect();
321
+ const layerBox = measureBox(layer);
322
+ const drawW = layerBox.width || baseSize.width;
323
+ const drawH = layerBox.height || baseSize.height;
324
+ const offsetX = scopeRect.width > 0 && layerRect.width > 0 ? layerRect.left - scopeRect.left : 0;
325
+ const offsetY = scopeRect.height > 0 && layerRect.height > 0 ? layerRect.top - scopeRect.top : 0;
326
+ if (layer.tagName.toLowerCase() === "canvas") {
327
+ ctx.drawImage(
328
+ layer,
329
+ offsetX,
330
+ offsetY,
331
+ drawW,
332
+ drawH
333
+ );
334
+ return void 0;
335
+ }
336
+ const { markup } = buildStandaloneSvg(
337
+ layer,
338
+ container,
339
+ null
340
+ );
341
+ return loadSvgImage(markup).then((img) => {
342
+ ctx.drawImage(img, offsetX, offsetY, drawW, drawH);
343
+ });
344
+ });
345
+ }
346
+ const mime = format === "jpeg" ? "image/jpeg" : "image/png";
347
+ return chain.then(
348
+ () => offscreen.toDataURL(mime, format === "jpeg" ? quality : void 0)
349
+ );
350
+ }
351
+ function downloadChart(container, options) {
352
+ var _a;
353
+ const format = (options == null ? void 0 : options.format) ?? "png";
354
+ const rawName = ((_a = options == null ? void 0 : options.filename) == null ? void 0 : _a.trim()) || `aura-chart.${format}`;
355
+ const extRe = /\.(png|jpe?g|svg)$/i;
356
+ const filename = extRe.test(rawName) ? rawName : `${rawName}.${format}`;
357
+ return exportChartDataUrl(container, options).then((dataUrl) => {
358
+ if (typeof document === "undefined")
359
+ return dataUrl;
360
+ let objectUrl = null;
361
+ const blob = dataUrlToBlob(dataUrl);
362
+ if (blob && typeof URL !== "undefined" && typeof URL.createObjectURL === "function") {
363
+ objectUrl = URL.createObjectURL(blob);
364
+ }
365
+ const link = document.createElement("a");
366
+ link.href = objectUrl ?? dataUrl;
367
+ link.download = filename;
368
+ link.style.display = "none";
369
+ document.body.appendChild(link);
370
+ try {
371
+ link.click();
372
+ } finally {
373
+ document.body.removeChild(link);
374
+ if (objectUrl && typeof URL !== "undefined" && typeof URL.revokeObjectURL === "function") {
375
+ const urlToRevoke = objectUrl;
376
+ setTimeout(() => {
377
+ if (typeof URL !== "undefined" && typeof URL.revokeObjectURL === "function") {
378
+ URL.revokeObjectURL(urlToRevoke);
379
+ }
380
+ }, 0);
381
+ }
382
+ }
383
+ return dataUrl;
384
+ });
385
+ }
386
+ export {
387
+ downloadChart,
388
+ exportChartDataUrl,
389
+ exportChartSvg
390
+ };
package/esm/core/force.js CHANGED
@@ -1,27 +1,14 @@
1
1
  'use client';
2
- /** 确定性伪随机:同一个 seed 恒定,保证 SSR 与截图一致 */
2
+ // src/core/force.ts
3
3
  function pseudo(seed) {
4
4
  const value = Math.sin(seed * 12.9898) * 43758.5453;
5
5
  return value - Math.floor(value);
6
6
  }
7
-
8
- /**
9
- * 力导向布局(Fruchterman–Reingold)。
10
- *
11
- * 把图当成物理系统:节点两两相斥、有连边的相互吸引,
12
- * 每轮按「温度」限制最大位移,温度线性冷却到 0 后收敛。
13
- *
14
- * 初始位置用「圆环 + 确定性扰动」而不是随机散布:
15
- * 随机数会让同一份数据在每次刷新时长得不一样,也不利于截图对比;
16
- * 圆环本身已经足够均匀,能让迭代更快收敛。
17
- */
18
- export function layoutForce(nodes, links, rect, options = {}) {
7
+ function layoutForce(nodes, links, rect, options = {}) {
19
8
  const count = nodes.length;
20
- if (count === 0) return [];
21
- const {
22
- iterations = 220,
23
- radius = 8
24
- } = options;
9
+ if (count === 0)
10
+ return [];
11
+ const { iterations = 220, radius = 8 } = options;
25
12
  const indexOf = new Map(nodes.map((node, index) => [node.id, index]));
26
13
  const xs = new Array(count);
27
14
  const ys = new Array(count);
@@ -30,16 +17,12 @@ export function layoutForce(nodes, links, rect, options = {}) {
30
17
  for (const link of links) {
31
18
  const a = indexOf.get(link.source);
32
19
  const b = indexOf.get(link.target);
33
- if (a === undefined || b === undefined || a === b) continue;
34
- valid.push({
35
- a,
36
- b
37
- });
20
+ if (a === void 0 || b === void 0 || a === b)
21
+ continue;
22
+ valid.push({ a, b });
38
23
  degrees[a] += 1;
39
24
  degrees[b] += 1;
40
25
  }
41
-
42
- // 初始:圆环 + 轻微扰动(单节点时居中)
43
26
  const cx = rect.x + rect.width / 2;
44
27
  const cy = rect.y + rect.height / 2;
45
28
  const ringRadius = Math.min(rect.width, rect.height) * 0.34;
@@ -55,12 +38,7 @@ export function layoutForce(nodes, links, rect, options = {}) {
55
38
  ys[index] = cy + Math.sin(angle) * (ringRadius + jitter);
56
39
  }
57
40
  if (count === 1) {
58
- return [{
59
- id: nodes[0].id,
60
- x: cx,
61
- y: cy,
62
- degree: 0
63
- }];
41
+ return [{ id: nodes[0].id, x: cx, y: cy, degree: 0 }];
64
42
  }
65
43
  const area = Math.max(1, rect.width * rect.height);
66
44
  const k = Math.sqrt(area / count);
@@ -69,15 +47,12 @@ export function layoutForce(nodes, links, rect, options = {}) {
69
47
  for (let step = 0; step < iterations; step += 1) {
70
48
  const dx = new Array(count).fill(0);
71
49
  const dy = new Array(count).fill(0);
72
-
73
- // 斥力:所有节点两两排斥
74
50
  for (let i = 0; i < count; i += 1) {
75
51
  for (let j = i + 1; j < count; j += 1) {
76
52
  let deltaX = xs[i] - xs[j];
77
53
  let deltaY = ys[i] - ys[j];
78
54
  let distance = Math.hypot(deltaX, deltaY);
79
55
  if (distance < 0.01) {
80
- // 完全重合时给一个确定性的偏移方向,避免除零
81
56
  deltaX = (pseudo(i + j + 1) - 0.5) * 0.1;
82
57
  deltaY = (pseudo(i + j + 2) - 0.5) * 0.1;
83
58
  distance = 0.01;
@@ -91,12 +66,7 @@ export function layoutForce(nodes, links, rect, options = {}) {
91
66
  dy[j] -= uy * force;
92
67
  }
93
68
  }
94
-
95
- // 引力:有连边的相互吸引
96
- for (const {
97
- a,
98
- b
99
- } of valid) {
69
+ for (const { a, b } of valid) {
100
70
  let deltaX = xs[a] - xs[b];
101
71
  let deltaY = ys[a] - ys[b];
102
72
  let distance = Math.hypot(deltaX, deltaY);
@@ -113,15 +83,19 @@ export function layoutForce(nodes, links, rect, options = {}) {
113
83
  dx[b] += ux * force;
114
84
  dy[b] += uy * force;
115
85
  }
116
-
117
- // 按温度限制位移,并夹在画布内
118
86
  for (let index = 0; index < count; index += 1) {
119
87
  const length = Math.hypot(dx[index], dy[index]) || 1;
120
88
  const limited = Math.min(length, temperature);
121
89
  xs[index] += dx[index] / length * limited;
122
90
  ys[index] += dy[index] / length * limited;
123
- xs[index] = Math.min(rect.x + rect.width - margin, Math.max(rect.x + margin, xs[index]));
124
- ys[index] = Math.min(rect.y + rect.height - margin, Math.max(rect.y + margin, ys[index]));
91
+ xs[index] = Math.min(
92
+ rect.x + rect.width - margin,
93
+ Math.max(rect.x + margin, xs[index])
94
+ );
95
+ ys[index] = Math.min(
96
+ rect.y + rect.height - margin,
97
+ Math.max(rect.y + margin, ys[index])
98
+ );
125
99
  }
126
100
  temperature = Math.max(0.5, temperature * 0.975);
127
101
  }
@@ -131,4 +105,7 @@ export function layoutForce(nodes, links, rect, options = {}) {
131
105
  y: ys[index],
132
106
  degree: degrees[index]
133
107
  }));
134
- }
108
+ }
109
+ export {
110
+ layoutForce
111
+ };
@@ -1,81 +1,77 @@
1
1
  'use client';
2
- /**
3
- * 数值与文本格式化。
4
- *
5
- * 图表里最容易出「廉价感」的地方就是刻度:`12000` 不如 `1.2万`,
6
- * `0.30000000000000004` 更要命。这里统一收口。
7
- */
8
-
9
- /** 去掉小数末尾多余的 0 */
2
+ // src/core/format.ts
10
3
  function trimZeros(text) {
11
- return text.includes('.') ? text.replace(/\.?0+$/, '') : text;
4
+ return text.includes(".") ? text.replace(/\.?0+$/, "") : text;
12
5
  }
13
-
14
- /** 根据数值量级推断合适的小数位 */
15
- export function inferDecimals(values) {
6
+ function inferDecimals(values) {
16
7
  let decimals = 0;
17
8
  for (const value of values) {
18
- if (!Number.isFinite(value)) continue;
9
+ if (!Number.isFinite(value))
10
+ continue;
19
11
  const text = String(value);
20
- const dot = text.indexOf('.');
21
- if (dot >= 0) decimals = Math.max(decimals, text.length - dot - 1);
12
+ const dot = text.indexOf(".");
13
+ if (dot >= 0)
14
+ decimals = Math.max(decimals, text.length - dot - 1);
22
15
  }
23
16
  return Math.min(decimals, 4);
24
17
  }
25
-
26
- /** 紧凑单位:中文场景用「万 / 亿」,符合国内看板习惯 */
27
- export function formatCompact(value, decimals = 1) {
18
+ function formatCompact(value, decimals = 1) {
28
19
  const abs = Math.abs(value);
29
- const sign = value < 0 ? '-' : '';
30
- if (abs >= 1e8) return `${sign}${trimZeros((abs / 1e8).toFixed(decimals))}亿`;
31
- if (abs >= 1e4) return `${sign}${trimZeros((abs / 1e4).toFixed(decimals))}万`;
32
- if (abs >= 1e3) return `${sign}${trimZeros((abs / 1e3).toFixed(decimals))}k`;
20
+ const sign = value < 0 ? "-" : "";
21
+ if (abs >= 1e8)
22
+ return `${sign}${trimZeros((abs / 1e8).toFixed(decimals))}亿`;
23
+ if (abs >= 1e4)
24
+ return `${sign}${trimZeros((abs / 1e4).toFixed(decimals))}万`;
25
+ if (abs >= 1e3)
26
+ return `${sign}${trimZeros((abs / 1e3).toFixed(decimals))}k`;
33
27
  return `${sign}${trimZeros(String(abs))}`;
34
28
  }
35
- export function formatNumber(value, options = {}) {
36
- if (!Number.isFinite(value)) return '—';
29
+ function formatNumber(value, options = {}) {
30
+ if (!Number.isFinite(value))
31
+ return "—";
37
32
  const {
38
33
  decimals,
39
34
  compact = false,
40
- prefix = '',
41
- suffix = '',
35
+ prefix = "",
36
+ suffix = "",
42
37
  thousands = true
43
38
  } = options;
44
- if (compact) return `${prefix}${formatCompact(value, decimals ?? 1)}${suffix}`;
45
- const fixed = decimals === undefined ? trimZeros(String(value)) : value.toFixed(decimals);
46
- if (!thousands) return `${prefix}${fixed}${suffix}`;
47
- const [intPart, decimalPart] = fixed.split('.');
48
- const withSeparator = intPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
39
+ if (compact)
40
+ return `${prefix}${formatCompact(value, decimals ?? 1)}${suffix}`;
41
+ const fixed = decimals === void 0 ? trimZeros(String(value)) : value.toFixed(decimals);
42
+ if (!thousands)
43
+ return `${prefix}${fixed}${suffix}`;
44
+ const [intPart, decimalPart] = fixed.split(".");
45
+ const withSeparator = intPart.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
49
46
  return `${prefix}${decimalPart ? `${withSeparator}.${decimalPart}` : withSeparator}${suffix}`;
50
47
  }
51
- export function formatPercent(value, total, decimals = 1) {
52
- if (!total) return '0%';
48
+ function formatPercent(value, total, decimals = 1) {
49
+ if (!total)
50
+ return "0%";
53
51
  return `${trimZeros((value / total * 100).toFixed(decimals))}%`;
54
52
  }
55
-
56
- /**
57
- * 粗略估算文本像素宽度。
58
- *
59
- * 为什么要估算而不是真实测量:布局阶段(计算 margin、判断标签是否重叠)
60
- * 发生在渲染之前,此时没有 DOM 可测量。用「CJK 记 1em、其余记 0.58em」
61
- * 的经验值足够可靠,误差被 8px 的留白吸收。
62
- */
63
- export function estimateTextWidth(text, fontSize) {
53
+ function estimateTextWidth(text, fontSize) {
64
54
  let width = 0;
65
55
  for (const char of text) {
66
56
  const code = char.codePointAt(0) ?? 0;
67
- // CJK 统一表意文字、全角标点、假名、韩文
68
- const isWide = code >= 0x2e80 && code <= 0x9fff || code >= 0xac00 && code <= 0xd7af || code >= 0xf900 && code <= 0xfaff || code >= 0xff00 && code <= 0xff60 || code >= 0xffe0 && code <= 0xffe6;
57
+ const isWide = code >= 11904 && code <= 40959 || code >= 44032 && code <= 55215 || code >= 63744 && code <= 64255 || code >= 65280 && code <= 65376 || code >= 65504 && code <= 65510;
69
58
  width += isWide ? fontSize : fontSize * 0.58;
70
59
  }
71
60
  return width;
72
61
  }
73
-
74
- /** 数值补零宽度,用于让刻度标签右对齐时视觉整齐 */
75
- export function padNumberLabels(labels) {
62
+ function padNumberLabels(labels) {
76
63
  const width = labels.reduce((max, item) => Math.max(max, item.length), 0);
77
- if (width === 0) return labels;
78
- // 只在全部为纯数字(含符号/千分位)时补零,避免把「1月」也补成「01月」
79
- if (!labels.every(item => /^-?[\d,.]+$/.test(item))) return labels;
80
- return labels.map(item => item.padStart(width, ' '));
81
- }
64
+ if (width === 0)
65
+ return labels;
66
+ if (!labels.every((item) => /^-?[\d,.]+$/.test(item)))
67
+ return labels;
68
+ return labels.map((item) => item.padStart(width, " "));
69
+ }
70
+ export {
71
+ estimateTextWidth,
72
+ formatCompact,
73
+ formatNumber,
74
+ formatPercent,
75
+ inferDecimals,
76
+ padNumberLabels
77
+ };