nitro-ui-charts 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 +21 -0
- package/Package.swift +107 -0
- package/README.md +191 -2
- package/android/build.gradle +4 -0
- package/android/src/main/java/com/margelo/nitro/charts/ChartAnimator.kt +145 -0
- package/android/src/main/java/com/margelo/nitro/charts/ChartContainerView.kt +722 -0
- package/android/src/main/java/com/margelo/nitro/charts/ChartLayout.kt +261 -0
- package/android/src/main/java/com/margelo/nitro/charts/ChartOverlayView.kt +243 -0
- package/android/src/main/java/com/margelo/nitro/charts/ChartPainter.kt +445 -0
- package/android/src/main/java/com/margelo/nitro/charts/ChartScene.kt +417 -0
- package/android/src/main/java/com/margelo/nitro/charts/HybridNativeChartView.kt +97 -0
- package/ios/ChartAccessibilityDescriptor.swift +43 -0
- package/ios/ChartAnimator.swift +163 -0
- package/ios/ChartCanvasView.swift +619 -0
- package/ios/ChartLayout.swift +256 -0
- package/ios/ChartOverlayView.swift +259 -0
- package/ios/ChartPainter.swift +470 -0
- package/ios/ChartScene.swift +713 -0
- package/ios/ChartStyle.swift +91 -0
- package/ios/HybridNativeChartView.swift +84 -0
- package/nitro.json +13 -0
- package/nitrogen/generated/.gitattributes +1 -0
- package/nitrogen/generated/android/NitroCharts+autolinking.cmake +30 -0
- package/nitrogen/generated/android/NitroCharts+autolinking.gradle +10 -0
- package/nitrogen/generated/android/NitroChartsOnLoad.cpp +24 -0
- package/nitrogen/generated/android/c++/JCallback_void_double_double.cpp +56 -0
- package/nitrogen/generated/android/c++/JCallback_void_double_double_double.cpp +56 -0
- package/nitrogen/generated/android/c++/JCallback_void_double_double_double_double_double_double.cpp +56 -0
- package/nitrogen/generated/android/c++/JHybridNativeChartViewSpec.cpp +139 -0
- package/nitrogen/generated/android/c++/include/NitroCharts/private/JCallback_void_double_double.hpp +55 -0
- package/nitrogen/generated/android/c++/include/NitroCharts/private/JCallback_void_double_double_double.hpp +55 -0
- package/nitrogen/generated/android/c++/include/NitroCharts/private/JCallback_void_double_double_double_double_double_double.hpp +55 -0
- package/nitrogen/generated/android/c++/include/NitroCharts/private/JHybridNativeChartViewSpec.hpp +107 -0
- package/nitrogen/generated/android/c++/include/NitroCharts/private/JHybridNativeChartViewSpecJavaPart.hpp +27 -0
- package/nitrogen/generated/android/include/NitroCharts/private/NitroChartsOnLoad.hpp +13 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/charts/Callback_void_double_double.kt +69 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/charts/Callback_void_double_double_double.kt +69 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/charts/Callback_void_double_double_double_double_double_double.kt +69 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/charts/HybridNativeChartViewSpec.kt +120 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/charts/NitroChartsOnLoad.kt +22 -0
- package/nitrogen/generated/apple/NitroCharts-Swift-Cxx-Bridge.cpp +104 -0
- package/nitrogen/generated/apple/NitroChartsAppleCxx/NitroChartsAppleCxx.cpp +9 -0
- package/nitrogen/generated/apple/NitroChartsAppleCxx/include/NitroChartsAppleCxx/NitroChartsAppleCxx.h +98 -0
- package/nitrogen/generated/apple/NitroChartsAutolinking.cpp +20 -0
- package/nitrogen/generated/apple/NitroChartsAutolinking.mm +24 -0
- package/nitrogen/generated/apple/c++/HybridNativeChartViewSpecSwift.cpp +111 -0
- package/nitrogen/generated/apple/c++/HybridNativeChartViewSpec_cxx-Swift.cpp +28 -0
- package/nitrogen/generated/apple/c++/include/NitroCharts/NitroChartsAutolinking.hpp +13 -0
- package/nitrogen/generated/apple/c++/include/NitroCharts/private/HybridNativeChartViewSpecSwift.hpp +84 -0
- package/nitrogen/generated/apple/c++/include/NitroCharts/private/HybridNativeChartViewSpec_cxx-Swift.hpp +23 -0
- package/nitrogen/generated/apple/c++/include/NitroCharts/private/NitroCharts-Swift-Cxx-Umbrella.hpp +54 -0
- package/nitrogen/generated/apple/c++/include/module.modulemap +12 -0
- package/nitrogen/generated/apple/swift/Callback_void_double_double.swift +60 -0
- package/nitrogen/generated/apple/swift/Callback_void_double_double_double.swift +60 -0
- package/nitrogen/generated/apple/swift/Callback_void_double_double_double_double_double_double.swift +60 -0
- package/nitrogen/generated/apple/swift/HybridNativeChartViewSpec.swift +73 -0
- package/nitrogen/generated/apple/swift/HybridNativeChartViewSpec_cxx.swift +225 -0
- package/nitrogen/generated/apple/swift/NitroCharts+ForeignTypeMetadata.swift +34 -0
- package/nitrogen/generated/apple/swift/Promise_void.swift +100 -0
- package/nitrogen/generated/hybrid-classes.json +19 -0
- package/nitrogen/generated/shared/c++/NitroChartsCxxModule.cpp +2 -0
- package/nitrogen/generated/shared/c++/include/NitroCharts/NitroChartsCxxModule.hpp +2 -0
- package/nitrogen/generated/shared/javascript/NativeChartView.cjs +19 -0
- package/nitrogen/generated/shared/javascript/NativeChartView.d.cts +9 -0
- package/package.json +112 -4
- package/src/CartesianChart.tsx +331 -0
- package/src/Legend.tsx +50 -0
- package/src/NativeChartViewHost.ts +14 -0
- package/src/PieChart.tsx +164 -0
- package/src/Sparkline.tsx +54 -0
- package/src/chart/accessors.ts +41 -0
- package/src/chart/cartesian.ts +1736 -0
- package/src/chart/deps.ts +30 -0
- package/src/chart/morph.ts +116 -0
- package/src/chart/pie.ts +212 -0
- package/src/chart/theme.ts +80 -0
- package/src/chart/types.ts +261 -0
- package/src/core/curves.ts +210 -0
- package/src/core/decimate.ts +154 -0
- package/src/core/format.ts +89 -0
- package/src/core/index.ts +11 -0
- package/src/core/path.ts +89 -0
- package/src/core/scales.ts +197 -0
- package/src/core/scene.ts +304 -0
- package/src/core/stack.ts +74 -0
- package/src/core/ticks.ts +139 -0
- package/src/core/time.ts +275 -0
- package/src/index.ts +34 -0
- package/src/marks.tsx +66 -0
- package/src/specs/NativeChartView.nitro.ts +75 -0
- package/src/useChartView.ts +203 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 nitro-ui-charts contributors
|
|
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/Package.swift
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// swift-tools-version: 6.4
|
|
2
|
+
|
|
3
|
+
import Foundation
|
|
4
|
+
import PackageDescription
|
|
5
|
+
|
|
6
|
+
let name = "NitroCharts"
|
|
7
|
+
let generated = "nitrogen/generated"
|
|
8
|
+
let nitroDependencies: [Target.Dependency] = [
|
|
9
|
+
.product(name: "NitroModules", package: "nitro-core"),
|
|
10
|
+
.product(name: "NitroUIRenderer", package: "nitro-ui-renderer"),
|
|
11
|
+
]
|
|
12
|
+
let cxxSettings: [CXXSetting] = [
|
|
13
|
+
.define("DEBUG", .when(configuration: .debug)),
|
|
14
|
+
.define("NDEBUG", .when(configuration: .release)),
|
|
15
|
+
.disableWarning("nullability-extension"),
|
|
16
|
+
]
|
|
17
|
+
let swiftSources = ["ios", "\(generated)/apple/swift"]
|
|
18
|
+
let bridgeSources = ["c++", "\(name)-Swift-Cxx-Bridge.cpp", "\(name)Autolinking.cpp"]
|
|
19
|
+
|
|
20
|
+
// Bare-host integration. Nitrogen generates the bindings; this manifest owns the targets.
|
|
21
|
+
// `nitro-ui prepare` copies this package into the app's `.nitro/native/`, beside `nitro-core` and
|
|
22
|
+
// `nitro-ui-renderer`: the relative paths below resolve there, as in every NitroUI package.
|
|
23
|
+
let package = Package(
|
|
24
|
+
name: name,
|
|
25
|
+
platforms: [.iOS(.v16), .macOS(.v13)],
|
|
26
|
+
products: [
|
|
27
|
+
.library(name: name, targets: ["\(name)Cxx", name, "\(name)SwiftBridge"])
|
|
28
|
+
],
|
|
29
|
+
dependencies: [
|
|
30
|
+
.package(path: "../nitro-core"),
|
|
31
|
+
.package(path: "../nitro-ui-renderer"),
|
|
32
|
+
],
|
|
33
|
+
targets: [
|
|
34
|
+
.target(
|
|
35
|
+
name: "\(name)Cxx",
|
|
36
|
+
dependencies: nitroDependencies,
|
|
37
|
+
path: "\(generated)/shared/c++",
|
|
38
|
+
exclude: ["include"],
|
|
39
|
+
publicHeadersPath: "include",
|
|
40
|
+
cxxSettings: cxxSettings
|
|
41
|
+
),
|
|
42
|
+
.target(
|
|
43
|
+
name: "\(name)AppleCxx",
|
|
44
|
+
dependencies: [.target(name: "\(name)Cxx")] + nitroDependencies,
|
|
45
|
+
path: "\(generated)/apple/\(name)AppleCxx",
|
|
46
|
+
cxxSettings: cxxSettings
|
|
47
|
+
),
|
|
48
|
+
.target(
|
|
49
|
+
name: name,
|
|
50
|
+
dependencies: [
|
|
51
|
+
.target(name: "\(name)AppleCxx"),
|
|
52
|
+
] + nitroDependencies,
|
|
53
|
+
path: ".",
|
|
54
|
+
exclude: excludes(in: ".", keeping: swiftSources),
|
|
55
|
+
sources: swiftSources,
|
|
56
|
+
cxxSettings: cxxSettings,
|
|
57
|
+
swiftSettings: [
|
|
58
|
+
.define("DEBUG", .when(configuration: .debug)),
|
|
59
|
+
// UIKit implementations run synchronously on the host's main thread.
|
|
60
|
+
.swiftLanguageMode(.v5),
|
|
61
|
+
.unsafeFlags(["-strict-concurrency=minimal"]),
|
|
62
|
+
.enableUpcomingFeature("InternalImportsByDefault"),
|
|
63
|
+
.enableUpcomingFeature("MemberImportVisibility"),
|
|
64
|
+
.interoperabilityMode(.Cxx),
|
|
65
|
+
.unsafeFlags(["-Xfrontend", "-clang-header-expose-decls=has-expose-attr-or-stdlib"]),
|
|
66
|
+
.unsafeFlags([
|
|
67
|
+
"-Xfrontend", "-clang-header-expose-module",
|
|
68
|
+
"-Xfrontend", "NitroModules=NitroModules-Swift.h",
|
|
69
|
+
]),
|
|
70
|
+
]
|
|
71
|
+
),
|
|
72
|
+
.target(
|
|
73
|
+
name: "\(name)SwiftBridge",
|
|
74
|
+
dependencies: [.target(name: name), .target(name: "\(name)AppleCxx")] + nitroDependencies,
|
|
75
|
+
path: "\(generated)/apple",
|
|
76
|
+
exclude: excludes(in: "\(generated)/apple", keeping: bridgeSources) + ["c++/include"],
|
|
77
|
+
sources: bridgeSources,
|
|
78
|
+
publicHeadersPath: "c++/include",
|
|
79
|
+
cxxSettings: cxxSettings + [
|
|
80
|
+
.unsafeFlags(["-I${GENERATED_MODULEMAP_DIR}", "-fno-modules"])
|
|
81
|
+
]
|
|
82
|
+
),
|
|
83
|
+
],
|
|
84
|
+
cxxLanguageStandard: .cxx20
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
func excludes(in path: String, keeping sources: [String]) -> [String] {
|
|
88
|
+
var parents: Set<String> = [""]
|
|
89
|
+
for source in sources {
|
|
90
|
+
var components = source.split(separator: "/").dropLast()
|
|
91
|
+
while !components.isEmpty {
|
|
92
|
+
parents.insert(components.joined(separator: "/"))
|
|
93
|
+
components = components.dropLast()
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
let root = URL(fileURLWithPath: Context.packageDirectory).appendingPathComponent(path)
|
|
97
|
+
return parents.sorted().flatMap { parent in
|
|
98
|
+
let entries =
|
|
99
|
+
(try? FileManager.default.contentsOfDirectory(
|
|
100
|
+
atPath: root.appendingPathComponent(parent).path)) ?? []
|
|
101
|
+
return entries.sorted().compactMap { entry in
|
|
102
|
+
let entryPath = parent.isEmpty ? entry : "\(parent)/\(entry)"
|
|
103
|
+
return entry.hasPrefix(".") || sources.contains(entryPath) || parents.contains(entryPath)
|
|
104
|
+
? nil : entryPath
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
package/README.md
CHANGED
|
@@ -1,3 +1,192 @@
|
|
|
1
|
-
#
|
|
1
|
+
# nitro-ui-charts
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Native charts for [NitroUI](https://github.com/margelo/nitro). Line, area, bar, scatter, bubble, candlestick, pie, donut and sparkline charts, drawn with Core Graphics on iOS and `Canvas` on Android.
|
|
4
|
+
|
|
5
|
+
- **Declarative marks.** Compose `<Line>`, `<Area>`, `<Bar>`, `<Scatter>`, `<Candlestick>`, `<ReferenceLine>` and `<ReferenceArea>` inside one chart, on one or two value axes.
|
|
6
|
+
- **Scrubbing.** A drag along the chart snaps to the nearest datum with a crosshair, markers, a callout and a haptic tick. A parent `ScrollView` keeps scrolling: by default the chart only takes drags along its axis.
|
|
7
|
+
- **Zoom and scroll.** Pinch, drag with momentum and double tap run natively at the display's frame rate.
|
|
8
|
+
- **Animation.** Every change animates from what is on screen, so a new range or a stacked/grouped switch morphs instead of jumping, even when interrupted. Spring, ease-out, ease-in-out or linear. Reduce Motion is respected.
|
|
9
|
+
- **Large data.** Lines and areas longer than the plot is wide are reduced with min–max (M4) decimation: every pixel column keeps its first, last, lowest and highest point, so peaks and dips survive.
|
|
10
|
+
- **Correct axes.** Ticks are round numbers (the d3 algorithm) and calendar steps on time axes (hours, days, months, years). Labels are measured natively, thinned evenly so they never overlap, and kept inside the view.
|
|
11
|
+
- **Accessibility.** Every chart has a spoken summary ("Revenue rises from $50.2K to $96.4K, between …") and can be stepped through value by value (VoiceOver adjustable, TalkBack slider). iOS also exposes an Audio Graph through `AXChartDescriptor`.
|
|
12
|
+
- **Light and dark themes**, right-to-left layout (`rtl`) and localized dates (`locale`).
|
|
13
|
+
|
|
14
|
+
## Install
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
bun add nitro-ui-charts
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Peer dependencies: `react` 19, `nitro-ui-renderer` 0.4 or later, and the `nitro-core` that renderer uses (the bindings are generated with Nitrogen `1.0.0-alpha.nightly.137`). The package ships TypeScript source and the generated native bindings; after installing, rebuild the app (`nitro-ui prepare`, then `nitro-ui ios` / `nitro-ui android`). The CLI copies each native package into `.nitro/native/`, next to `nitro-core` and `nitro-ui-renderer`, which is where `Package.swift` looks for them.
|
|
21
|
+
|
|
22
|
+
## Line and area
|
|
23
|
+
|
|
24
|
+
```tsx
|
|
25
|
+
import { CartesianChart, Area, ReferenceLine } from 'nitro-ui-charts'
|
|
26
|
+
|
|
27
|
+
// Outside the component: a function prop with a new identity rebuilds the chart.
|
|
28
|
+
const formatPrice = (v: number) => `$${v.toFixed(2)}`
|
|
29
|
+
|
|
30
|
+
<CartesianChart
|
|
31
|
+
data={prices}
|
|
32
|
+
x="date"
|
|
33
|
+
layout={{ height: 220 }}
|
|
34
|
+
yDomain={{ zero: false }}
|
|
35
|
+
onSelect={(s) => setPrice(s?.values[0]?.formatted ?? null)}
|
|
36
|
+
>
|
|
37
|
+
<Area y="close" name="Close" color="#16A34A" format={formatPrice} />
|
|
38
|
+
<ReferenceLine y={prices[0].close} label="Open" dash={[4, 4]} />
|
|
39
|
+
</CartesianChart>
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`x` and `y` take a field name or a function `(datum, index) => value`. Field names are cached per `data` array; functions are called on every rebuild. The x scale follows the data unless `xScale` says otherwise:
|
|
43
|
+
|
|
44
|
+
| x values | Without bars | With bars |
|
|
45
|
+
| --- | --- | --- |
|
|
46
|
+
| strings | category (`band`) | category |
|
|
47
|
+
| `Date`s | time | category (time with candlesticks) |
|
|
48
|
+
| numbers | linear | category |
|
|
49
|
+
|
|
50
|
+
`xScale` also takes `'log'`; `yScale` is `'linear'` or `'log'` (both value axes). Without a height or flex, a chart is 220 pt tall.
|
|
51
|
+
|
|
52
|
+
`null`, `undefined` and `NaN` values leave a gap (`connectGaps` draws across). Rows whose x is missing are skipped.
|
|
53
|
+
|
|
54
|
+
## Bars
|
|
55
|
+
|
|
56
|
+
```tsx
|
|
57
|
+
<CartesianChart data={revenue} x="month" layout={{ height: 220 }}>
|
|
58
|
+
<Bar y="ios" name="iOS" stack={stacked ? 'total' : undefined} radius={4} />
|
|
59
|
+
<Bar y="android" name="Android" stack={stacked ? 'total' : undefined} radius={4} />
|
|
60
|
+
</CartesianChart>
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Bars without `stack` are grouped. `stackOffset` is `'diverging'` for bars by default (negatives stack down) and `'none'` for areas; `'expand'` stacks to 100 % and `'silhouette'` centers the stack. `orientation="horizontal"` turns every mark sideways. `labels` prints values past the bar ends, or inside them with `labels={{ position: 'inside' }}`.
|
|
64
|
+
|
|
65
|
+
## Marks
|
|
66
|
+
|
|
67
|
+
Every series mark takes `name`, `color`, `axis` (`'y'`, or `'y2'` for a second value axis: on the right, or on top in a horizontal chart), `format` (callout and VoiceOver), `hidden` and `excludeFromSelection`.
|
|
68
|
+
|
|
69
|
+
| Mark | Props |
|
|
70
|
+
| --- | --- |
|
|
71
|
+
| `<Line>` | `y`, `width`, `dash`, `curve`, `connectGaps`, `points` (dots), `threshold={{ value, above, below }}` (colors the line on either side of a value). |
|
|
72
|
+
| `<Area>` | `y`, `y0` (a lower edge: a number or a field, for bands), `fill` (a color or `{ colors, positions }` gradient; a fading gradient by default), `fillOpacity`, `line`, `curve`, `connectGaps`, `stack`, `stackOffset`. |
|
|
73
|
+
| `<Bar>` | `y`, `fill`, `colors` (per bar), `radius`, `thickness`, `labels`, `base`, `stack`, `stackOffset`. |
|
|
74
|
+
| `<Scatter>` | `y`, `size` (a radius, or a field scaled by area into `sizeRange`, `[3, 14]` by default: bubbles), `shape` (`circle`, `square`, `diamond`, `triangle`), `colors`, `opacity`. |
|
|
75
|
+
| `<Candlestick>` | `open`, `high`, `low`, `close`, `upColor`, `downColor`, `thickness`, `wickWidth`, `ohlc` (ticks instead of bodies). |
|
|
76
|
+
| `<ReferenceLine>` | `y` (horizontal) or `x` (vertical), `label`, `labelPosition`, `color`, `width`, `dash`, `extendDomain` (default true). |
|
|
77
|
+
| `<ReferenceArea>` | `y1`/`y2` or `x1`/`x2`, `color`, `opacity`, `label`. |
|
|
78
|
+
|
|
79
|
+
Curves: `monotone` (default, never overshoots), `linear`, `natural`, `step`, `stepBefore`, `stepAfter`, `catmullRom`.
|
|
80
|
+
|
|
81
|
+
Mark components accept any data type; to check field names against your data, give the type: `<Line<Price> y="close" />`.
|
|
82
|
+
|
|
83
|
+
## Axes and domains
|
|
84
|
+
|
|
85
|
+
`xAxis`, `yAxis` and `y2Axis` take `hidden`, `position`, `tickCount`, `tickValues`, `format`, `grid`, `line`, `ticks`, `labelColor`, `labelSize`, `inside` (labels inside the plot, no gutter), `title`, `labelGap` and `size` (a fixed gutter). In a horizontal chart `xAxis` is the category axis on the left and `yAxis` the value axis along the bottom.
|
|
86
|
+
|
|
87
|
+
`xDomain`, `yDomain` and `y2Domain` take `min`, `max`, `zero`, `nice` and `padding`. Value axes include zero for bars and areas and round to ticks; the x axis runs edge to edge (rounded for scatter-only charts).
|
|
88
|
+
|
|
89
|
+
## Pie and donut
|
|
90
|
+
|
|
91
|
+
```tsx
|
|
92
|
+
import { PieChart } from 'nitro-ui-charts'
|
|
93
|
+
|
|
94
|
+
<PieChart data={languages} value="share" label="name" innerRadius={0.6} gap={2} legend layout={{ height: 220 }} />
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Tap or long-press a slice to select it: it grows and the callout shows its value and percentage (`onSelect` receives `{ index, datum, label, value, fraction }`). `gap` separates slices by an even gap in points at every radius. `startAngle`/`endAngle` (degrees clockwise from 12 o'clock; `-90` and `90` for a half donut), `sort`, `colors` and `format` complete it. `sliceLabels` prints percentages on slices of at least `minFraction` (0.06) of the total, with an optional `format` and `color`. `legend` (`true` or `'bottom'`, or `'top'`) lists the slices; tapping one hides it and the others grow to fill the circle.
|
|
98
|
+
|
|
99
|
+
## Sparkline
|
|
100
|
+
|
|
101
|
+
```tsx
|
|
102
|
+
<Sparkline data={closes} area baseline={closes[0]} layout={{ flex: 1, height: 36 }} />
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
A line (or `area`) over an array of numbers, with no axes and 2 pt insets. `baseline` draws a dashed reference line. `color`, `curve`, `width`, `animation` and `accessibilityLabel` are optional; it is not interactive unless `interactive`.
|
|
106
|
+
|
|
107
|
+
## Selection
|
|
108
|
+
|
|
109
|
+
```tsx
|
|
110
|
+
<CartesianChart selection={{ activation: 'pan', haptics: true, persist: false, callout: 'top' }} onSelect={…} />
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
- `activation`: `'pan'` (default: starts on a drag along the axis, so the page still scrolls), `'longPress'` (250 ms), or `'immediate'` (starts at touch down and keeps the touch: for charts outside a scroll view).
|
|
114
|
+
- `persist`: keep the selection after the finger lifts; a tap then selects.
|
|
115
|
+
- `callout`: `'top'` (pinned to the top of the chart, beside the selection), `'point'` (next to the datum) or `false` to drive your own UI from `onSelect`.
|
|
116
|
+
- `haptics`: a selection tick per change (default on). `selection={false}` turns scrubbing off.
|
|
117
|
+
- `onSelect` receives `{ index, datum, x, xLabel, values: [{ name, value, formatted, color }], position }`, or `null` when the selection clears. It runs synchronously on the main thread during the gesture: a header updated through a ref changes in the same frame.
|
|
118
|
+
- `ref.current.select(index | null)` selects a datum from code.
|
|
119
|
+
- Scatter-only charts snap in two dimensions, to the nearest point within 32 pt, and the callout always sits next to the point. They default to `activation: 'longPress'` and `persist: true`, so a tap selects a point and a second tap clears it.
|
|
120
|
+
- Zoomed in, a drag scrolls, so scrubbing starts with a long press.
|
|
121
|
+
|
|
122
|
+
### Range
|
|
123
|
+
|
|
124
|
+
```tsx
|
|
125
|
+
<CartesianChart selection={{ range: true }} onRangeSelect={(r) => …} />
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
Two fingers on the plot select everything between them. The callout shows each series' change, e.g. `-90 ms (−57.1%)`, and `onRangeSelect` receives `{ start, end, values: [{ name, color, from, to, change, changeRatio, formatted }] }`, then `null` when the fingers lift. With pinch zoom on, two fingers zoom instead.
|
|
129
|
+
|
|
130
|
+
## Zoom and scroll
|
|
131
|
+
|
|
132
|
+
```tsx
|
|
133
|
+
<CartesianChart zoom={{ initial: { start: 0.75, end: 1 } }} onViewportChange={(v) => …} />
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
Pinch along the x axis to zoom, drag to scroll (with momentum), double tap to zoom out. Native moves the window itself, at the display's frame rate, and reports each new window. JavaScript then rebuilds the scene for it: the value axis fits the visible data (`autoScaleY`), ticks match the zoom level and long series are decimated at the new resolution. Only the data near the window is drawn.
|
|
137
|
+
|
|
138
|
+
- `zoom`: `true` or `{ pinch, scroll, doubleTapReset, minPoints, autoScaleY, initial }`, all on by default; `minPoints` (4) limits how far it zooms in. `initial` is read once.
|
|
139
|
+
- `viewport={{ start, end }}` (fractions of the x domain, needs `zoom`) moves the window when it changes. Passing back what `onViewportChange` reported is safe: it does not interrupt the gesture.
|
|
140
|
+
- `ref.current.resetZoom()` animates back to the whole domain.
|
|
141
|
+
- A vertical drag on a zoomable chart still scrolls the page.
|
|
142
|
+
|
|
143
|
+
## Legend
|
|
144
|
+
|
|
145
|
+
`legend` (`true` or `'top'`, or `'bottom'`) adds a row of series names above the chart. Tapping an entry hides or shows its series; the others rescale and morph into place. Colors and the x axis stay as they were.
|
|
146
|
+
|
|
147
|
+
## Transitions
|
|
148
|
+
|
|
149
|
+
Every scene change animates from what is on screen. When points or bars are added or removed (a new time range, a live feed, a hidden series), they are matched by their x value, so the points that stay slide into place and the new ones grow in, instead of the whole chart cross-fading. `animation={{ duration, easing, damping }}` tunes it (450 ms spring with damping 0.9 by default); `animation={false}` turns it off.
|
|
150
|
+
|
|
151
|
+
## Styling
|
|
152
|
+
|
|
153
|
+
`colorScheme` follows the system by default. `theme` overrides any token of `lightTheme` / `darkTheme`: `palette`, `labelColor`, `labelSize`, `gridColor`, `gridWidth`, `gridDash`, `axisColor`, `crosshairColor`, `background`, `positive`, `negative`, `tooltipBackground`, `tooltipText`, `tooltipSecondaryText`. `insets` (top, right, bottom, left; `[8, 4, 0, 0]` by default) adds space around the plot; axis gutters are measured from the labels.
|
|
154
|
+
|
|
155
|
+
`locale` formats dates in the callout and on time axes with `Intl`. Numbers use `formatNumber` (exported, with `compact`, `prefix`, `suffix`, `signed` and separator options); pass `format` to a mark or an axis for other number formats.
|
|
156
|
+
|
|
157
|
+
Chart text (axis labels, value labels, the callout) follows the system text size: Dynamic Type on iOS, the font size setting on Android, up to twice the given size, and changes while the app runs. `allowFontScaling={false}` keeps the sizes as given.
|
|
158
|
+
|
|
159
|
+
## Performance
|
|
160
|
+
|
|
161
|
+
- The scene is rebuilt only when something it reads changes. Props are compared by content three levels deep, so inline objects and short arrays (`zoom={{ … }}`, `dash={[4, 4]}`, `theme`) are fine. Functions (`format`, accessor functions, `formatX`) compare by identity: define them outside the component or memoize them, or every parent render rebuilds the chart.
|
|
162
|
+
- Treat `data` as immutable and pass a new array when it changes. Columns, x positions, stacks, extents and decimation are cached per array; an array that grows in place is noticed by its length, an element changed in place is not.
|
|
163
|
+
- Zooming rebuilds the scene once per new window on the main thread, so that work is kept per window: the window's extent comes from block minima and maxima, coarser decimation levels are derived from one shared level, and only the data near the window is drawn. On a Mac without a JIT (close to Hermes), a 100,000-point line rebuilds in about 1 ms zoomed out and 5 ms zoomed in.
|
|
164
|
+
- Native measures label text once per string and font. A scroll or pinch frame only moves the measured labels to the new window; text is measured again only when JavaScript's scene for that window arrives. The Audio Graph descriptor is built only when VoiceOver asks for it.
|
|
165
|
+
|
|
166
|
+
## Using the engine directly
|
|
167
|
+
|
|
168
|
+
`nitro-ui-charts/core` exports the scale, tick, time, curve, path, stacking, decimation (`decimateMinMax`, `decimateLTTB`) and formatting code, plus `buildCartesian` and `buildPie`. It has no React or native dependency, so it can build a scene on any thread or in tests. See [docs/scene-format.md](docs/scene-format.md) for the scene the native views draw.
|
|
169
|
+
|
|
170
|
+
## Architecture
|
|
171
|
+
|
|
172
|
+
JavaScript turns the chart's props into a *scene*: a small JSON description (layers, axes, styles, interaction) plus one flat `number[]` of geometry in normalized plot space. The native view lays out axes with real text metrics, draws the layers, interpolates between scenes and runs every gesture. JavaScript hears about a gesture only when it changes something: a new selected datum, a new range, a new zoom window.
|
|
173
|
+
|
|
174
|
+
## Notes on NitroUI
|
|
175
|
+
|
|
176
|
+
- The first frame already has the right axes: the chart measures its native view in a layout effect (NitroUI sets native frames before layout effects run) and re-renders for the real plot size before anything is drawn.
|
|
177
|
+
- Selection callbacks run synchronously on the main thread, so a header updated from `onSelect` through a ref changes in the same frame. A React state update made there renders one task later.
|
|
178
|
+
- Charts inside a recycling `List` keep their state between rows: give each row's chart a `key` tied to its data.
|
|
179
|
+
|
|
180
|
+
## Development
|
|
181
|
+
|
|
182
|
+
```sh
|
|
183
|
+
bun install
|
|
184
|
+
bun test # engine tests (ticks, curves, stacking, decimation, builders)
|
|
185
|
+
bun run typecheck
|
|
186
|
+
bun run example:prepare
|
|
187
|
+
bun run example:ios # or example:android
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
## License
|
|
191
|
+
|
|
192
|
+
MIT
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
package com.margelo.nitro.charts
|
|
2
|
+
|
|
3
|
+
import kotlin.math.cos
|
|
4
|
+
import kotlin.math.exp
|
|
5
|
+
import kotlin.math.max
|
|
6
|
+
import kotlin.math.min
|
|
7
|
+
import kotlin.math.pow
|
|
8
|
+
import kotlin.math.sin
|
|
9
|
+
import kotlin.math.sqrt
|
|
10
|
+
|
|
11
|
+
/** A layer as drawn in one frame. */
|
|
12
|
+
internal class ChartDrawnLayer(val layer: ChartLayer, val values: DoubleArray, val opacity: Float)
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Interpolates layers between scenes, the same way as the iOS renderer: a layer animates from what
|
|
16
|
+
* is on screen, a new layer from its `from` numbers, other layers fade in, removed layers fade out.
|
|
17
|
+
*/
|
|
18
|
+
internal class ChartAnimator {
|
|
19
|
+
private class State(val layer: ChartLayer, val start: DoubleArray?, val target: DoubleArray, val fadesIn: Boolean)
|
|
20
|
+
private class Exiting(val layer: ChartLayer, val values: DoubleArray, val opacity: Float)
|
|
21
|
+
|
|
22
|
+
private var states: List<State> = emptyList()
|
|
23
|
+
private var exiting: List<Exiting> = emptyList()
|
|
24
|
+
private var startTime = 0L
|
|
25
|
+
private var duration = 0.0
|
|
26
|
+
private var easing = "easeOut"
|
|
27
|
+
private var damping = 0.9
|
|
28
|
+
var progress = 1.0
|
|
29
|
+
private set
|
|
30
|
+
|
|
31
|
+
val isRunning get() = progress < 1
|
|
32
|
+
|
|
33
|
+
fun setScene(scene: ChartScene, geometry: DoubleArray, nowNanos: Long, animated: Boolean) {
|
|
34
|
+
// The same numbers again (a scene that only changed styles or the selection): keep animating.
|
|
35
|
+
if (exiting.isEmpty() && states.size == scene.layers.size) {
|
|
36
|
+
val same = states.indices.all { i ->
|
|
37
|
+
val state = states[i]
|
|
38
|
+
val layer = scene.layers[i]
|
|
39
|
+
state.layer.key == layer.key && state.target.contentEquals(layer.data?.values(geometry) ?: DoubleArray(0))
|
|
40
|
+
}
|
|
41
|
+
if (same) {
|
|
42
|
+
states = states.indices.map { State(scene.layers[it], states[it].start, states[it].target, states[it].fadesIn) }
|
|
43
|
+
return
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
val current = drawnLayers()
|
|
47
|
+
val previous = current.filter { it.opacity > 0 }.associateBy { it.layer.key }
|
|
48
|
+
val matched = HashSet<String>()
|
|
49
|
+
states = scene.layers.map { layer ->
|
|
50
|
+
val target = layer.data?.values(geometry) ?: DoubleArray(0)
|
|
51
|
+
val old = previous[layer.key]
|
|
52
|
+
val from = layer.from?.values(geometry)
|
|
53
|
+
when {
|
|
54
|
+
// New items: JavaScript drew the old picture in the new structure.
|
|
55
|
+
layer.morph && from != null && compatible(from, target, layer.kind) -> {
|
|
56
|
+
if (old != null) matched.add(layer.key)
|
|
57
|
+
State(layer, from, target, false)
|
|
58
|
+
}
|
|
59
|
+
old != null && old.opacity >= 0.999f && compatible(old.values, target, layer.kind) -> {
|
|
60
|
+
matched.add(layer.key)
|
|
61
|
+
State(layer, old.values, target, false)
|
|
62
|
+
}
|
|
63
|
+
old != null && layer.kind == "labels" && old.opacity >= 0.999f -> {
|
|
64
|
+
matched.add(layer.key)
|
|
65
|
+
State(layer, null, target, false)
|
|
66
|
+
}
|
|
67
|
+
else -> {
|
|
68
|
+
if (old == null && from != null && compatible(from, target, layer.kind)) State(layer, from, target, false)
|
|
69
|
+
else State(layer, null, target, old != null || animated)
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
exiting = current.filter { it.opacity > 0.01f && it.layer.key !in matched }.map { Exiting(it.layer, it.values, it.opacity) }
|
|
74
|
+
duration = if (animated) max(0.0, scene.duration / 1000) else 0.0
|
|
75
|
+
easing = scene.easing
|
|
76
|
+
damping = scene.damping
|
|
77
|
+
startTime = nowNanos
|
|
78
|
+
progress = if (duration > 0) 0.0 else 1.0
|
|
79
|
+
if (duration == 0.0) exiting = emptyList()
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
fun tick(nowNanos: Long): Boolean {
|
|
83
|
+
if (duration <= 0) {
|
|
84
|
+
progress = 1.0
|
|
85
|
+
exiting = emptyList()
|
|
86
|
+
return false
|
|
87
|
+
}
|
|
88
|
+
progress = ((nowNanos - startTime) / 1e9 / duration).coerceIn(0.0, 1.0)
|
|
89
|
+
if (progress >= 1) exiting = emptyList()
|
|
90
|
+
return progress < 1
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
fun drawnLayers(): List<ChartDrawnLayer> {
|
|
94
|
+
val eased = ease(progress)
|
|
95
|
+
val out = ArrayList<ChartDrawnLayer>(exiting.size + states.size)
|
|
96
|
+
for (e in exiting) out.add(ChartDrawnLayer(e.layer, e.values, e.opacity * (1 - progress).toFloat()))
|
|
97
|
+
for (s in states) {
|
|
98
|
+
val start = s.start
|
|
99
|
+
val values = if (start != null && progress < 1 && start.size == s.target.size) {
|
|
100
|
+
DoubleArray(s.target.size) { i ->
|
|
101
|
+
val a = start[i]
|
|
102
|
+
val b = s.target[i]
|
|
103
|
+
if (a.isFinite() && b.isFinite()) a + (b - a) * eased else b
|
|
104
|
+
}
|
|
105
|
+
} else s.target
|
|
106
|
+
out.add(ChartDrawnLayer(s.layer, values, if (s.fadesIn) min(1.0, progress * 1.6).toFloat() else 1f))
|
|
107
|
+
}
|
|
108
|
+
return out
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
private fun compatible(a: DoubleArray, b: DoubleArray, kind: String): Boolean {
|
|
112
|
+
if (a.size != b.size || a.isEmpty()) return false
|
|
113
|
+
if (kind != "path") return true
|
|
114
|
+
var i = 0
|
|
115
|
+
while (i < a.size) {
|
|
116
|
+
if (a[i] != b[i]) return false
|
|
117
|
+
i += when (a[i].toInt()) {
|
|
118
|
+
0, 1 -> 3
|
|
119
|
+
2 -> 7
|
|
120
|
+
3 -> 1
|
|
121
|
+
else -> return false
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return true
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
private fun ease(t: Double): Double {
|
|
128
|
+
if (t >= 1) return 1.0
|
|
129
|
+
return when (easing) {
|
|
130
|
+
"linear" -> t
|
|
131
|
+
"easeInOut" -> if (t < 0.5) 4 * t * t * t else 1 - (-2 * t + 2).pow(3) / 2
|
|
132
|
+
"spring" -> {
|
|
133
|
+
val zeta = damping.coerceIn(0.05, 1.0)
|
|
134
|
+
val omega = 6.5 / zeta
|
|
135
|
+
if (zeta >= 0.999) {
|
|
136
|
+
1 - (1 + omega * t) * exp(-omega * t)
|
|
137
|
+
} else {
|
|
138
|
+
val damped = omega * sqrt(1 - zeta * zeta)
|
|
139
|
+
1 - exp(-zeta * omega * t) * (cos(damped * t) + (zeta * omega / damped) * sin(damped * t))
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
else -> 1 - (1 - t).pow(3)
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|