@konce-pt/chart 0.8.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 konce.pt
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,53 @@
1
+ <p align="center">
2
+ <img src="https://ui.konce.pt/images/koncept_ui_lib.png" alt="Koncept UI — Angular component library" width="100%" />
3
+ </p>
4
+
5
+ # @konce-pt/chart
6
+
7
+ Rdzeń geometrii wykresów [Koncept UI](https://gitlab.com/konce-pt/koncept-ui): skale i podziałki,
8
+ ścieżki linii i obszaru, układ słupków, geometria wykresów kołowych, polarnych i radaru. Czysty
9
+ TypeScript, **zero zależności runtime**, bez wiązania z frameworkiem.
10
+
11
+ Zwykle nie instalujesz go samodzielnie: używają go `@konce-pt/angular/charts`
12
+ i `@konce-pt/react/charts`, i oba re-eksportują jego API. Sięgnij po niego wprost, gdy renderujesz
13
+ wykres po stronie serwera albo budujesz własny typ wykresu na tej samej geometrii.
14
+
15
+ ```bash
16
+ npm i @konce-pt/chart
17
+ ```
18
+
19
+ ```ts
20
+ import { niceScale, linePath, pieSlices } from '@konce-pt/chart';
21
+
22
+ // Oś zawsze zawiera zero i ma równe, „ładne" kroki.
23
+ niceScale(12, 87); // { min: 0, max: 100, step: 25, ticks: [0, 25, 50, 75, 100] }
24
+
25
+ // Trzy tryby interpolacji; monotoniczny nie przestrzeliwuje ekstremów danych.
26
+ linePath([{ x: 0, y: 10 }, { x: 10, y: 0 }], 'cubic-monotonic');
27
+
28
+ // Same zera nie rysują nic, zamiast dzielić przez zero.
29
+ pieSlices([0, 0], 50, 50, 40); // []
30
+ ```
31
+
32
+ ## API
33
+
34
+ - **Skale** — `extent`, `linearScale`, `bandScale`, `niceScale`
35
+ - **Linie** — `linePath`, `areaPath`
36
+ - **Słupki** — `barLayout`
37
+ - **Łuki** — `arcPath`, `pieSlices`, `polarSlices`, `polarToCartesian`
38
+ - **Radar** — `radarGrid`, `radarPoints`, `polygonPath`
39
+ - **Układ i prezentacja** — `plotArea`, `radialArea`, `seriesColor`, `KPT_CHART_PALETTE`,
40
+ `formatNumber`, `round`
41
+ - **Typy** — `KptChartConfig` i wszystko, do czego się odwołuje
42
+
43
+ Pełny opis: [`llms.txt`](./llms.txt) (EN) i [`llms-pl.txt`](./llms-pl.txt) (PL).
44
+
45
+ ## Testy
46
+
47
+ ```bash
48
+ pnpm --filter @konce-pt/chart exec node --test "src/**/*.test.ts"
49
+ ```
50
+
51
+ ## Licencja
52
+
53
+ MIT © [konce.pt](https://konce.pt)
package/dist/arc.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ import type { KptPoint } from './types.ts';
2
+ /** Punkt na okręgu dla kąta (0 = góra, rośnie zgodnie z zegarem). */
3
+ export declare function polarToCartesian(cx: number, cy: number, radius: number, angle: number): KptPoint;
4
+ /**
5
+ * Ścieżka wycinka pierścienia od `startAngle` do `endAngle`.
6
+ * `innerRadius = 0` → pełny wycinek koła (pie); > 0 → pierścień (doughnut).
7
+ */
8
+ export declare function arcPath(cx: number, cy: number, outerRadius: number, innerRadius: number, startAngle: number, endAngle: number): string;
9
+ export interface ArcSlice {
10
+ path: string;
11
+ /** Kąt środka wycinka (do pozycjonowania etykiet/tooltipa). */
12
+ midAngle: number;
13
+ startAngle: number;
14
+ endAngle: number;
15
+ value: number;
16
+ }
17
+ /**
18
+ * Wycinki pie/doughnut: kąt proporcjonalny do wartości (Σ = 2π).
19
+ * `innerRadius` w px (0 dla pie).
20
+ */
21
+ export declare function pieSlices(values: number[], cx: number, cy: number, outerRadius: number, innerRadius?: number): ArcSlice[];
22
+ /**
23
+ * Wycinki polar area: równy kąt (2π/N), promień proporcjonalny do wartości.
24
+ * `maxValue` skaluje promień do `outerRadius`.
25
+ */
26
+ export declare function polarSlices(values: number[], cx: number, cy: number, outerRadius: number, maxValue?: number): ArcSlice[];
package/dist/arc.js ADDED
@@ -0,0 +1,101 @@
1
+ const HALF_PI = Math.PI / 2;
2
+ function n(value) {
3
+ return Number.isInteger(value) ? String(value) : value.toFixed(3);
4
+ }
5
+ /** Punkt na okręgu dla kąta (0 = góra, rośnie zgodnie z zegarem). */
6
+ export function polarToCartesian(cx, cy, radius, angle) {
7
+ const a = angle - HALF_PI;
8
+ return { x: cx + radius * Math.cos(a), y: cy + radius * Math.sin(a) };
9
+ }
10
+ /**
11
+ * Ścieżka wycinka pierścienia od `startAngle` do `endAngle`.
12
+ * `innerRadius = 0` → pełny wycinek koła (pie); > 0 → pierścień (doughnut).
13
+ */
14
+ export function arcPath(cx, cy, outerRadius, innerRadius, startAngle, endAngle) {
15
+ const sweep = endAngle - startAngle;
16
+ const largeArc = sweep > Math.PI ? 1 : 0;
17
+ // Pełny okrąg (np. pojedynczy wycinek 100%) — rozbijamy na dwa łuki.
18
+ if (sweep >= Math.PI * 2 - 1e-6) {
19
+ const outer = fullCircle(cx, cy, outerRadius, 1);
20
+ if (innerRadius <= 0)
21
+ return outer;
22
+ return `${outer} ${fullCircle(cx, cy, innerRadius, 0)}`;
23
+ }
24
+ const oStart = polarToCartesian(cx, cy, outerRadius, startAngle);
25
+ const oEnd = polarToCartesian(cx, cy, outerRadius, endAngle);
26
+ if (innerRadius <= 0) {
27
+ return [
28
+ `M ${n(cx)} ${n(cy)}`,
29
+ `L ${n(oStart.x)} ${n(oStart.y)}`,
30
+ `A ${n(outerRadius)} ${n(outerRadius)} 0 ${largeArc} 1 ${n(oEnd.x)} ${n(oEnd.y)}`,
31
+ 'Z',
32
+ ].join(' ');
33
+ }
34
+ const iStart = polarToCartesian(cx, cy, innerRadius, endAngle);
35
+ const iEnd = polarToCartesian(cx, cy, innerRadius, startAngle);
36
+ return [
37
+ `M ${n(oStart.x)} ${n(oStart.y)}`,
38
+ `A ${n(outerRadius)} ${n(outerRadius)} 0 ${largeArc} 1 ${n(oEnd.x)} ${n(oEnd.y)}`,
39
+ `L ${n(iStart.x)} ${n(iStart.y)}`,
40
+ `A ${n(innerRadius)} ${n(innerRadius)} 0 ${largeArc} 0 ${n(iEnd.x)} ${n(iEnd.y)}`,
41
+ 'Z',
42
+ ].join(' ');
43
+ }
44
+ /** Pełny okrąg jako dwa półłuki (sweepFlag steruje kierunkiem — dla wycięcia). */
45
+ function fullCircle(cx, cy, r, sweepFlag) {
46
+ const top = polarToCartesian(cx, cy, r, 0);
47
+ const bottom = polarToCartesian(cx, cy, r, Math.PI);
48
+ return [
49
+ `M ${n(top.x)} ${n(top.y)}`,
50
+ `A ${n(r)} ${n(r)} 0 1 ${sweepFlag} ${n(bottom.x)} ${n(bottom.y)}`,
51
+ `A ${n(r)} ${n(r)} 0 1 ${sweepFlag} ${n(top.x)} ${n(top.y)}`,
52
+ 'Z',
53
+ ].join(' ');
54
+ }
55
+ /**
56
+ * Wycinki pie/doughnut: kąt proporcjonalny do wartości (Σ = 2π).
57
+ * `innerRadius` w px (0 dla pie).
58
+ */
59
+ export function pieSlices(values, cx, cy, outerRadius, innerRadius = 0) {
60
+ const total = values.reduce((a, v) => a + Math.max(0, v), 0);
61
+ if (total <= 0)
62
+ return [];
63
+ const slices = [];
64
+ let angle = 0;
65
+ for (const value of values) {
66
+ const sweep = (Math.max(0, value) / total) * Math.PI * 2;
67
+ const start = angle;
68
+ const end = angle + sweep;
69
+ slices.push({
70
+ path: arcPath(cx, cy, outerRadius, innerRadius, start, end),
71
+ midAngle: (start + end) / 2,
72
+ startAngle: start,
73
+ endAngle: end,
74
+ value,
75
+ });
76
+ angle = end;
77
+ }
78
+ return slices;
79
+ }
80
+ /**
81
+ * Wycinki polar area: równy kąt (2π/N), promień proporcjonalny do wartości.
82
+ * `maxValue` skaluje promień do `outerRadius`.
83
+ */
84
+ export function polarSlices(values, cx, cy, outerRadius, maxValue = 1) {
85
+ const count = values.length;
86
+ if (count === 0)
87
+ return [];
88
+ const sweep = (Math.PI * 2) / count;
89
+ return values.map((value, i) => {
90
+ const start = i * sweep;
91
+ const end = start + sweep;
92
+ const r = (Math.max(0, value) / maxValue) * outerRadius;
93
+ return {
94
+ path: arcPath(cx, cy, r, 0, start, end),
95
+ midAngle: (start + end) / 2,
96
+ startAngle: start,
97
+ endAngle: end,
98
+ value,
99
+ };
100
+ });
101
+ }
package/dist/bar.d.ts ADDED
@@ -0,0 +1,29 @@
1
+ import { niceScale } from './scale.ts';
2
+ import type { KptBarOrientation, KptRect } from './types.ts';
3
+ export interface BarGeom {
4
+ rect: KptRect;
5
+ /** Ścieżka słupka z zaokrąglonymi rogami „od strony wzrostu". */
6
+ path: string;
7
+ seriesIndex: number;
8
+ categoryIndex: number;
9
+ value: number;
10
+ }
11
+ export interface BarLayout {
12
+ bars: BarGeom[];
13
+ /** Podziałki osi wartości (wartość → współrzędna). */
14
+ ticks: {
15
+ value: number;
16
+ pos: number;
17
+ }[];
18
+ /** Współrzędna linii bazowej (0). */
19
+ baseline: number;
20
+ scale: ReturnType<typeof niceScale>;
21
+ }
22
+ /**
23
+ * Wylicza słupki dla obszaru `plot`.
24
+ * @param seriesData wartości[serie][kategorie]
25
+ * @param plot obszar rysowania {x,y,width,height}
26
+ * @param orientation pionowa (rośnie w górę) lub pozioma (rośnie w prawo)
27
+ * @param borderRadius promień zaokrąglenia w px
28
+ */
29
+ export declare function barLayout(seriesData: number[][], categoryCount: number, plot: KptRect, orientation: KptBarOrientation, borderRadius: number): BarLayout;
package/dist/bar.js ADDED
@@ -0,0 +1,101 @@
1
+ /*
2
+ * Geometria wykresu słupkowego (pionowego i poziomego) z zaokrągleniem rogów.
3
+ * Wspiera wiele serii (grupowanie obok siebie w obrębie kategorii).
4
+ */
5
+ import { bandScale, linearScale, niceScale } from "./scale.js";
6
+ function n(value) {
7
+ return Number.isInteger(value) ? String(value) : value.toFixed(3);
8
+ }
9
+ /** Prostokąt z zaokrąglonymi rogami tylko po wybranych stronach. */
10
+ function roundedRect(x, y, w, h, r, corners) {
11
+ const radius = Math.max(0, Math.min(r, w / 2, h / 2));
12
+ const tl = corners.tl ? radius : 0;
13
+ const tr = corners.tr ? radius : 0;
14
+ const br = corners.br ? radius : 0;
15
+ const bl = corners.bl ? radius : 0;
16
+ return [
17
+ `M ${n(x + tl)} ${n(y)}`,
18
+ `H ${n(x + w - tr)}`,
19
+ tr ? `A ${n(tr)} ${n(tr)} 0 0 1 ${n(x + w)} ${n(y + tr)}` : '',
20
+ `V ${n(y + h - br)}`,
21
+ br ? `A ${n(br)} ${n(br)} 0 0 1 ${n(x + w - br)} ${n(y + h)}` : '',
22
+ `H ${n(x + bl)}`,
23
+ bl ? `A ${n(bl)} ${n(bl)} 0 0 1 ${n(x)} ${n(y + h - bl)}` : '',
24
+ `V ${n(y + tl)}`,
25
+ tl ? `A ${n(tl)} ${n(tl)} 0 0 1 ${n(x + tl)} ${n(y)}` : '',
26
+ 'Z',
27
+ ]
28
+ .filter(Boolean)
29
+ .join(' ');
30
+ }
31
+ /**
32
+ * Wylicza słupki dla obszaru `plot`.
33
+ * @param seriesData wartości[serie][kategorie]
34
+ * @param plot obszar rysowania {x,y,width,height}
35
+ * @param orientation pionowa (rośnie w górę) lub pozioma (rośnie w prawo)
36
+ * @param borderRadius promień zaokrąglenia w px
37
+ */
38
+ export function barLayout(seriesData, categoryCount, plot, orientation, borderRadius) {
39
+ let min = 0;
40
+ let max = 0;
41
+ for (const row of seriesData) {
42
+ for (const v of row) {
43
+ if (v < min)
44
+ min = v;
45
+ if (v > max)
46
+ max = v;
47
+ }
48
+ }
49
+ const scale = niceScale(min, max, 5);
50
+ const seriesCount = seriesData.length || 1;
51
+ const bars = [];
52
+ if (orientation === 'vertical') {
53
+ const value = linearScale(scale.min, scale.max, plot.y + plot.height, plot.y);
54
+ const baseline = value(0);
55
+ const cat = bandScale(categoryCount, plot.x, plot.x + plot.width, 0.2);
56
+ const group = bandScale(seriesCount, 0, cat.bandwidth, 0.1);
57
+ seriesData.forEach((values, s) => {
58
+ for (let c = 0; c < categoryCount; c++) {
59
+ const v = values[c] ?? 0;
60
+ const x = cat.start(c) + group.start(s);
61
+ const w = group.bandwidth;
62
+ const yv = value(v);
63
+ const top = Math.min(baseline, yv);
64
+ const h = Math.abs(yv - baseline);
65
+ const up = v >= 0;
66
+ bars.push({
67
+ rect: { x, y: top, width: w, height: h },
68
+ path: roundedRect(x, top, w, h, borderRadius, up ? { tl: true, tr: true } : { bl: true, br: true }),
69
+ seriesIndex: s,
70
+ categoryIndex: c,
71
+ value: v,
72
+ });
73
+ }
74
+ });
75
+ return { bars, baseline, scale, ticks: scale.ticks.map((t) => ({ value: t, pos: value(t) })) };
76
+ }
77
+ // horizontal
78
+ const value = linearScale(scale.min, scale.max, plot.x, plot.x + plot.width);
79
+ const baseline = value(0);
80
+ const cat = bandScale(categoryCount, plot.y, plot.y + plot.height, 0.2);
81
+ const group = bandScale(seriesCount, 0, cat.bandwidth, 0.1);
82
+ seriesData.forEach((values, s) => {
83
+ for (let c = 0; c < categoryCount; c++) {
84
+ const v = values[c] ?? 0;
85
+ const y = cat.start(c) + group.start(s);
86
+ const h = group.bandwidth;
87
+ const xv = value(v);
88
+ const left = Math.min(baseline, xv);
89
+ const w = Math.abs(xv - baseline);
90
+ const right = v >= 0;
91
+ bars.push({
92
+ rect: { x: left, y, width: w, height: h },
93
+ path: roundedRect(left, y, w, h, borderRadius, right ? { tr: true, br: true } : { tl: true, bl: true }),
94
+ seriesIndex: s,
95
+ categoryIndex: c,
96
+ value: v,
97
+ });
98
+ }
99
+ });
100
+ return { bars, baseline, scale, ticks: scale.ticks.map((t) => ({ value: t, pos: value(t) })) };
101
+ }
@@ -0,0 +1,4 @@
1
+ /** Kolejność kolorów dla kolejnych serii / wycinków. */
2
+ export declare const KPT_CHART_PALETTE: readonly string[];
3
+ /** Kolor serii/wycinka: jawny z danych albo z palety (cyklicznie). */
4
+ export declare function seriesColor(explicit: string | undefined, index: number, palette?: readonly string[]): string;
package/dist/color.js ADDED
@@ -0,0 +1,21 @@
1
+ /*
2
+ * Domyślna paleta kolorów wykresów — oparta o semantyczne tokeny Koncept UI.
3
+ * Rozszerzona o dodatkowe odcienie skali, by obsłużyć wiele serii/wycinków.
4
+ */
5
+ /** Kolejność kolorów dla kolejnych serii / wycinków. */
6
+ export const KPT_CHART_PALETTE = [
7
+ 'var(--kpt-color-primary)',
8
+ 'var(--kpt-color-info)',
9
+ 'var(--kpt-color-success)',
10
+ 'var(--kpt-color-warning)',
11
+ 'var(--kpt-color-danger)',
12
+ 'var(--kpt-color-blue-700)',
13
+ 'var(--kpt-color-green-700)',
14
+ 'var(--kpt-color-amber-700)',
15
+ 'var(--kpt-color-red-700)',
16
+ 'var(--kpt-color-neutral-500)',
17
+ ];
18
+ /** Kolor serii/wycinka: jawny z danych albo z palety (cyklicznie). */
19
+ export function seriesColor(explicit, index, palette = KPT_CHART_PALETTE) {
20
+ return explicit ?? palette[index % palette.length];
21
+ }
@@ -0,0 +1,4 @@
1
+ /** Formatuje liczbę zwięźle (do 2 miejsc, bez zer końcowych). */
2
+ export declare function formatNumber(value: number, locale?: string): string;
3
+ /** Zaokrągla do skończonej liczby miejsc (do etykiet osi). */
4
+ export declare function round(value: number, digits?: number): number;
package/dist/format.js ADDED
@@ -0,0 +1,15 @@
1
+ /*
2
+ * Lekki formatter liczb dla etykiet osi i tooltipów.
3
+ * Framework-free; korzysta z wbudowanego Intl (dostępny w przeglądarce i Node).
4
+ */
5
+ /** Formatuje liczbę zwięźle (do 2 miejsc, bez zer końcowych). */
6
+ export function formatNumber(value, locale) {
7
+ if (!Number.isFinite(value))
8
+ return '';
9
+ return new Intl.NumberFormat(locale, { maximumFractionDigits: 2 }).format(value);
10
+ }
11
+ /** Zaokrągla do skończonej liczby miejsc (do etykiet osi). */
12
+ export function round(value, digits = 0) {
13
+ const f = 10 ** digits;
14
+ return Math.round(value * f) / f;
15
+ }
@@ -0,0 +1,9 @@
1
+ export * from './types.ts';
2
+ export * from './scale.ts';
3
+ export * from './line.ts';
4
+ export * from './bar.ts';
5
+ export * from './arc.ts';
6
+ export * from './radar.ts';
7
+ export * from './layout.ts';
8
+ export * from './color.ts';
9
+ export * from './format.ts';
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ /* Rdzeń wykresów (pure TS) — barrel eksportów. */
2
+ export * from "./types.js";
3
+ export * from "./scale.js";
4
+ export * from "./line.js";
5
+ export * from "./bar.js";
6
+ export * from "./arc.js";
7
+ export * from "./radar.js";
8
+ export * from "./layout.js";
9
+ export * from "./color.js";
10
+ export * from "./format.js";
@@ -0,0 +1,15 @@
1
+ import type { KptRect } from './types.ts';
2
+ export interface Insets {
3
+ top: number;
4
+ right: number;
5
+ bottom: number;
6
+ left: number;
7
+ }
8
+ /** Obszar rysowania po odjęciu marginesów od pełnego viewBoxa. */
9
+ export declare function plotArea(width: number, height: number, insets: Insets): KptRect;
10
+ /** Środek i promień dla wykresów promieniowych (pie/doughnut/polar/radar). */
11
+ export declare function radialArea(width: number, height: number, padding: number): {
12
+ cx: number;
13
+ cy: number;
14
+ radius: number;
15
+ };
package/dist/layout.js ADDED
@@ -0,0 +1,16 @@
1
+ /** Obszar rysowania po odjęciu marginesów od pełnego viewBoxa. */
2
+ export function plotArea(width, height, insets) {
3
+ return {
4
+ x: insets.left,
5
+ y: insets.top,
6
+ width: Math.max(0, width - insets.left - insets.right),
7
+ height: Math.max(0, height - insets.top - insets.bottom),
8
+ };
9
+ }
10
+ /** Środek i promień dla wykresów promieniowych (pie/doughnut/polar/radar). */
11
+ export function radialArea(width, height, padding) {
12
+ const cx = width / 2;
13
+ const cy = height / 2;
14
+ const radius = Math.max(0, Math.min(width, height) / 2 - padding);
15
+ return { cx, cy, radius };
16
+ }
package/dist/line.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ import type { KptLineInterpolation, KptPoint } from './types.ts';
2
+ /** Ścieżka linii dla wybranego trybu interpolacji. */
3
+ export declare function linePath(points: KptPoint[], mode?: KptLineInterpolation): string;
4
+ /** Ścieżka obszaru pod linią (domknięta do `baselineY`). */
5
+ export declare function areaPath(points: KptPoint[], baselineY: number, mode?: KptLineInterpolation): string;
package/dist/line.js ADDED
@@ -0,0 +1,105 @@
1
+ function n(value) {
2
+ // Skraca zapis (mniejszy DOM) i unika notacji wykładniczej dla małych liczb.
3
+ return Number.isInteger(value) ? String(value) : value.toFixed(3);
4
+ }
5
+ /** Ścieżka odcinkowa (M/L). */
6
+ function linearPath(points) {
7
+ return points.map((p, i) => `${i === 0 ? 'M' : 'L'} ${n(p.x)} ${n(p.y)}`).join(' ');
8
+ }
9
+ /** Standardowa interpolacja sześcienna (Catmull-Rom przez punkty → krzywe Béziera). */
10
+ function cubicPath(points) {
11
+ if (points.length < 3)
12
+ return linearPath(points);
13
+ let d = `M ${n(points[0].x)} ${n(points[0].y)}`;
14
+ for (let i = 0; i < points.length - 1; i++) {
15
+ const p0 = points[i - 1] ?? points[i];
16
+ const p1 = points[i];
17
+ const p2 = points[i + 1];
18
+ const p3 = points[i + 2] ?? p2;
19
+ const c1x = p1.x + (p2.x - p0.x) / 6;
20
+ const c1y = p1.y + (p2.y - p0.y) / 6;
21
+ const c2x = p2.x - (p3.x - p1.x) / 6;
22
+ const c2y = p2.y - (p3.y - p1.y) / 6;
23
+ d += ` C ${n(c1x)} ${n(c1y)}, ${n(c2x)} ${n(c2y)}, ${n(p2.x)} ${n(p2.y)}`;
24
+ }
25
+ return d;
26
+ }
27
+ /**
28
+ * Monotoniczna interpolacja sześcienna (Fritsch–Carlson).
29
+ * Styczne przycinane tak, by krzywa nie przestrzelała ekstremów danych.
30
+ * Liczona względem indeksu punktu (równe odstępy w X, typowe dla osi kategorii).
31
+ */
32
+ function monotonePath(points) {
33
+ const size = points.length;
34
+ if (size < 3)
35
+ return linearPath(points);
36
+ const dx = [];
37
+ const dy = [];
38
+ const slope = [];
39
+ for (let i = 0; i < size - 1; i++) {
40
+ dx[i] = points[i + 1].x - points[i].x;
41
+ dy[i] = points[i + 1].y - points[i].y;
42
+ slope[i] = dy[i] / (dx[i] || 1);
43
+ }
44
+ // Styczne w węzłach (m).
45
+ const m = new Array(size);
46
+ m[0] = slope[0];
47
+ m[size - 1] = slope[size - 2];
48
+ for (let i = 1; i < size - 1; i++) {
49
+ if (slope[i - 1] * slope[i] <= 0) {
50
+ m[i] = 0; // lokalne ekstremum → styczna pozioma
51
+ }
52
+ else {
53
+ m[i] = (slope[i - 1] + slope[i]) / 2;
54
+ }
55
+ }
56
+ // Ograniczenie Fritsch–Carlson.
57
+ for (let i = 0; i < size - 1; i++) {
58
+ if (slope[i] === 0) {
59
+ m[i] = 0;
60
+ m[i + 1] = 0;
61
+ continue;
62
+ }
63
+ const a = m[i] / slope[i];
64
+ const b = m[i + 1] / slope[i];
65
+ const h = Math.hypot(a, b);
66
+ if (h > 3) {
67
+ const t = 3 / h;
68
+ m[i] = t * a * slope[i];
69
+ m[i + 1] = t * b * slope[i];
70
+ }
71
+ }
72
+ let d = `M ${n(points[0].x)} ${n(points[0].y)}`;
73
+ for (let i = 0; i < size - 1; i++) {
74
+ const c1x = points[i].x + dx[i] / 3;
75
+ const c1y = points[i].y + (m[i] * dx[i]) / 3;
76
+ const c2x = points[i + 1].x - dx[i] / 3;
77
+ const c2y = points[i + 1].y - (m[i + 1] * dx[i]) / 3;
78
+ d += ` C ${n(c1x)} ${n(c1y)}, ${n(c2x)} ${n(c2y)}, ${n(points[i + 1].x)} ${n(points[i + 1].y)}`;
79
+ }
80
+ return d;
81
+ }
82
+ /** Ścieżka linii dla wybranego trybu interpolacji. */
83
+ export function linePath(points, mode = 'linear') {
84
+ if (points.length === 0)
85
+ return '';
86
+ if (points.length === 1)
87
+ return `M ${n(points[0].x)} ${n(points[0].y)}`;
88
+ switch (mode) {
89
+ case 'cubic':
90
+ return cubicPath(points);
91
+ case 'cubic-monotonic':
92
+ return monotonePath(points);
93
+ default:
94
+ return linearPath(points);
95
+ }
96
+ }
97
+ /** Ścieżka obszaru pod linią (domknięta do `baselineY`). */
98
+ export function areaPath(points, baselineY, mode = 'linear') {
99
+ if (points.length === 0)
100
+ return '';
101
+ const top = linePath(points, mode);
102
+ const first = points[0];
103
+ const last = points.at(-1);
104
+ return `${top} L ${n(last.x)} ${n(baselineY)} L ${n(first.x)} ${n(baselineY)} Z`;
105
+ }
@@ -0,0 +1,18 @@
1
+ import type { KptPoint } from './types.ts';
2
+ export interface RadarAxis {
3
+ /** Punkt na obwodzie (koniec osi). */
4
+ end: KptPoint;
5
+ angle: number;
6
+ labelIndex: number;
7
+ }
8
+ export interface RadarGrid {
9
+ /** Poziomy siatki (pierścienie) jako ścieżki wielokątów. */
10
+ rings: string[];
11
+ axes: RadarAxis[];
12
+ }
13
+ /** Siatka radaru: `levels` koncentrycznych wielokątów + osie do etykiet. */
14
+ export declare function radarGrid(count: number, cx: number, cy: number, radius: number, levels?: number): RadarGrid;
15
+ /** Punkty wielokąta serii (wartość → promień, skalowane do `maxValue`). */
16
+ export declare function radarPoints(values: number[], cx: number, cy: number, radius: number, maxValue: number): KptPoint[];
17
+ /** Zamknięta ścieżka wielokąta łącząca punkty. */
18
+ export declare function polygonPath(points: KptPoint[]): string;
package/dist/radar.js ADDED
@@ -0,0 +1,33 @@
1
+ /*
2
+ * Geometria wykresu radarowego: osie promieniowe + wielokąty serii.
3
+ */
4
+ import { polarToCartesian } from "./arc.js";
5
+ /** Siatka radaru: `levels` koncentrycznych wielokątów + osie do etykiet. */
6
+ export function radarGrid(count, cx, cy, radius, levels = 4) {
7
+ const axes = [];
8
+ const step = (Math.PI * 2) / Math.max(1, count);
9
+ for (let i = 0; i < count; i++) {
10
+ const angle = i * step;
11
+ axes.push({ angle, labelIndex: i, end: polarToCartesian(cx, cy, radius, angle) });
12
+ }
13
+ const rings = [];
14
+ for (let l = 1; l <= levels; l++) {
15
+ const r = (radius * l) / levels;
16
+ rings.push(polygonPath(axes.map((a) => polarToCartesian(cx, cy, r, a.angle))));
17
+ }
18
+ return { rings, axes };
19
+ }
20
+ /** Punkty wielokąta serii (wartość → promień, skalowane do `maxValue`). */
21
+ export function radarPoints(values, cx, cy, radius, maxValue) {
22
+ const count = values.length;
23
+ const step = (Math.PI * 2) / Math.max(1, count);
24
+ const max = maxValue || 1;
25
+ return values.map((v, i) => polarToCartesian(cx, cy, (Math.max(0, v) / max) * radius, i * step));
26
+ }
27
+ /** Zamknięta ścieżka wielokąta łącząca punkty. */
28
+ export function polygonPath(points) {
29
+ if (points.length === 0)
30
+ return '';
31
+ const nf = (v) => (Number.isInteger(v) ? String(v) : v.toFixed(3));
32
+ return points.map((p, i) => `${i === 0 ? 'M' : 'L'} ${nf(p.x)} ${nf(p.y)}`).join(' ') + ' Z';
33
+ }
@@ -0,0 +1,29 @@
1
+ /** Zakres [min, max] tablicy liczb (0..0 dla pustej). */
2
+ export declare function extent(values: number[]): [number, number];
3
+ /** Interpolacja liniowa domeny → zakresu (np. wartość → współrzędna piksela). */
4
+ export declare function linearScale(domainMin: number, domainMax: number, rangeMin: number, rangeMax: number): (value: number) => number;
5
+ export interface NiceScale {
6
+ min: number;
7
+ max: number;
8
+ step: number;
9
+ ticks: number[];
10
+ }
11
+ /**
12
+ * „Ładna" skala obejmująca [dataMin, dataMax] z ~`maxTicks` podziałkami.
13
+ * Wynikowy zakres jest rozszerzony do równych kroków; zawsze zawiera 0,
14
+ * gdy dane są jednoznakowe (typowe dla słupków/linii wartościowych).
15
+ */
16
+ export declare function niceScale(dataMin: number, dataMax: number, maxTicks?: number): NiceScale;
17
+ export interface BandScale {
18
+ /** Lewy/górny brzeg pasma dla danego indeksu kategorii. */
19
+ start: (index: number) => number;
20
+ /** Szerokość pojedynczego pasma kategorii. */
21
+ bandwidth: number;
22
+ /** Środek pasma dla danego indeksu (np. pozycja punktu linii). */
23
+ center: (index: number) => number;
24
+ }
25
+ /**
26
+ * Skala pasmowa: dzieli [rangeStart, rangeEnd] na `count` równych pasm
27
+ * z marginesem `padding` (0..1 udziału pasma) po bokach i między pasmami.
28
+ */
29
+ export declare function bandScale(count: number, rangeStart: number, rangeEnd: number, padding?: number): BandScale;
package/dist/scale.js ADDED
@@ -0,0 +1,90 @@
1
+ /*
2
+ * Skalowanie i „ładne" podziałki osi (auto-skala).
3
+ * Wszystkie funkcje czyste — bez stanu i DOM.
4
+ */
5
+ /** Zakres [min, max] tablicy liczb (0..0 dla pustej). */
6
+ export function extent(values) {
7
+ if (values.length === 0)
8
+ return [0, 0];
9
+ let min = values[0];
10
+ let max = values[0];
11
+ for (const v of values) {
12
+ if (v < min)
13
+ min = v;
14
+ if (v > max)
15
+ max = v;
16
+ }
17
+ return [min, max];
18
+ }
19
+ /** Interpolacja liniowa domeny → zakresu (np. wartość → współrzędna piksela). */
20
+ export function linearScale(domainMin, domainMax, rangeMin, rangeMax) {
21
+ const dSpan = domainMax - domainMin || 1;
22
+ const rSpan = rangeMax - rangeMin;
23
+ return (value) => rangeMin + ((value - domainMin) / dSpan) * rSpan;
24
+ }
25
+ /** Zaokrągla liczbę do „ładnej" wartości (1/2/5 × 10ⁿ). */
26
+ function niceNum(range, round) {
27
+ const exponent = Math.floor(Math.log10(range || 1));
28
+ const fraction = (range || 1) / 10 ** exponent;
29
+ return niceFraction(fraction, round) * 10 ** exponent;
30
+ }
31
+ /** Mantysa 1/2/5/10 — do najbliższej (`round`) albo w górę. */
32
+ function niceFraction(fraction, round) {
33
+ if (round) {
34
+ if (fraction < 1.5)
35
+ return 1;
36
+ if (fraction < 3)
37
+ return 2;
38
+ if (fraction < 7)
39
+ return 5;
40
+ return 10;
41
+ }
42
+ if (fraction <= 1)
43
+ return 1;
44
+ if (fraction <= 2)
45
+ return 2;
46
+ if (fraction <= 5)
47
+ return 5;
48
+ return 10;
49
+ }
50
+ /**
51
+ * „Ładna" skala obejmująca [dataMin, dataMax] z ~`maxTicks` podziałkami.
52
+ * Wynikowy zakres jest rozszerzony do równych kroków; zawsze zawiera 0,
53
+ * gdy dane są jednoznakowe (typowe dla słupków/linii wartościowych).
54
+ */
55
+ export function niceScale(dataMin, dataMax, maxTicks = 5) {
56
+ let lo = dataMin;
57
+ let hi = dataMax;
58
+ if (lo > 0)
59
+ lo = 0;
60
+ if (hi < 0)
61
+ hi = 0;
62
+ if (lo === hi) {
63
+ hi = lo + 1;
64
+ }
65
+ const range = niceNum(hi - lo, false);
66
+ const step = niceNum(range / Math.max(1, maxTicks - 1), true);
67
+ const niceMin = Math.floor(lo / step) * step;
68
+ const niceMax = Math.ceil(hi / step) * step;
69
+ const ticks = [];
70
+ // +1e-9: zabezpieczenie przed błędami zmiennoprzecinkowymi na krańcu pętli.
71
+ for (let t = niceMin; t <= niceMax + 1e-9; t += step) {
72
+ ticks.push(Math.abs(t) < 1e-9 ? 0 : t);
73
+ }
74
+ return { min: niceMin, max: niceMax, step, ticks };
75
+ }
76
+ /**
77
+ * Skala pasmowa: dzieli [rangeStart, rangeEnd] na `count` równych pasm
78
+ * z marginesem `padding` (0..1 udziału pasma) po bokach i między pasmami.
79
+ */
80
+ export function bandScale(count, rangeStart, rangeEnd, padding = 0.1) {
81
+ const span = rangeEnd - rangeStart;
82
+ const step = count > 0 ? span / count : span;
83
+ const bandwidth = step * (1 - padding);
84
+ const offset = (step - bandwidth) / 2;
85
+ return {
86
+ bandwidth,
87
+ start: (index) => rangeStart + index * step + offset,
88
+ center: (index) => rangeStart + index * step + step / 2,
89
+ };
90
+ }
@@ -0,0 +1,103 @@
1
+ export type KptChartType = 'line' | 'bar' | 'pie' | 'doughnut' | 'polarArea' | 'radar';
2
+ /** Tryb interpolacji linii dla wykresu liniowego. */
3
+ export type KptLineInterpolation = 'linear' | 'cubic' | 'cubic-monotonic';
4
+ /** Orientacja słupków. */
5
+ export type KptBarOrientation = 'vertical' | 'horizontal';
6
+ /** Pojedyncza seria danych. Kolejność wartości odpowiada `labels`. */
7
+ export interface KptChartSeries {
8
+ /** Nazwa serii (legenda, tooltip). */
9
+ name: string;
10
+ /** Wartości; długość zwykle równa liczbie etykiet. */
11
+ data: number[];
12
+ /** Kolor (CSS). Domyślnie z palety tokenów. */
13
+ color?: string;
14
+ }
15
+ export type KptLegendPosition = 'top' | 'bottom' | 'left' | 'right';
16
+ export type KptAlign = 'start' | 'center' | 'end';
17
+ export type KptPointStyle = 'circle' | 'rect' | 'rectRot' | 'triangle' | 'line';
18
+ export interface KptLegendTitle {
19
+ display?: boolean;
20
+ text?: string;
21
+ position?: KptAlign;
22
+ }
23
+ export interface KptLegendOptions {
24
+ display?: boolean;
25
+ position?: KptLegendPosition;
26
+ align?: KptAlign;
27
+ pointStyle?: KptPointStyle;
28
+ title?: KptLegendTitle;
29
+ }
30
+ export interface KptFont {
31
+ family?: string;
32
+ size?: number;
33
+ weight?: string | number;
34
+ }
35
+ export interface KptPadding {
36
+ top?: number;
37
+ bottom?: number;
38
+ }
39
+ export interface KptTitleOptions {
40
+ display?: boolean;
41
+ text?: string;
42
+ align?: KptAlign;
43
+ color?: string;
44
+ font?: KptFont;
45
+ padding?: KptPadding;
46
+ }
47
+ /** Kontekst przekazywany do formatera tooltipa. */
48
+ export interface KptTooltipContext {
49
+ series: string;
50
+ label: string;
51
+ value: number;
52
+ }
53
+ export interface KptTooltipOptions {
54
+ enabled?: boolean;
55
+ format?: (ctx: KptTooltipContext) => string;
56
+ }
57
+ export interface KptAnimationOptions {
58
+ enabled?: boolean;
59
+ /** Czas trwania w ms (domyślnie 400). */
60
+ duration?: number;
61
+ /** Opóźnienie startu w ms (domyślnie 0). */
62
+ delay?: number;
63
+ /** Przesunięcie kolejnych elementów w ms (`delay = index * stagger`). */
64
+ stagger?: number;
65
+ }
66
+ /** Pełna konfiguracja wykresu. Jeden kształt dla wszystkich typów. */
67
+ export interface KptChartConfig {
68
+ type: KptChartType;
69
+ /** Etykiety osi kategorii / wycinków. */
70
+ labels: string[];
71
+ series: KptChartSeries[];
72
+ /** Bar: orientacja słupków (domyślnie 'vertical'). */
73
+ orientation?: KptBarOrientation;
74
+ /** Line: tryb interpolacji (domyślnie 'linear'). */
75
+ interpolation?: KptLineInterpolation;
76
+ /** Line: wypełnienie obszaru pod linią. */
77
+ area?: boolean;
78
+ /** Line: punkty danych widoczne (domyślnie true). */
79
+ points?: boolean;
80
+ /** Line: pionowa prowadnica + podświetlona etykieta osi X przy hoverze punktu. */
81
+ crosshair?: boolean;
82
+ /** Doughnut/PolarArea/Radar: promień wewnętrzny 0..1 (doughnut, domyślnie 0.6). */
83
+ innerRadius?: number;
84
+ /** Bar: promień zaokrąglenia rogów w px (domyślnie 4). */
85
+ borderRadius?: number;
86
+ animation?: KptAnimationOptions;
87
+ legend?: KptLegendOptions;
88
+ title?: KptTitleOptions;
89
+ subtitle?: KptTitleOptions;
90
+ tooltip?: KptTooltipOptions;
91
+ }
92
+ /** Punkt w układzie SVG. */
93
+ export interface KptPoint {
94
+ x: number;
95
+ y: number;
96
+ }
97
+ /** Prostokąt obszaru rysowania (plot area). */
98
+ export interface KptRect {
99
+ x: number;
100
+ y: number;
101
+ width: number;
102
+ height: number;
103
+ }
package/dist/types.js ADDED
@@ -0,0 +1,5 @@
1
+ /*
2
+ * Rdzeń wykresów — czyste typy TypeScript (bez zależności od DOM/frameworka).
3
+ * Współdzielone przez warstwę Angular (Faza 1) i React (Faza 2).
4
+ */
5
+ export {};
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@konce-pt/chart",
3
+ "version": "0.8.0",
4
+ "description": "Chart geometry core for Koncept UI — scales, line and area paths, bar layout, pie and radar geometry. Framework-free TypeScript, zero runtime dependencies.",
5
+ "license": "MIT",
6
+ "author": "konce.pt",
7
+ "homepage": "https://ui.konce.pt/",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://gitlab.com/konce-pt/koncept-ui.git",
11
+ "directory": "packages/chart"
12
+ },
13
+ "bugs": {
14
+ "url": "https://gitlab.com/konce-pt/koncept-ui/-/issues"
15
+ },
16
+ "keywords": [
17
+ "charts",
18
+ "svg",
19
+ "data-visualization",
20
+ "design-system",
21
+ "koncept-ui",
22
+ "kpt"
23
+ ],
24
+ "type": "module",
25
+ "sideEffects": false,
26
+ "files": [
27
+ "dist"
28
+ ],
29
+ "module": "./dist/index.js",
30
+ "types": "./dist/index.d.ts",
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/index.d.ts",
34
+ "default": "./dist/index.js"
35
+ }
36
+ },
37
+ "devDependencies": {
38
+ "typescript": "~6.0.3"
39
+ },
40
+ "scripts": {
41
+ "build": "tsc -p tsconfig.build.json",
42
+ "test": "node --test \"src/**/*.test.ts\"",
43
+ "clean": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\""
44
+ }
45
+ }