@funnest/charts-viz 0.0.0-stage → 0.1.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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Funnest Charts
2
+ Copyright 2026 Funnest
3
+
4
+ This product includes software developed by the Funnest Charts project.
package/README.md CHANGED
@@ -1,3 +1,24 @@
1
- # Temporary Holding Version
1
+ # @funnest/charts-viz
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 웹과 React Native가 함께 쓰는 차트 계산
4
+
5
+ Platform-neutral chart math (scales, ticks, SVG paths, stacking) for web and React Native.
6
+
7
+ ```bash
8
+ npm i @funnest/charts-viz
9
+ ```
10
+
11
+ DOM을 쓰지 않는 순수 TypeScript예요. `@funnest/charts-react`의 SVG 컴포넌트가 이 계산을 쓰고, React Native(react-native-svg)에서도 같은 결과를 그릴 수 있어요.
12
+
13
+ ```ts
14
+ import { linearScale, linePath, ticks } from '@funnest/charts-viz';
15
+
16
+ const y = linearScale([0, 100], [200, 0]);
17
+ const d = linePath(values.map((v, i) => ({ x: i * 10, y: y(v) })), 'monotone');
18
+ ```
19
+
20
+ ## 링크
21
+
22
+ - 문서: https://charts.funnest.xyz/docs/
23
+ - GitHub: https://github.com/funnest-xyz/funnest-charts
24
+ - 라이선스: Apache-2.0
package/dist/data.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ /** One numeric series. `data[i]` lines up with x position i (null = gap). */
2
+ export interface SeriesData {
3
+ id: string;
4
+ data: readonly (number | null)[];
5
+ }
6
+ /** Min/max over the non-null values of every series (null when there is none). */
7
+ export declare function extent(series: readonly SeriesData[]): [number, number] | null;
8
+ /** Longest series length. */
9
+ export declare const maxLength: (series: readonly SeriesData[]) => number;
10
+ export interface StackedSeries {
11
+ id: string;
12
+ /** Lower edge per index (the sum of the series below). */
13
+ y0: number[];
14
+ /** Upper edge per index. */
15
+ y1: number[];
16
+ }
17
+ /**
18
+ * Stack series on top of each other. Positive values stack upward from 0, negative values
19
+ * downward, so mixed-sign data (P&L by strategy, inflow/outflow) stays readable.
20
+ */
21
+ export declare function stack(series: readonly SeriesData[]): StackedSeries[];
22
+ /** [min, max] of stacked series (always includes 0). */
23
+ export declare function stackedExtent(stacked: readonly StackedSeries[]): [number, number];
24
+ export interface PercentageSegment {
25
+ id: string;
26
+ value: number;
27
+ /** Share of the total, 0–1. */
28
+ fraction: number;
29
+ /** Cumulative start, 0–1. */
30
+ start: number;
31
+ }
32
+ /** Split a whole into shares (negative values count as 0). */
33
+ export declare function percentages(items: readonly {
34
+ id: string;
35
+ value: number;
36
+ }[]): PercentageSegment[];
37
+ /** Index of the x position nearest to `pixel`, given each index's pixel x (sorted ascending). */
38
+ export declare function nearestIndex(xs: readonly number[], pixel: number): number;
39
+ /**
40
+ * Change from the first non-null value to the last non-null value at or before `end`
41
+ * (for "+12.3% this month" headers; pass the scrubbed index as `end`).
42
+ */
43
+ export declare function seriesChange(data: readonly (number | null)[], end?: number): {
44
+ first: number;
45
+ last: number;
46
+ change: number;
47
+ percent: number;
48
+ } | null;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * @funnest/charts-viz — platform-neutral chart math.
3
+ *
4
+ * Pure TypeScript with no DOM access, so the same scales, ticks and SVG path strings
5
+ * drive the web components (@funnest/charts-react) and React Native (react-native-svg).
6
+ */
7
+ export { linearScale, bandScale, clamp, type LinearScale, type BandScale } from './scale';
8
+ export { niceStep, niceDomain, ticks, sampleIndices } from './ticks';
9
+ export { linePath, areaPath, barPath, segments, type XY, type Curve } from './path';
10
+ export { extent, maxLength, stack, stackedExtent, percentages, nearestIndex, seriesChange, type SeriesData, type StackedSeries, type PercentageSegment, } from './data';
11
+ export { DEFAULT_PALETTE, seriesColor } from './palette';
package/dist/index.js ADDED
@@ -0,0 +1,275 @@
1
+ // src/scale.ts
2
+ function linearScale(domain, range) {
3
+ const [d0, d1] = domain;
4
+ const [r0, r1] = range;
5
+ const span = d1 - d0;
6
+ const scale = ((v) => span === 0 ? (r0 + r1) / 2 : r0 + (v - d0) / span * (r1 - r0));
7
+ scale.invert = (p) => r1 === r0 ? d0 : d0 + (p - r0) / (r1 - r0) * span;
8
+ Object.assign(scale, { kind: "linear", domain: [d0, d1], range: [r0, r1] });
9
+ return scale;
10
+ }
11
+ function bandScale(count, range, padding = 0.2) {
12
+ const [r0, r1] = range;
13
+ const n = Math.max(1, count);
14
+ const step = (r1 - r0) / n;
15
+ const pad = clamp(padding, 0, 0.95);
16
+ const bandwidth = step * (1 - pad);
17
+ const scale = ((i) => r0 + i * step + (step - bandwidth) / 2);
18
+ scale.center = (i) => r0 + i * step + step / 2;
19
+ scale.invert = (p) => clamp(Math.floor((p - r0) / step), 0, n - 1);
20
+ Object.assign(scale, { kind: "band", count: n, range: [r0, r1], bandwidth, step });
21
+ return scale;
22
+ }
23
+ var clamp = (v, lo, hi) => v < lo ? lo : v > hi ? hi : v;
24
+
25
+ // src/ticks.ts
26
+ var STEPS = [1, 2, 2.5, 5, 10];
27
+ var round = (v) => Number.parseFloat(v.toPrecision(12));
28
+ function niceStep(min, max, count = 5) {
29
+ const span = Math.abs(max - min);
30
+ if (!Number.isFinite(span) || span === 0) return 1;
31
+ const raw = span / Math.max(1, count);
32
+ const mag = 10 ** Math.floor(Math.log10(raw));
33
+ const norm = raw / mag;
34
+ const step = STEPS.find((s) => s >= norm - 1e-9) ?? 10;
35
+ return round(step * mag);
36
+ }
37
+ function niceDomain(min, max, count = 5) {
38
+ if (min === max) {
39
+ const pad = min === 0 ? 1 : Math.abs(min) * 0.1;
40
+ return [round(min - pad), round(max + pad)];
41
+ }
42
+ const step = niceStep(min, max, count);
43
+ return [round(Math.floor(min / step + 1e-9) * step), round(Math.ceil(max / step - 1e-9) * step)];
44
+ }
45
+ function ticks(min, max, count = 5) {
46
+ if (!Number.isFinite(min) || !Number.isFinite(max)) return [];
47
+ if (min === max) return [min];
48
+ const lo = Math.min(min, max);
49
+ const hi = Math.max(min, max);
50
+ const step = niceStep(lo, hi, count);
51
+ const out = [];
52
+ const first = Math.ceil(lo / step - 1e-9);
53
+ for (let k = first; k * step <= hi + step * 1e-9; k++) out.push(round(k * step));
54
+ return out;
55
+ }
56
+ function sampleIndices(count, max) {
57
+ if (count <= 0) return [];
58
+ if (count <= max) return Array.from({ length: count }, (_, i) => i);
59
+ const every = Math.ceil(count / Math.max(1, max));
60
+ const out = [];
61
+ for (let i = 0; i < count; i += every) out.push(i);
62
+ return out;
63
+ }
64
+
65
+ // src/path.ts
66
+ var f = (n) => (Math.round(n * 100) / 100).toString();
67
+ function linePath(points, curve = "linear") {
68
+ const n = points.length;
69
+ if (n === 0) return "";
70
+ const p0 = points[0];
71
+ let d = `M${f(p0.x)},${f(p0.y)}`;
72
+ if (n === 1) return d;
73
+ switch (curve) {
74
+ case "monotone":
75
+ return d + monotoneSegments(points);
76
+ case "step":
77
+ for (let i = 1; i < n; i++) {
78
+ const a = points[i - 1];
79
+ const b = points[i];
80
+ d += `H${f((a.x + b.x) / 2)}V${f(b.y)}H${f(b.x)}`;
81
+ }
82
+ return d;
83
+ case "stepAfter":
84
+ for (let i = 1; i < n; i++) d += `H${f(points[i].x)}V${f(points[i].y)}`;
85
+ return d;
86
+ case "stepBefore":
87
+ for (let i = 1; i < n; i++) d += `V${f(points[i].y)}H${f(points[i].x)}`;
88
+ return d;
89
+ default:
90
+ for (let i = 1; i < n; i++) d += `L${f(points[i].x)},${f(points[i].y)}`;
91
+ return d;
92
+ }
93
+ }
94
+ function areaPath(top, baseline, curve = "linear") {
95
+ if (top.length === 0) return "";
96
+ const upper = linePath(top, curve);
97
+ if (typeof baseline === "number") {
98
+ const last = top[top.length - 1];
99
+ const first = top[0];
100
+ return `${upper}L${f(last.x)},${f(baseline)}L${f(first.x)},${f(baseline)}Z`;
101
+ }
102
+ const lower = linePath([...baseline].reverse(), curve).replace(/^M/, "L");
103
+ return `${upper}${lower}Z`;
104
+ }
105
+ function segments(values) {
106
+ const out = [];
107
+ let cur = null;
108
+ values.forEach((v, i) => {
109
+ if (v === null || v === void 0 || typeof v === "number" && !Number.isFinite(v)) {
110
+ cur = null;
111
+ return;
112
+ }
113
+ if (!cur) {
114
+ cur = { start: i, values: [] };
115
+ out.push(cur);
116
+ }
117
+ cur.values.push(v);
118
+ });
119
+ return out;
120
+ }
121
+ function barPath(x, width, baseY, valueY, radius = 0) {
122
+ const top = Math.min(baseY, valueY);
123
+ const h = Math.abs(valueY - baseY);
124
+ const r = Math.max(0, Math.min(radius, width / 2, h));
125
+ const x1 = x + width;
126
+ if (r === 0) return `M${f(x)},${f(top)}H${f(x1)}V${f(top + h)}H${f(x)}Z`;
127
+ if (valueY <= baseY) {
128
+ return `M${f(x)},${f(baseY)}V${f(top + r)}Q${f(x)},${f(top)} ${f(x + r)},${f(top)}H${f(x1 - r)}Q${f(x1)},${f(top)} ${f(x1)},${f(top + r)}V${f(baseY)}Z`;
129
+ }
130
+ const bottom = top + h;
131
+ return `M${f(x)},${f(baseY)}V${f(bottom - r)}Q${f(x)},${f(bottom)} ${f(x + r)},${f(bottom)}H${f(x1 - r)}Q${f(x1)},${f(bottom)} ${f(x1)},${f(bottom - r)}V${f(baseY)}Z`;
132
+ }
133
+ function monotoneSegments(p) {
134
+ const n = p.length;
135
+ const dx = [];
136
+ const slope = [];
137
+ for (let i = 0; i < n - 1; i++) {
138
+ const h = p[i + 1].x - p[i].x;
139
+ dx.push(h);
140
+ slope.push(h === 0 ? 0 : (p[i + 1].y - p[i].y) / h);
141
+ }
142
+ const t = new Array(n).fill(0);
143
+ t[0] = slope[0];
144
+ t[n - 1] = slope[n - 2];
145
+ for (let i = 1; i < n - 1; i++) {
146
+ const s0 = slope[i - 1];
147
+ const s1 = slope[i];
148
+ if (s0 * s1 <= 0) continue;
149
+ const h0 = dx[i - 1];
150
+ const h1 = dx[i];
151
+ const w1 = 2 * h1 + h0;
152
+ const w2 = h1 + 2 * h0;
153
+ t[i] = (w1 + w2) / (w1 / s0 + w2 / s1);
154
+ }
155
+ let d = "";
156
+ for (let i = 0; i < n - 1; i++) {
157
+ const a = p[i];
158
+ const b = p[i + 1];
159
+ const h = dx[i] / 3;
160
+ d += `C${f(a.x + h)},${f(a.y + t[i] * h)} ${f(b.x - h)},${f(b.y - t[i + 1] * h)} ${f(b.x)},${f(b.y)}`;
161
+ }
162
+ return d;
163
+ }
164
+
165
+ // src/data.ts
166
+ var isNum = (v) => v !== null && v !== void 0 && Number.isFinite(v);
167
+ function extent(series) {
168
+ let min = Infinity;
169
+ let max = -Infinity;
170
+ for (const s of series) {
171
+ for (const v of s.data) {
172
+ if (!isNum(v)) continue;
173
+ if (v < min) min = v;
174
+ if (v > max) max = v;
175
+ }
176
+ }
177
+ return min === Infinity ? null : [min, max];
178
+ }
179
+ var maxLength = (series) => series.reduce((m, s) => Math.max(m, s.data.length), 0);
180
+ function stack(series) {
181
+ const n = maxLength(series);
182
+ const pos = new Array(n).fill(0);
183
+ const neg = new Array(n).fill(0);
184
+ return series.map((s) => {
185
+ const y0 = [];
186
+ const y1 = [];
187
+ for (let i = 0; i < n; i++) {
188
+ const raw = s.data[i];
189
+ const v = isNum(raw) ? raw : 0;
190
+ const base = v >= 0 ? pos : neg;
191
+ y0.push(base[i]);
192
+ base[i] = base[i] + v;
193
+ y1.push(base[i]);
194
+ }
195
+ return { id: s.id, y0, y1 };
196
+ });
197
+ }
198
+ function stackedExtent(stacked) {
199
+ let min = 0;
200
+ let max = 0;
201
+ for (const s of stacked) {
202
+ for (let i = 0; i < s.y1.length; i++) {
203
+ min = Math.min(min, s.y0[i], s.y1[i]);
204
+ max = Math.max(max, s.y0[i], s.y1[i]);
205
+ }
206
+ }
207
+ return [min, max];
208
+ }
209
+ function percentages(items) {
210
+ const total = items.reduce((t, i) => t + Math.max(0, i.value), 0);
211
+ let start = 0;
212
+ return items.map((i) => {
213
+ const fraction = total > 0 ? Math.max(0, i.value) / total : 0;
214
+ const seg = { id: i.id, value: i.value, fraction, start };
215
+ start += fraction;
216
+ return seg;
217
+ });
218
+ }
219
+ function nearestIndex(xs, pixel) {
220
+ if (xs.length === 0) return -1;
221
+ let lo = 0;
222
+ let hi = xs.length - 1;
223
+ while (hi - lo > 1) {
224
+ const mid = lo + hi >> 1;
225
+ if (xs[mid] <= pixel) lo = mid;
226
+ else hi = mid;
227
+ }
228
+ return Math.abs(xs[hi] - pixel) < Math.abs(xs[lo] - pixel) ? hi : lo;
229
+ }
230
+ function seriesChange(data, end = data.length - 1) {
231
+ let first = null;
232
+ for (const v of data) {
233
+ if (isNum(v)) {
234
+ first = v;
235
+ break;
236
+ }
237
+ }
238
+ let last = null;
239
+ for (let i = Math.min(end, data.length - 1); i >= 0; i--) {
240
+ const v = data[i];
241
+ if (isNum(v)) {
242
+ last = v;
243
+ break;
244
+ }
245
+ }
246
+ if (first === null || last === null) return null;
247
+ const change = last - first;
248
+ return { first, last, change, percent: first === 0 ? 0 : change / Math.abs(first) * 100 };
249
+ }
250
+
251
+ // src/palette.ts
252
+ var DEFAULT_PALETTE = ["#6C4DFF", "#F59E0B", "#14B8A6", "#EC4899", "#0EA5E9", "#84CC16", "#A16207", "#64748B"];
253
+ var seriesColor = (index, palette = DEFAULT_PALETTE) => palette[(index % palette.length + palette.length) % palette.length];
254
+ export {
255
+ DEFAULT_PALETTE,
256
+ areaPath,
257
+ bandScale,
258
+ barPath,
259
+ clamp,
260
+ extent,
261
+ linePath,
262
+ linearScale,
263
+ maxLength,
264
+ nearestIndex,
265
+ niceDomain,
266
+ niceStep,
267
+ percentages,
268
+ sampleIndices,
269
+ segments,
270
+ seriesChange,
271
+ seriesColor,
272
+ stack,
273
+ stackedExtent,
274
+ ticks
275
+ };
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Default categorical colors: Funnest violet first, then hues chosen to stay apart from
3
+ * each other and from the up/down colors (red/blue in Korea, green/red elsewhere).
4
+ */
5
+ export declare const DEFAULT_PALETTE: readonly ['#6C4DFF', '#F59E0B', '#14B8A6', '#EC4899', '#0EA5E9', '#84CC16', '#A16207', '#64748B'];
6
+ export declare const seriesColor: (index: number, palette?: readonly string[]) => string;
package/dist/path.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ export interface XY {
2
+ x: number;
3
+ y: number;
4
+ }
5
+ export type Curve = 'linear' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter';
6
+ /**
7
+ * SVG path data through the points. Works for web <path d> and react-native-svg alike.
8
+ * 'monotone' is the Fritsch–Carlson cubic: smooth, but never overshoots the data
9
+ * (no fake highs/lows between samples — important for price charts).
10
+ */
11
+ export declare function linePath(points: readonly XY[], curve?: Curve): string;
12
+ /**
13
+ * Closed area between the `top` line and either a flat `baseline` y or a `bottom` line
14
+ * (same length as `top`, used for stacked areas / bands).
15
+ */
16
+ export declare function areaPath(top: readonly XY[], baseline: number | readonly XY[], curve?: Curve): string;
17
+ /** Split a series with gaps (null / NaN) into continuous runs. */
18
+ export declare function segments<T>(values: readonly (T | null | undefined)[]): {
19
+ start: number;
20
+ values: T[];
21
+ }[];
22
+ /**
23
+ * Bar from `baseY` to `valueY` (pixels), `radius` rounding only the end away from the
24
+ * baseline — so negative bars round at the bottom.
25
+ */
26
+ export declare function barPath(x: number, width: number, baseY: number, valueY: number, radius?: number): string;
@@ -0,0 +1,27 @@
1
+ /** A continuous scale mapping a numeric domain onto a pixel range. */
2
+ export interface LinearScale {
3
+ readonly kind: 'linear';
4
+ readonly domain: readonly [number, number];
5
+ readonly range: readonly [number, number];
6
+ (value: number): number;
7
+ invert(pixel: number): number;
8
+ }
9
+ export declare function linearScale(domain: readonly [number, number], range: readonly [number, number]): LinearScale;
10
+ /** A categorical scale: `count` equal bands across the range, each with inner padding. */
11
+ export interface BandScale {
12
+ readonly kind: 'band';
13
+ readonly count: number;
14
+ readonly range: readonly [number, number];
15
+ /** Width of one bar (band minus padding). */
16
+ readonly bandwidth: number;
17
+ /** Distance between band starts. */
18
+ readonly step: number;
19
+ /** Left edge of the bar for band `i`. */
20
+ (index: number): number;
21
+ /** Center of band `i`. */
22
+ center(index: number): number;
23
+ /** Band index under a pixel, clamped to [0, count-1]. */
24
+ invert(pixel: number): number;
25
+ }
26
+ export declare function bandScale(count: number, range: readonly [number, number], padding?: number): BandScale;
27
+ export declare const clamp: (v: number, lo: number, hi: number) => number;
@@ -0,0 +1,11 @@
1
+ /** The "nice" step (1, 2, 2.5 or 5 × 10ⁿ) giving about `count` intervals over [min, max]. */
2
+ export declare function niceStep(min: number, max: number, count?: number): number;
3
+ /** Expand [min, max] outward to multiples of a nice step. */
4
+ export declare function niceDomain(min: number, max: number, count?: number): [number, number];
5
+ /** Nice tick values inside [min, max] (inclusive). */
6
+ export declare function ticks(min: number, max: number, count?: number): number[];
7
+ /**
8
+ * Pick at most `max` evenly spread indices out of `count` (for category / time labels),
9
+ * always keeping the first one.
10
+ */
11
+ export declare function sampleIndices(count: number, max: number): number[];
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@funnest/charts-viz",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Platform-neutral chart math (scales, ticks, paths, scrubbing) shared by Funnest Charts web and React Native components",
5
+ "keywords": [
6
+ "chart",
7
+ "svg",
8
+ "react-native",
9
+ "sparkline"
10
+ ],
11
+ "license": "Apache-2.0",
12
+ "author": "Funnest",
13
+ "homepage": "https://charts.funnest.xyz",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/funnest-xyz/funnest-charts.git",
17
+ "directory": "packages/viz"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/funnest-xyz/funnest-charts/issues"
21
+ },
22
+ "type": "module",
23
+ "sideEffects": false,
24
+ "main": "./dist/index.js",
25
+ "types": "./dist/index.d.ts",
26
+ "exports": {
27
+ ".": {
28
+ "funnest-source": "./src/index.ts",
29
+ "types": "./dist/index.d.ts",
30
+ "import": "./dist/index.js"
31
+ }
32
+ },
33
+ "files": [
34
+ "dist",
35
+ "README.md",
36
+ "LICENSE",
37
+ "NOTICE"
38
+ ],
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "scripts": {
43
+ "build": "tsup src/index.ts --format esm --clean && tsc -p tsconfig.build.json",
44
+ "typecheck": "tsc -p tsconfig.json"
45
+ }
6
46
  }