exact-charts 0.0.1 → 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/CHANGELOG.md ADDED
@@ -0,0 +1,71 @@
1
+ # Changelog
2
+
3
+ All notable changes to this package are recorded here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the package uses
5
+ [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [0.1.0] - 2026-12-06
8
+
9
+ The first npm release.
10
+
11
+ ### Verified
12
+
13
+ On Exact `f7788c9e6` (2026-12-04), with no change to the package:
14
+
15
+ - iOS: run on an iPhone 12 (iOS 27.2.1), a development build made on Linux: the line chart's readout,
16
+ bars, the donut picked from its legend, sparklines, the bar strip and the table, scrolled by touch.
17
+ - Android: run on an API 35 emulator (x86_64) by hand: a picked day, light and dark, the donut.
18
+ - Web: `bun exact.mjs verify`, 10 of 10 tests, `contract verify` 0 findings. The look check's 29 findings are
19
+ bar bands scrolled under the example's header at a test's end.
20
+ - Linux: 10 of 10 tests headless.
21
+ - macOS and Windows: not built, not run. `bun test`: 16 pass.
22
+ - README: screenshots from iPhone, Android, the web and Linux, and `bun add exact-charts`.
23
+
24
+ ### Fixed
25
+
26
+ - An axis written with no decimals (or one, two or three) steps by a whole number of its last digit. A chart up
27
+ to 10 with `valueAxis("decimal", 0, …)` showed ticks 0, 3, 5, 8, 10 for 0, 2.5, 5, 7.5 and 10. A percent axis
28
+ steps by whole percents.
29
+ - A chart whose values are all zero runs from 0 to 1. Bars of all zeros drew an axis from -1 to 1.
30
+ - `niceTicks` in `exact-charts/data` widens an all-zero range to 0 to 1 as well, as the components do.
31
+
32
+ ### Changed
33
+
34
+ - The example is built and tested against Exact `main` at `e2a98fb3`, and builds for iOS too. Each value axis
35
+ label has the test id `<id>-tick-<k>`, counted from the bottom.
36
+
37
+ ### Known issues
38
+
39
+ - On the Android 15 emulator with Exact `e2a98fb3`, a long, fast swipe (about 1,300 pixels in 0.7 s, starting low on
40
+ the screen) did not scroll the example's page, whether it began on a chart or on plain text. Shorter swipes, on a
41
+ chart or off it, scrolled. A like swipe (from 1,900 to 500 pixels in 0.6 s) scrolled it with Exact `82be4bdc`. The package has no scrolling code of its
42
+ own, so this looks like a host change, but it was not narrowed down further.
43
+
44
+ ## Before the first npm release (2026-11-24)
45
+
46
+ ### Added
47
+
48
+ - `LineChart` and `AreaChart`: one or more series over shared x labels. They have nice value ticks with gridlines
49
+ and a stronger zero line, x labels thinned to fit the screen, a legend for two or more series, and a readout
50
+ above the plot with the selected point's values (or the last point's).
51
+ - `BarChart`: grouped or `stacked` bars from zero, one band per x label. A selected band keeps its colour and the
52
+ other bands fade.
53
+ - `PieChart`: a pie or a `donut`, drawn clockwise from the top. Its legend rows (label, value, share) are buttons, and
54
+ the donut's centre shows the selected slice.
55
+ - `Sparkline`: a line, optionally filled, scaled to its own range.
56
+ - `Bars`: a small strip of bars with one bar highlighted, for a fact such as a station's usual occupancy by hour.
57
+ - `ChartTable`: the same data as a `table` with row and column headers.
58
+ - `ChartSeries`, `ChartSlice` and `ChartAxis` records, with the constructors `series`, `valueAxis`,
59
+ `rangedAxis` and `labelledAxis`, plus `chartValue`, `niceTicks`, `chartTint` and `chartPalette`.
60
+ - Selection on tap. Each chart sends the index to its `pick` action, or `-1` when the same point is tapped again. A
61
+ dense series has at most 12 touch bands on a phone (24 at 640 points and wider).
62
+ - Motion: plots fade in, bars change height smoothly, and the `Bars` strip rises bar by bar. All
63
+ of it stops under reduced motion.
64
+ - Loading (a placeholder with the platform's spinner) and empty (your own text) states, each in the chart's height.
65
+ - Accessibility: every touch band is a labelled button that says whether it is pressed. `Sparkline` and `Bars` are one
66
+ labelled image each. Axis labels are capped at 14 points at the largest text sizes.
67
+ - Light and dark through platform colour roles, with a fixed six-colour palette order.
68
+ - Right to left: the value axis, legend, readout and `Bars` follow the writing direction. Plots are not mirrored.
69
+ - `exact-charts/data` for `app.ts`: `lttbIndices`, `lttb`, `downsampleSeries`, `niceTicks`, `niceNumber`,
70
+ `axisLabels`, `stack`, `bucketMeans` and `pick`, with types and unit tests.
71
+ - An example app (`example/`) that shows every component, fed by its `app.ts`, with eight Contract tests.
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 softwhere.uz
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.
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 softwhere.uz
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 CHANGED
@@ -1,5 +1,225 @@
1
- # exact-charts
2
-
3
- Charts (line, bar, area, pie) for [Expo Exact](https://github.com/expo/exact), on every platform Exact supports.
4
-
5
- This version is a placeholder. The first release is coming soon from softwhere.uz.
1
+ # exact-charts
2
+
3
+ Charts for [Expo Exact](https://github.com/expo/exact), written in Contract alone: SVG, layout and `fn`s, with no native code. Every Exact host draws them the same way.
4
+
5
+ [![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
6
+
7
+ The package has:
8
+
9
+ - **Components:** `LineChart`, `AreaChart`, `BarChart` (grouped or stacked), `PieChart` (pie or donut), `Sparkline`, `Bars` (a small strip of bars, such as a station's usual occupancy by hour) and `ChartTable` (the same data as a table).
10
+ - **Data helpers** for `app.ts`, in `exact-charts/data`: LTTB downsampling, nice ticks with the app's own labels, stacking and bucket means.
11
+
12
+ ## Features
13
+
14
+ - **Axes.** The value axis has nice ticks (steps of 1, 2, 2.5 or 5 times a power of ten) and gridlines. A step is always a whole number of the axis' last digit, so an axis written with no decimals never steps by 2.5 (it takes 2 or 5) and every label is its gridline's own value. A `compact` axis is not held to this, since its digits depend on the number. A chart whose values are all zero runs from 0 to 1. The zero line is stronger than the others. You can pin either end of the axis, or pass your own ticks and labels.
15
+ - **Selection.** Tapping the plot selects a point (line and area), a band (bars) or a slice (from the pie's legend). A readout above the plot shows the selected point's values, or the last point's when nothing is selected. Your `pick` action receives the index. Tapping the same point again clears the selection and sends `-1`.
16
+ - **Motion.** Plots fade in, bars change height smoothly when the data or stacking changes, and the strip in `Bars` rises bar by bar. A line, area or pie redraws at once when its data changes. All motion stops when the person asks for reduced motion (`prefersReducedMotion`), so the final frame shows at once.
17
+ - **Formatting.** Numbers go through the platform's `formatNumber` in the person's locale: `decimal` (0 to 3 digits), `compact` or `percent`, with a unit you supply. Dates and every other word come from your app.
18
+ - **Empty and loading states.** While `loading` is set, a chart shows a placeholder of its own height with the platform's spinner, named by your `label`. With no data it shows your `emptyText`.
19
+ - **Large series.** `lttb` and `downsampleSeries` in `exact-charts/data` cut thousands of points to about the number a plot can show, keeping peaks and dips. A dense series also gets at most 12 touch bands on a phone (24 when the screen is 640 points or wider), so on a phone 390 points wide a band is about 24 points wide (a band at an end of a short series is half as wide as its neighbours). A `BarChart` has one band for each x label: keep its labels few enough to tap.
20
+ - **Accessibility.** Each touch band is a button labelled with its point ("Thu, Solar 24 kWh, Wind 11 kWh") and says whether it is pressed. A pie's legend rows are its buttons. `Sparkline` and `Bars` are single images named by your `label`. `ChartTable` is a real `table` with row and column headers. Axis labels are capped at 14 points even at the largest text sizes, as a calendar caps its day cells, so they stay on their gridlines. Everything else grows with the person's text size.
21
+ - **Light and dark.** Colours are platform roles (`-exact-system-blue`, `-exact-label`, `-exact-secondary-label` and so on), so they follow the scheme. Text uses text roles and never a series' colour.
22
+ - **Right to left.** The value axis, legend, readout and `Bars` follow the writing direction. A line, area or bar plot is not mirrored: time runs left to right, as in Apple's and Android's own charts. Its x labels and touch bands are placed to match the plot.
23
+
24
+ ## Platform support
25
+
26
+ What was run for 0.1.0, with the example on Exact `f7788c9e6` (`expo/exact` main, 2026-12-04):
27
+
28
+ | Platform | Status |
29
+ | --- | --- |
30
+ | iOS | **Run on an iPhone 12 (iOS 27.2.1)**, a development build made on Linux, driven through XCUITest: the line chart, a day tapped (readout and crosshair), the bars (a band tapped), the donut with a slice picked from the legend (its count and name in the centre), sparklines, the small bar strip and the table, all scrolled through by touch. |
31
+ | Android | **Run on an API 35 emulator (x86_64)**, driven by hand through adb: a day tapped on the line chart, light and dark, scrolled through by touch, a slice picked on the donut. Exact's own `test android` was not run: from WSL it could not drive this emulator, which runs on the Windows side. |
32
+ | Web | `bun exact.mjs verify`: the 10 Contract tests pass, the accessibility tree, the largest text size and `contract verify` (0 findings) are clean. Its look check reports 29 findings, all for bar bands scrolled under the example's own collapsed header (or cut by the window's bottom edge) at the end of two tests; none is in a chart as drawn on screen. |
33
+ | Linux | The host builds and the 10 tests pass headless; a picked day was looked at in a screenshot. |
34
+ | macOS, Windows | Not built, not run. Nothing is specific to them. |
35
+
36
+ Because the package contains no native code, the hosts that were not run use the same Contract (SVG and layout) as those that were. That is an expectation, not a test.
37
+
38
+ | iPhone: a picked day | iPhone: the donut | Android (dark): a picked day | Android: the donut |
39
+ | --- | --- | --- | --- |
40
+ | <img src=\"docs/screenshots/ios-line.png\" width=\"200\"> | <img src=\"docs/screenshots/ios-donut.png\" width=\"200\"> | <img src=\"docs/screenshots/android-line-dark.png\" width=\"200\"> | <img src=\"docs/screenshots/android-donut.png\" width=\"200\"> |
41
+
42
+ | Web | Linux (headless) |
43
+ | --- | --- |
44
+ | <img src=\"docs/screenshots/web.png\" width=\"200\"> | <img src=\"docs/screenshots/linux-line.png\" width=\"200\"> |
45
+
46
+ ## Compatibility
47
+
48
+ | exact-charts | Exact |
49
+ | --- | --- |
50
+ | 0.1.x | `expo/exact` main at `f7788c9e6` (December 2026). Written on `82be4bdc`; the moves to `e2a98fb3` and `f7788c9e6` needed no change to the package. |
51
+
52
+ Exact has no releases or tags, so the package names the commit it was tested on.
53
+
54
+ ## Installation
55
+
56
+ ```sh
57
+ bun add exact-charts
58
+ ```
59
+
60
+ Then use the components in your `app.contract`, and the helpers in `app.ts`:
61
+
62
+ ```contract
63
+ use LineChart, BarChart, Bars, ChartSeries, valueAxis, series from "exact-charts"
64
+ ```
65
+
66
+ ```ts
67
+ import { downsampleSeries, axisLabels } from 'exact-charts/data';
68
+ ```
69
+
70
+ ## Quick start
71
+
72
+ ```contract
73
+ use LineChart, ChartSeries, valueAxis, series from "exact-charts"
74
+
75
+ shape Week
76
+ series: ChartSeries[]
77
+ labels: string[]
78
+
79
+ component App
80
+ resource week = weekEnergy() as shape Week
81
+ state day = -1
82
+ action pickDay(i: number)
83
+ day = i
84
+ view
85
+ column padding=16 gap=8
86
+ LineChart(id="energy", series=week.series, xLabels=week.labels, axis=valueAxis("decimal", 0, " kWh"), label="Energy this week", emptyText="No readings this week.", loading=(not current(week)), height=180, pick=pickDay)
87
+ ```
88
+
89
+ ```ts
90
+ const weekday = new Intl.DateTimeFormat(undefined, { weekday: 'short', timeZone: 'UTC' });
91
+ const weekEnergy = (): Result<'weekEnergy'> => ({
92
+ labels: days.map((ms) => weekday.format(new Date(ms))),
93
+ series: [{ name: 'Solar', values: solar, tint: '' }, { name: 'Wind', values: wind, tint: '' }],
94
+ });
95
+ ```
96
+
97
+ A small bar strip, for example a station's usual occupancy by hour, with the current hour highlighted:
98
+
99
+ ```contract
100
+ Bars(id="occupancy", values=station.hourly, labels=station.hourLabels, highlight=station.nowHour, tint="-exact-system-blue", max=1, label="Usually busiest around 6 PM", height=64)
101
+ ```
102
+
103
+ Contract props have no defaults, so every component takes all of its props. Pass `[]`, `""`, `false` or `-1` where you don't need one.
104
+
105
+ ## Records
106
+
107
+ Series names must be unique within a chart, and so must slice labels.
108
+
109
+ | Shape | Fields |
110
+ | --- | --- |
111
+ | `ChartSeries` | `name: string`: the series' name, used in the legend, the readout and labels. `values: number[]`: one value per x label, in x order. `tint: string`: a colour role or token, or `""` for the palette colour at the series' position. |
112
+ | `ChartSlice` | `label: string`, `value: number` (only values above zero are drawn), `tint: string` (as for a series). |
113
+ | `ChartAxis` | `format`: `"decimal"`, `"compact"` or `"percent"`. `digits`: fraction digits for `decimal`, 0 to 3. `unit`: text after each number (`" kW"`). `min`, `max`: `option<number>`, a pinned end. `ticks`: two or more evenly spaced values, used instead of computed ticks. `tickLabels`: your text for those ticks (the same length as `ticks`, or empty). |
114
+
115
+ ### Constructors and functions
116
+
117
+ | Function | Returns |
118
+ | --- | --- |
119
+ | `series(name, values)` | A `ChartSeries` with the palette's colour. |
120
+ | `valueAxis(format, digits, unit)` | An axis with nice ticks from the data. |
121
+ | `rangedAxis(format, digits, unit, lo, hi)` | An axis pinned from `lo` to `hi`, divided evenly into four. |
122
+ | `labelledAxis(format, digits, unit, ticks, tickLabels)` | Your own ticks and labels, for example from `axisLabels` in `app.ts`. The readout still uses `format`. |
123
+ | `chartValue(n, axis)` | `n` written the axis' way. |
124
+ | `niceTicks(lo, hi, count)` | Nice ticks over `[lo, hi]` in about `count` intervals. |
125
+ | `chartTint(i)`, `chartPalette()` | The palette's colour at position `i`, and the whole palette. |
126
+
127
+ ## Components
128
+
129
+ Each chart takes an `id`. The chart's root has that `testId`, and its parts are `<id>-plot`, `<id>-point-<b>` (line and area touch bands), `<id>-band-<i>` (bar bands), `<id>-slice-<j>` (pie legend rows), `<id>-center` (the donut's centre value), `<id>-tick-<k>` (a line, area or bar chart's value axis labels, from the bottom), `<id>-loading` and `<id>-empty`.
130
+
131
+ ### `LineChart` and `AreaChart`
132
+
133
+ | Prop | Type | Meaning |
134
+ | --- | --- | --- |
135
+ | `id` | `string` | The test id prefix. |
136
+ | `series` | `ChartSeries[]` | One line each. Two or more series get a legend. |
137
+ | `xLabels` | `string[]` | One label per point, written by your app. They are thinned to fit the screen, and the first and last are kept inside the plot. |
138
+ | `axis` | `ChartAxis` | The value axis. An area chart's axis always includes zero. |
139
+ | `label` | `string` | The plot's accessible name, also used for the loading spinner. |
140
+ | `emptyText` | `string` | Shown when no series has a value. |
141
+ | `loading` | `bool` | Shows the loading placeholder instead of the chart. |
142
+ | `height` | `number` | The plot's height in points (the readout, axis labels and legend add to it). |
143
+ | `pick` | `action` | Called with the selected point's index, or `-1` when the selection is cleared. |
144
+
145
+ ### `BarChart`
146
+
147
+ The same props as `LineChart`, plus `stacked: bool`. Bars always start from zero. Stacked bars expect values of zero or more. Each x label has a band. Grouped bars share 72% of the band, and a stack takes 56% of it, with a hairline gap between its segments. `pick` receives the band's index.
148
+
149
+ ### `PieChart`
150
+
151
+ | Prop | Type | Meaning |
152
+ | --- | --- | --- |
153
+ | `id` | `string` | The test id prefix. |
154
+ | `slices` | `ChartSlice[]` | Drawn clockwise from the top, in order. |
155
+ | `axis` | `ChartAxis` | How the legend and the centre write values. |
156
+ | `donut` | `bool` | A ring rather than a pie. |
157
+ | `centerTitle`, `centerValue` | `string` | The donut's centre when nothing is selected, such as `"ports"` and `"96"`. A selected slice shows its own label and value there. |
158
+ | `label`, `emptyText`, `loading` | as above | |
159
+ | `size` | `number` | The chart's width and height in points. The legend sits beside it, or below it when space is short. |
160
+ | `pick` | `action` | Called with the slice's index, or `-1`. |
161
+
162
+ Each legend row shows a slice's swatch, label, value and share (formatted by the platform as a percentage). The rows are buttons.
163
+
164
+ ### `Sparkline`
165
+
166
+ `values: number[]`, `tint: string`, `filled: bool`, `label: string`, `height: number`. The line is scaled to the values' own range and fills the width it is given. It is one image, named by `label`. Say what it shows, for example "Rising, 4 to 14 kW this week".
167
+
168
+ ### `Bars`
169
+
170
+ `id`, `values: number[]`, `labels: string[]` (use `""` for no label), `highlight: number` (the index drawn in full `tint`, or `-1` to draw every bar in full), `tint: string`, `max: number` (the top of the scale, or `0` to use the largest value), `label: string`, `height: number`. It is one image, named by `label`. At most eight labels show: one at the start of every `ceil(n / 8)` bars. Unlike the plots, the strip follows the writing direction.
171
+
172
+ ### `ChartTable`
173
+
174
+ `id`, `series`, `xLabels`, `axis`, `caption: string`, `xTitle: string` (the heading of the x labels' column). It renders a `table` with a row for each x label and a column for each series. Offer it next to a chart so that every value can be read exactly.
175
+
176
+ ### `ChartLegend`, `ChartEmpty`, `ChartLoading`
177
+
178
+ These are the charts' own parts, exported for an app that builds its own chart.
179
+
180
+ ## `exact-charts/data`
181
+
182
+ These are pure functions with no imports and no globals, so Exact's data runtime accepts them on every platform. Types are in `data/index.d.ts`.
183
+
184
+ | Function | What it does |
185
+ | --- | --- |
186
+ | `lttbIndices(values, threshold, xs?)` | Largest-Triangle-Three-Buckets: the indices of at most `threshold` points that keep the series' shape. It always keeps the first and last points and skips values that are not finite. |
187
+ | `lttb(values, threshold, xs?)` | `{ indices, values }`. |
188
+ | `downsampleSeries(series, labels, threshold)` | Downsamples series that share x labels to the union of each series' LTTB points, so they stay aligned. An x where any series has a value that is not finite is left out. Returns `{ series, labels, indices }`. |
189
+ | `niceTicks(min, max, count = 4)` | `{ min, max, step, ticks }`, using the same rule as the Contract `niceTicks`. It knows nothing of an axis' digits, so it can step by 2.5 where a chart's own axis written with no decimals would step by 2 or 5. |
190
+ | `axisLabels(values, format, { count, zero })` | `{ ticks, tickLabels }` for `labelledAxis`, with each label written by your `format` (an `Intl.NumberFormat`, for example). |
191
+ | `stack(values)` | Each series' running totals at each x. |
192
+ | `bucketMeans(values, buckets)` | The mean of each of `buckets` equal buckets, such as a day of readings turned into 24 hourly bars. |
193
+ | `pick(xs, indices)`, `niceNumber(n, round)` | Small helpers. |
194
+
195
+ A series of 5,000 readings, cut to 120 points before it reaches a chart:
196
+
197
+ ```ts
198
+ const cut = downsampleSeries([{ name: 'Meter', values, tint: '' }], labels, 120);
199
+ const axis = axisLabels(cut.series[0].values, (n) => `${kw.format(n)} kW`, { zero: true });
200
+ return { series: cut.series, labels: cut.labels, ticks: axis.ticks, tickLabels: axis.tickLabels };
201
+ ```
202
+
203
+ ## Design notes
204
+
205
+ - **Palette.** In order: blue, orange, purple, green, pink and indigo, all platform roles. On iOS's light values this order passes the dataviz validator's lightness, chroma and normal-vision checks. Two pairs fall in its 6 to 8 colour-vision-deficiency band, which is allowed only with a second cue, so identity never depends on colour alone: the legend, the readout's names and each touch band's label carry it. Positions past the sixth repeat the colours, so give more than six series or slices their own `tint`, or fold the rest into one. Colour follows the series' position, so keep a series in the same position when the set changes, or give it a fixed `tint`.
206
+ - **Plot geometry.** Each plot is a 1000 by 1000 SVG view box stretched to its box (`preserveAspectRatio="none"`), with `vector-effect="non-scaling-stroke"` so lines stay 2 points wide at any size. Dots and labels are laid-out boxes, not SVG, so they keep their shape.
207
+ - **Contract limits.** Contract has no `pow`, `log` or `abs`, so a nice step is the first entry of a fixed table (from 0.000001 to 10^15) that fits. `formatNumber` takes its style and digits as literals, so each combination is a separate call, and currency is not offered: write currency labels in `app.ts`.
208
+ - **Even spacing.** Points are evenly spaced along x, after downsampling too: LTTB keeps one point from each equal bucket, so a single series shifts by less than a bucket. With several downsampled series the spacing is only approximate.
209
+ - **No mirroring.** The plot does not mirror right to left (see Features).
210
+
211
+ ## Example
212
+
213
+ `example/` is an Exact app that shows every component, fed by its `app.ts`. To run it:
214
+
215
+ ```sh
216
+ cd example
217
+ bun tools/pack-package.mjs # packs the package into vendor/ and installs it
218
+ bun exact.mjs web # or: verify, linux, android
219
+ ```
220
+
221
+ Its tests are in `example/app.test.contract`. The data helpers' unit tests run with `bun test` at the root.
222
+
223
+ ## License
224
+
225
+ MIT © softwhere.uz
@@ -0,0 +1,17 @@
1
+ // Types for exact-charts/data. See index.js for each function's contract.
2
+
3
+ export interface ChartSeries {
4
+ name: string;
5
+ values: number[];
6
+ tint: string;
7
+ }
8
+
9
+ export declare function lttbIndices(values: number[], threshold: number, xs?: number[]): number[];
10
+ export declare function pick<T>(xs: T[], indices: number[]): T[];
11
+ export declare function lttb(values: number[], threshold: number, xs?: number[]): { indices: number[]; values: number[] };
12
+ export declare function downsampleSeries<S extends ChartSeries>(series: S[], labels: string[], threshold: number): { series: S[]; labels: string[]; indices: number[] };
13
+ export declare function niceNumber(n: number, round: boolean): number;
14
+ export declare function niceTicks(min: number, max: number, count?: number): { min: number; max: number; step: number; ticks: number[] };
15
+ export declare function axisLabels(values: number[], format: (n: number) => string, options?: { count?: number; zero?: boolean }): { ticks: number[]; tickLabels: string[] };
16
+ export declare function stack(values: number[][]): number[][];
17
+ export declare function bucketMeans(values: number[], buckets: number): number[];
package/data/index.js ADDED
@@ -0,0 +1,209 @@
1
+ // exact-charts/data: the data side of exact-charts, for an app's data module
2
+ // (app.ts). Pure functions with no imports and no globals, so Exact's data
3
+ // runtime takes them on every platform. The Contract components draw what
4
+ // these return: a downsampled series, nice ticks and their labels.
5
+
6
+ const isNumber = (n) => typeof n === 'number' && Number.isFinite(n);
7
+
8
+ /**
9
+ * Largest-Triangle-Three-Buckets (Steinarsson, 2013): the indices of at most
10
+ * `threshold` points that keep a series' visual shape. The first and last
11
+ * points are always kept. Non-finite values are skipped. With `threshold`
12
+ * below 3, or at least the number of points, every finite point is kept.
13
+ * `xs` are the points' x values (default: their indices), ascending.
14
+ * @param {number[]} values
15
+ * @param {number} threshold
16
+ * @param {number[]} [xs]
17
+ * @returns {number[]}
18
+ */
19
+ export function lttbIndices(values, threshold, xs) {
20
+ if (!Array.isArray(values)) throw new TypeError('lttbIndices: values must be an array of numbers');
21
+ if (xs !== undefined && (!Array.isArray(xs) || xs.length !== values.length)) {
22
+ throw new TypeError('lttbIndices: xs must be an array as long as values');
23
+ }
24
+ const kept = [];
25
+ for (let i = 0; i < values.length; i++) {
26
+ if (isNumber(values[i]) && (xs === undefined || isNumber(xs[i]))) kept.push(i);
27
+ }
28
+ const limit = Math.floor(Number(threshold));
29
+ if (!(limit >= 3) || limit >= kept.length) return kept;
30
+ const x = (k) => (xs === undefined ? kept[k] : xs[kept[k]]);
31
+ const y = (k) => values[kept[k]];
32
+ const out = [kept[0]];
33
+ const every = (kept.length - 2) / (limit - 2);
34
+ let a = 0;
35
+ for (let b = 0; b < limit - 2; b++) {
36
+ // The next bucket's average point is the third corner.
37
+ const nextStart = Math.floor((b + 1) * every) + 1;
38
+ const nextEnd = Math.min(Math.floor((b + 2) * every) + 1, kept.length);
39
+ let avgX = 0;
40
+ let avgY = 0;
41
+ for (let k = nextStart; k < nextEnd; k++) { avgX += x(k); avgY += y(k); }
42
+ const span = Math.max(nextEnd - nextStart, 1);
43
+ avgX /= span;
44
+ avgY /= span;
45
+ // Of this bucket's points, keep the one making the largest triangle with
46
+ // the last kept point and that average.
47
+ const start = Math.floor(b * every) + 1;
48
+ const end = Math.floor((b + 1) * every) + 1;
49
+ let best = start;
50
+ let bestArea = -1;
51
+ for (let k = start; k < end; k++) {
52
+ const area = Math.abs((x(a) - avgX) * (y(k) - y(a)) - (x(a) - x(k)) * (avgY - y(a)));
53
+ if (area > bestArea) { bestArea = area; best = k; }
54
+ }
55
+ out.push(kept[best]);
56
+ a = best;
57
+ }
58
+ out.push(kept[kept.length - 1]);
59
+ return out;
60
+ }
61
+
62
+ /**
63
+ * The values at `indices`, in order.
64
+ * @template T
65
+ * @param {T[]} xs
66
+ * @param {number[]} indices
67
+ * @returns {T[]}
68
+ */
69
+ export const pick = (xs, indices) => indices.map((i) => xs[i]);
70
+
71
+ /**
72
+ * LTTB on one series: its kept values and their indices.
73
+ * @param {number[]} values
74
+ * @param {number} threshold
75
+ * @param {number[]} [xs]
76
+ * @returns {{ indices: number[], values: number[] }}
77
+ */
78
+ export function lttb(values, threshold, xs) {
79
+ const indices = lttbIndices(values, threshold, xs);
80
+ return { indices, values: pick(values, indices) };
81
+ }
82
+
83
+ /**
84
+ * Downsamples series that share x labels (a LineChart's `series` and
85
+ * `xLabels`) to the union of each series' LTTB points, so every series
86
+ * keeps its own peaks and all stay aligned. An x where any series has a
87
+ * non-finite value is left out, and so is its label. Each series is given an
88
+ * equal part of `threshold` (3 points at least).
89
+ * @param {{ name: string, values: number[], tint: string }[]} series
90
+ * @param {string[]} labels
91
+ * @param {number} threshold
92
+ * @returns {{ series: { name: string, values: number[], tint: string }[], labels: string[], indices: number[] }}
93
+ */
94
+ export function downsampleSeries(series, labels, threshold) {
95
+ if (!Array.isArray(series)) throw new TypeError('downsampleSeries: series must be an array');
96
+ const each = Math.max(3, Math.floor(threshold / Math.max(series.length, 1)));
97
+ const union = new Set();
98
+ for (const s of series) for (const i of lttbIndices(s.values, series.length > 1 ? each : threshold)) union.add(i);
99
+ const indices = [...union]
100
+ .filter((i) => series.every((s) => i >= s.values.length || isNumber(s.values[i])))
101
+ .sort((p, q) => p - q);
102
+ return {
103
+ indices,
104
+ labels: indices.map((i) => labels[i] ?? ''),
105
+ series: series.map((s) => ({ ...s, values: indices.filter((i) => i < s.values.length).map((i) => s.values[i]) })),
106
+ };
107
+ }
108
+
109
+ /**
110
+ * A "nice" number near `n` (1, 2, 2.5 or 5 times a power of ten): rounded
111
+ * to the nearest when `round`, else the smallest at or above.
112
+ * @param {number} n
113
+ * @param {boolean} round
114
+ * @returns {number}
115
+ */
116
+ export function niceNumber(n, round) {
117
+ if (!(n > 0) || !Number.isFinite(n)) return 1;
118
+ const power = 10 ** Math.floor(Math.log10(n));
119
+ const f = n / power;
120
+ const nice = round
121
+ ? (f < 1.5 ? 1 : f < 2.25 ? 2 : f < 3.5 ? 2.5 : f < 7.5 ? 5 : 10)
122
+ : (f <= 1 ? 1 : f <= 2 ? 2 : f <= 2.5 ? 2.5 : f <= 5 ? 5 : 10);
123
+ return nice * power;
124
+ }
125
+
126
+ const tidy = (n, step) => {
127
+ const digits = Math.max(0, -Math.floor(Math.log10(step)) + 2);
128
+ return Number(n.toFixed(Math.min(digits, 15)));
129
+ };
130
+
131
+ /**
132
+ * Nice, evenly spaced ticks covering [min, max] in about `count` intervals,
133
+ * the rule of the components' `niceTicks`: the first tick at or below
134
+ * `min`, the last at or above `max`. A flat range is widened (all zeros: from 0 to 1).
135
+ * @param {number} min
136
+ * @param {number} max
137
+ * @param {number} [count=4]
138
+ * @returns {{ min: number, max: number, step: number, ticks: number[] }}
139
+ */
140
+ export function niceTicks(min, max, count = 4) {
141
+ if (!Number.isFinite(min) || !Number.isFinite(max)) throw new RangeError('niceTicks: min and max must be finite');
142
+ let lo = Math.min(min, max);
143
+ let hi = Math.max(min, max);
144
+ if (hi === lo) {
145
+ const pad = lo === 0 ? 1 : Math.abs(lo) / 2;
146
+ if (lo !== 0) lo -= pad;
147
+ hi += pad;
148
+ }
149
+ const intervals = Math.max(1, Math.floor(count));
150
+ const step = niceNumber((hi - lo) / intervals, false);
151
+ const first = Math.floor(lo / step) * step;
152
+ const last = Math.ceil(hi / step) * step;
153
+ const ticks = [];
154
+ for (let k = 0; k <= Math.round((last - first) / step); k++) ticks.push(tidy(first + k * step, step));
155
+ return { min: ticks[0], max: ticks[ticks.length - 1], step, ticks };
156
+ }
157
+
158
+ /**
159
+ * Ticks and their labels for the components' `labelledAxis`, from every
160
+ * value a chart draws, written by the app's own `format` (an
161
+ * `Intl.NumberFormat`'s, so the locale and units are the app's).
162
+ * @param {number[]} values
163
+ * @param {(n: number) => string} format
164
+ * @param {{ count?: number, zero?: boolean }} [options]
165
+ * @returns {{ ticks: number[], tickLabels: string[] }}
166
+ */
167
+ export function axisLabels(values, format, { count = 4, zero = false } = {}) {
168
+ if (typeof format !== 'function') throw new TypeError('axisLabels: format must be a function');
169
+ const finite = values.filter(isNumber);
170
+ const lo = finite.length ? finite.reduce((a, b) => Math.min(a, b)) : 0;
171
+ const hi = finite.length ? finite.reduce((a, b) => Math.max(a, b)) : 1;
172
+ const { ticks } = niceTicks(zero ? Math.min(0, lo) : lo, zero ? Math.max(0, hi) : hi, count);
173
+ return { ticks, tickLabels: ticks.map((t) => format(t)) };
174
+ }
175
+
176
+ /**
177
+ * Each series' running totals at each x (a stack's tops), for a stacked
178
+ * chart's own drawing or its readout. Missing values count as zero.
179
+ * @param {number[][]} values
180
+ * @returns {number[][]}
181
+ */
182
+ export function stack(values) {
183
+ const length = Math.max(0, ...values.map((v) => v.length));
184
+ const running = new Array(length).fill(0);
185
+ return values.map((v) => running.map((total, i) => {
186
+ running[i] = total + (isNumber(v[i]) ? v[i] : 0);
187
+ return running[i];
188
+ }));
189
+ }
190
+
191
+ /**
192
+ * Averages `values` into `buckets` equal buckets (an hour's readings into a
193
+ * day's 24 bars): each bucket's mean, or 0 when it holds none.
194
+ * @param {number[]} values
195
+ * @param {number} buckets
196
+ * @returns {number[]}
197
+ */
198
+ export function bucketMeans(values, buckets) {
199
+ const n = Math.max(1, Math.floor(buckets));
200
+ const sums = new Array(n).fill(0);
201
+ const counts = new Array(n).fill(0);
202
+ values.forEach((v, i) => {
203
+ if (!isNumber(v)) return;
204
+ const b = Math.min(n - 1, Math.floor((i * n) / Math.max(values.length, 1)));
205
+ sums[b] += v;
206
+ counts[b] += 1;
207
+ });
208
+ return sums.map((s, b) => (counts[b] ? s / counts[b] : 0));
209
+ }
package/index.contract ADDED
@@ -0,0 +1,15 @@
1
+ // exact-charts: charts for Expo Exact in Contract alone (SVG and layout), so
2
+ // every host draws them with no native code: line, area, grouped or
3
+ // stacked bars, pie and donut, a sparkline and a small bar strip, with a
4
+ // table view of the same data. The data helpers (LTTB downsampling, nice
5
+ // ticks, stacking) are `exact-charts/data`, for app.ts.
6
+
7
+ use ChartSeries, ChartSlice, ChartAxis from "./src/shapes.contract"
8
+ use niceTicks, chartTint, chartPalette from "./src/scale.contract"
9
+ use valueAxis, rangedAxis, labelledAxis, series, chartValue from "./src/format.contract"
10
+ use ChartLegend, ChartEmpty, ChartLoading from "./src/parts.contract"
11
+ use LineChart, AreaChart from "./src/line-chart.contract"
12
+ use BarChart from "./src/bar-chart.contract"
13
+ use PieChart from "./src/pie-chart.contract"
14
+ use Sparkline, Bars from "./src/sparkline.contract"
15
+ use ChartTable from "./src/table.contract"
package/package.json CHANGED
@@ -1,9 +1,34 @@
1
- {
2
- "name": "exact-charts",
3
- "version": "0.0.1",
4
- "description": "Charts (line, bar, area, pie) for Expo Exact (Android, iOS, macOS, web, Windows, Linux). First release coming soon.",
5
- "keywords": ["exact", "expo-exact", "charts", "chart", "graphs"],
6
- "license": "MIT",
7
- "author": "softwhere.uz",
8
- "files": ["README.md", "LICENSE"]
9
- }
1
+ {
2
+ "name": "exact-charts",
3
+ "version": "0.1.0",
4
+ "description": "Charts for Expo Exact in pure Contract (SVG and layout), so they draw on Android, iOS, macOS, web, Windows and Linux with no native code: line, area, grouped and stacked bars, pie and donut, sparklines, a small bar strip and a table view, plus LTTB downsampling and nice ticks for app.ts.",
5
+ "license": "MIT",
6
+ "author": "softwhere.uz <kamuranbek1998@gmail.com> (https://github.com/softwhere-uz)",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/softwhere-uz/exact-charts.git"
10
+ },
11
+ "homepage": "https://github.com/softwhere-uz/exact-charts#readme",
12
+ "bugs": "https://github.com/softwhere-uz/exact-charts/issues",
13
+ "keywords": ["exact", "expo-exact", "contract", "charts", "chart", "svg", "line-chart", "bar-chart", "pie-chart", "sparkline", "lttb", "downsampling"],
14
+ "type": "module",
15
+ "exports": {
16
+ ".": "./index.contract",
17
+ "./data": {
18
+ "types": "./data/index.d.ts",
19
+ "default": "./data/index.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "index.contract",
24
+ "src/*.contract",
25
+ "data/index.js",
26
+ "data/index.d.ts",
27
+ "README.md",
28
+ "CHANGELOG.md",
29
+ "LICENSE"
30
+ ],
31
+ "scripts": {
32
+ "test": "bun test test/"
33
+ }
34
+ }
@@ -0,0 +1,63 @@
1
+ // exact-charts: bar charts, grouped side by side or stacked, from zero, over
2
+ // one band per x label. A tapped band is selected: its bars stay full and the
3
+ // rest fade, and the readout above the plot names its values. Bars fade
4
+ // in and move to new values, both still under reduced motion.
5
+
6
+ use ChartSeries, ChartAxis from "./shapes.contract"
7
+ use axisTicks, listMin, listMax, seriesValues, seriesLength, stackTotals, stackBelow, hasData, labelAt, tintOf, yAt, bandAt, baseOf, barLeft, barWidth, barTop, barHeight, labelRoom from "./scale.contract"
8
+ use pointText from "./format.contract"
9
+ use ChartViewport, ChartYLabels, ChartXLabels, ChartLegend, ChartReadout, ChartEmpty, ChartLoading, chartReveal from "./parts.contract"
10
+
11
+ // A bar chart. `stacked` stacks the series at each x (values at or above
12
+ // zero); otherwise they stand side by side. `pick` hears the tapped band's
13
+ // index, or -1 when the same band is tapped again.
14
+ component BarChart
15
+ props
16
+ id: string
17
+ series: ChartSeries[]
18
+ xLabels: string[]
19
+ axis: ChartAxis
20
+ stacked: bool
21
+ label: string
22
+ emptyText: string
23
+ loading: bool
24
+ height: number
25
+ pick: action
26
+ resource screen = exactViewport() as shape ChartViewport
27
+ state chosen = -1
28
+ derive still = screen.prefersReducedMotion
29
+ derive ticks = axisTicks((stacked ? stackTotals(series) : seriesValues(series)), axis, true, 4)
30
+ derive lo = listMin(ticks)
31
+ derive hi = listMax(ticks)
32
+ derive n = seriesLength(series)
33
+ derive k = series.length
34
+ derive picked = chosen < n ? chosen : -1
35
+ action tapBand(i: number)
36
+ let next = chosen == i ? -1 : i
37
+ chosen = next
38
+ pick(next)
39
+ view
40
+ if loading
41
+ ChartLoading(id=id, label=label, height=height, still=still)
42
+ else if not hasData(series)
43
+ ChartEmpty(id=id, text=emptyText, height=height)
44
+ else
45
+ column gap=8 testId=id
46
+ ChartReadout(series=series, title=labelAt(xLabels, (picked >= 0 ? picked : n - 1)), index=(picked >= 0 ? picked : n - 1), axis=axis)
47
+ row gap=8 padding-top=8
48
+ ChartYLabels(id=id, ticks=ticks, axis=axis, height=height)
49
+ column flex=1 min-width=0 gap=4
50
+ view position="relative" height=height role="group" aria-label=label testId=`${id}-plot`
51
+ svg width="100%" height="100%" viewBox="0 0 1000 1000" preserveAspectRatio="none" overflow="visible" aria-hidden=true
52
+ for t in ticks key=`${t}`
53
+ line x1=0 x2=1000 y1=yAt(t, lo, hi) y2=yAt(t, lo, hi) stroke="-exact-label" stroke-opacity=(t == 0 ? 0.4 : 0.14) stroke-width=1 vector-effect="non-scaling-stroke"
54
+ g animation=(still ? "none" : "chartReveal 400ms ease-out both")
55
+ for s, j in series key=s.name
56
+ // exact-accept lower-key-position
57
+ for v, i in s.values key=`${i}`
58
+ rect x=barLeft(i, j, n, k, stacked) width=barWidth(n, k, stacked) y=(stacked ? barTop(v, stackBelow(series, j, i), lo, hi) : barTop(v, 0, lo, hi)) height=(stacked ? barHeight(v, stackBelow(series, j, i), (j > 0 ? 6 : 0), lo, hi) : barHeight(v, 0, 0, lo, hi)) fill=tintOf(s.tint, j) opacity=(picked < 0 or picked == i ? 1 : 0.35) transition=(still ? "none" : "y 350ms ease, height 350ms ease, opacity 150ms ease")
59
+ for i in range(n) key=`${i}`
60
+ view position="absolute" top=0 bottom=0 left=`${bandAt(i, n) / 10}%` width=`${100 / n}%` press=tapBand(i) role="button" aria-label=pointText(series, xLabels, i, axis) aria-pressed=(picked == i) testId=`${id}-band-${i}`
61
+ ChartXLabels(labels=xLabels, count=n, most=labelRoom(screen.width, xLabels, 12), bands=true)
62
+ if series.length > 1
63
+ ChartLegend(series=series)
@@ -0,0 +1,29 @@
1
+ // exact-charts: writing values. Numbers go through the platform's
2
+ // `formatNumber` in the person's locale; every word is the app's.
3
+
4
+ use ChartSeries, ChartAxis from "./shapes.contract"
5
+ use labelAt, valueAt from "./scale.contract"
6
+
7
+ // An axis in a `formatNumber` style with `digits` fraction digits and a unit
8
+ // the app wrote (" kW", or "").
9
+ fn valueAxis(format: string, digits: number, unit: string): ChartAxis = ChartAxis(format=format, digits=digits, unit=unit, min=none, max=none, ticks=[], tickLabels=[])
10
+ // The same with pinned ends (a percentage axis from 0 to 1).
11
+ fn rangedAxis(format: string, digits: number, unit: string, lo: number, hi: number): ChartAxis = ChartAxis(format=format, digits=digits, unit=unit, min=some(lo), max=some(hi), ticks=[], tickLabels=[])
12
+ // The app's own ticks and their text (ticks from `niceTicks` in
13
+ // exact-charts/data, labels from Intl in app.ts); values still use `format`.
14
+ fn labelledAxis(format: string, digits: number, unit: string, ticks: number[], tickLabels: string[]): ChartAxis = ChartAxis(format=format, digits=digits, unit=unit, min=none, max=none, ticks=ticks, tickLabels=tickLabels)
15
+
16
+ // A series or a slice with the palette's colour at its place.
17
+ fn series(name: string, values: number[]): ChartSeries = ChartSeries(name=name, values=values, tint="")
18
+
19
+ // `formatNumber` takes its style and digits as literals, so each pair is its
20
+ // own call: `decimal` takes 0 to 3 digits; `compact` (1.2K) and `percent`
21
+ // (26%) take the platform's.
22
+ fn decimalIn(n: number, digits: number): string = digits >= 3 ? formatNumber(n, "decimal", 3) : (digits == 2 ? formatNumber(n, "decimal", 2) : (digits == 1 ? formatNumber(n, "decimal", 1) : formatNumber(n, "decimal", 0)))
23
+ fn formatIn(n: number, format: string, digits: number): string = format == "compact" ? formatNumber(n, "compact") : (format == "percent" ? formatNumber(n, "percent") : decimalIn(n, digits))
24
+ fn chartValue(n: number, axis: ChartAxis): string = `${formatIn(n, axis.format, axis.digits)}${axis.unit}`
25
+ fn tickText(axis: ChartAxis, ticks: number[], k: number): string = axis.tickLabels.length == ticks.length ? labelAt(axis.tickLabels, k) : chartValue(valueAt(ticks, k), axis)
26
+
27
+ // A point's spoken and shown description: its x label, then each series'
28
+ // name and value ("Mon, Solar 12 kW, Wind 4 kW").
29
+ fn pointText(series: ChartSeries[], xLabels: string[], i: number, axis: ChartAxis): string = [labelAt(xLabels, i)].concat(series.filter(s => i < s.values.length).map(s => `${s.name} ${chartValue(valueAt(s.values, i), axis)}`)).filter(t => t != "").join(", ")
@@ -0,0 +1,100 @@
1
+ // exact-charts: line and area charts. A plot of one or more series over
2
+ // shared x labels, nice value ticks with gridlines, a legend for two series
3
+ // or more, and a readout for the point a person taps. The plot fades
4
+ // in, still under reduced motion.
5
+
6
+ use ChartSeries, ChartAxis from "./shapes.contract"
7
+ use axisTicks, listMin, listMax, seriesValues, seriesLength, hasData, labelAt, valueAt, tintOf, yAt, xAt, linePath, areaPath, touchBands, bandPoint, touchLeft, touchWidth, labelRoom from "./scale.contract"
8
+ use pointText from "./format.contract"
9
+ use ChartViewport, ChartYLabels, ChartXLabels, ChartLegend, ChartReadout, ChartEmpty, ChartLoading, chartReveal from "./parts.contract"
10
+
11
+ // A line chart. `pick` hears the tapped point's index, or -1 when the
12
+ // same point is tapped again.
13
+ component LineChart
14
+ props
15
+ id: string
16
+ series: ChartSeries[]
17
+ xLabels: string[]
18
+ axis: ChartAxis
19
+ label: string
20
+ emptyText: string
21
+ loading: bool
22
+ height: number
23
+ pick: action
24
+ view
25
+ ChartPlot(id=id, series=series, xLabels=xLabels, axis=axis, label=label, emptyText=emptyText, loading=loading, height=height, area=false, pick=pick)
26
+
27
+ // An area chart: a line chart whose series are filled down to zero (or the
28
+ // axis' nearer end), its value axis always holding zero.
29
+ component AreaChart
30
+ props
31
+ id: string
32
+ series: ChartSeries[]
33
+ xLabels: string[]
34
+ axis: ChartAxis
35
+ label: string
36
+ emptyText: string
37
+ loading: bool
38
+ height: number
39
+ pick: action
40
+ view
41
+ ChartPlot(id=id, series=series, xLabels=xLabels, axis=axis, label=label, emptyText=emptyText, loading=loading, height=height, area=true, pick=pick)
42
+
43
+ component ChartPlot
44
+ props
45
+ id: string
46
+ series: ChartSeries[]
47
+ xLabels: string[]
48
+ axis: ChartAxis
49
+ label: string
50
+ emptyText: string
51
+ loading: bool
52
+ height: number
53
+ area: bool
54
+ pick: action
55
+ resource screen = exactViewport() as shape ChartViewport
56
+ state chosen = -1
57
+ derive still = screen.prefersReducedMotion
58
+ derive ticks = axisTicks(seriesValues(series), axis, area, 4)
59
+ derive lo = listMin(ticks)
60
+ derive hi = listMax(ticks)
61
+ derive n = seriesLength(series)
62
+ derive picked = chosen < n ? chosen : -1
63
+ // The point with a dot: the picked one, or an only point, which no line shows.
64
+ derive dot = n == 1 ? 0 : picked
65
+ derive bands = touchBands(n, (screen.width >= 640 ? 24 : 12))
66
+ action tapPoint(i: number)
67
+ let next = chosen == i ? -1 : i
68
+ chosen = next
69
+ pick(next)
70
+ view
71
+ if loading
72
+ ChartLoading(id=id, label=label, height=height, still=still)
73
+ else if not hasData(series)
74
+ ChartEmpty(id=id, text=emptyText, height=height)
75
+ else
76
+ column gap=8 testId=id
77
+ ChartReadout(series=series, title=labelAt(xLabels, (picked >= 0 ? picked : n - 1)), index=(picked >= 0 ? picked : n - 1), axis=axis)
78
+ row gap=8 padding-top=8
79
+ ChartYLabels(id=id, ticks=ticks, axis=axis, height=height)
80
+ column flex=1 min-width=0 gap=4
81
+ view position="relative" height=height role="group" aria-label=label testId=`${id}-plot`
82
+ svg width="100%" height="100%" viewBox="0 0 1000 1000" preserveAspectRatio="none" overflow="visible" aria-hidden=true
83
+ for t in ticks key=`${t}`
84
+ line x1=0 x2=1000 y1=yAt(t, lo, hi) y2=yAt(t, lo, hi) stroke="-exact-label" stroke-opacity=(t == 0 ? 0.4 : 0.14) stroke-width=1 vector-effect="non-scaling-stroke"
85
+ g animation=(still ? "none" : "chartReveal 500ms ease-out both")
86
+ for s, j in series key=s.name
87
+ if area
88
+ path d=areaPath(s.values, n, lo, hi) fill=tintOf(s.tint, j) fill-opacity=(series.length > 1 ? 0.14 : 0.22) stroke="none"
89
+ path d=linePath(s.values, n, lo, hi) fill="none" stroke=tintOf(s.tint, j) stroke-width=2 stroke-linejoin="round" stroke-linecap="round" vector-effect="non-scaling-stroke"
90
+ if picked >= 0
91
+ line x1=xAt(picked, n) x2=xAt(picked, n) y1=0 y2=1000 stroke="-exact-secondary-label" stroke-width=1 vector-effect="non-scaling-stroke"
92
+ if dot >= 0
93
+ for s, j in series key=s.name
94
+ if dot < s.values.length
95
+ view position="absolute" left=`${xAt(dot, n) / 10}%` top=`${yAt(valueAt(s.values, dot), lo, hi) / 10}%` width=10 height=10 translate="-50% -50%" border-radius="50%" background-color=tintOf(s.tint, j) border-width=2 border-style="solid" border-color="-exact-background" pointer-events="none" aria-hidden=true
96
+ for b in range(bands) key=`${b}`
97
+ view position="absolute" top=0 bottom=0 left=`${touchLeft(b, bands, n)}%` width=`${touchWidth(b, bands, n)}%` press=tapPoint(bandPoint(b, bands, n)) role="button" aria-label=pointText(series, xLabels, bandPoint(b, bands, n), axis) aria-pressed=(picked == bandPoint(b, bands, n)) testId=`${id}-point-${b}`
98
+ ChartXLabels(labels=xLabels, count=n, most=labelRoom(screen.width, xLabels, 8), bands=false)
99
+ if series.length > 1
100
+ ChartLegend(series=series)
@@ -0,0 +1,119 @@
1
+ // exact-charts: the pieces every chart shares: the value axis' labels, the
2
+ // x labels, a legend, the empty and loading states and the readout shown for
3
+ // a selected point. Text wears the platform's text roles, never a series'
4
+ // colour; the swatch beside it carries the series.
5
+
6
+ use ChartSeries, ChartAxis from "./shapes.contract"
7
+ use labelAt, valueAt, tintOf, xAt, bandAt, centredLeft, centredWidth, labelStride, showsLabel from "./scale.contract"
8
+ use tickText, chartValue from "./format.contract"
9
+
10
+ // What a chart reads of the screen: reduced motion, and the width that
11
+ // decides how many x labels fit.
12
+ shape ChartViewport
13
+ prefersReducedMotion: bool
14
+ width: number
15
+
16
+ keyframes chartReveal
17
+ from opacity=0
18
+ keyframes chartGrow
19
+ from translate="0px 100%"
20
+ keyframes chartBreathe
21
+ 50% opacity=0.45
22
+
23
+ // Axis labels are capped at 14 points (at the largest text sizes as well),
24
+ // as a calendar caps its day cells: each must sit on its gridline.
25
+ //
26
+ // The value axis' labels, top to bottom, each centred on its gridline: the
27
+ // column overhangs the plot by half a line above and below, and its labels
28
+ // are spread evenly (the ticks are evenly spaced). It sits at the inline
29
+ // start, so right to left it is on the right.
30
+ component ChartYLabels
31
+ props
32
+ id: string
33
+ ticks: number[]
34
+ axis: ChartAxis
35
+ height: number
36
+ view
37
+ column height=`${height + 18}px` margin-top=-9 justify-content="space-between" align-self="flex-start" flex-shrink=0 aria-hidden=true
38
+ for k in sortBy(range(ticks.length), k => k, "desc") key=`${k}`
39
+ text tickText(axis, ticks, k) font-size="min(-exact-caption1, 14px)" line-height="18px" color="-exact-secondary-label" font-variant-numeric="tabular-nums" text-align="end" white-space="nowrap" testId=`${id}-tick-${k}`
40
+
41
+ // The x labels under a line or area plot, at their points: the first starts
42
+ // at the plot's left, the last ends at its right, the rest are centred. At
43
+ // most `most` show. The plot is not mirrored right to left (a time axis runs
44
+ // left to right, as Apple's and Android's charts draw it), so these are
45
+ // placed by `left`.
46
+ component ChartXLabels
47
+ props
48
+ labels: string[]
49
+ count: number
50
+ most: number
51
+ bands: bool
52
+ view
53
+ view position="relative" height=20 overflow="hidden" aria-hidden=true
54
+ for i in range(count) key=`${i}`
55
+ if showsLabel(i, count, most) and labelAt(labels, i) != ""
56
+ if bands
57
+ text labelAt(labels, i) position="absolute" top=0 left=`${centredLeft((bandAt(i, count) + 500 / count) / 10, labelStride(count, most) * 100 / count)}%` width=`${centredWidth((bandAt(i, count) + 500 / count) / 10, labelStride(count, most) * 100 / count)}%` text-align="center" font-size="min(-exact-caption1, 14px)" line-height="18px" color="-exact-secondary-label" white-space="nowrap"
58
+ else if i == 0 and count > 1
59
+ text labelAt(labels, i) position="absolute" top=0 left="0%" font-size="min(-exact-caption1, 14px)" line-height="18px" color="-exact-secondary-label" white-space="nowrap"
60
+ else if i == count - 1 and count > 1
61
+ text labelAt(labels, i) position="absolute" top=0 right="0%" font-size="min(-exact-caption1, 14px)" line-height="18px" color="-exact-secondary-label" white-space="nowrap"
62
+ else
63
+ text labelAt(labels, i) position="absolute" top=0 left=`${centredLeft(xAt(i, count) / 10, labelStride(count, most) * 100 / max(count - 1, 1))}%` width=`${centredWidth(xAt(i, count) / 10, labelStride(count, most) * 100 / max(count - 1, 1))}%` text-align="center" font-size="min(-exact-caption1, 14px)" line-height="18px" color="-exact-secondary-label" white-space="nowrap"
64
+
65
+ // A legend: a swatch and the series' name each, wrapping. A chart shows it
66
+ // for two series or more (one series is named by the chart's label).
67
+ component ChartLegend
68
+ props
69
+ series: ChartSeries[]
70
+ view
71
+ row flex-wrap="wrap" column-gap=16 row-gap=4 aria-hidden=true
72
+ for s, j in series key=s.name
73
+ row gap=6 align-items="center"
74
+ view width=10 height=10 border-radius=3 background-color=tintOf(s.tint, j)
75
+ text s.name font="-exact-footnote" color="-exact-secondary-label"
76
+
77
+ // The readout over the plot: the selected point's x label, then each
78
+ // series' swatch, name and value; with nothing selected, the last point's.
79
+ // It keeps its height either way, so choosing a point moves nothing, and a
80
+ // finger on the plot never covers it.
81
+ component ChartReadout
82
+ props
83
+ series: ChartSeries[]
84
+ title: string
85
+ index: number
86
+ axis: ChartAxis
87
+ view
88
+ row flex-wrap="wrap" align-items="baseline" column-gap=12 row-gap=2 min-height=20 aria-hidden=true
89
+ if title != ""
90
+ text title font="-exact-footnote" color="-exact-secondary-label" white-space="nowrap"
91
+ for s, j in series key=s.name
92
+ if index >= 0 and index < s.values.length
93
+ row gap=6 align-items="center"
94
+ view width=8 height=8 border-radius="50%" background-color=tintOf(s.tint, j)
95
+ if series.length > 1
96
+ text s.name font="-exact-footnote" color="-exact-secondary-label" white-space="nowrap"
97
+ text chartValue(valueAt(s.values, index), axis) font="-exact-footnote" font-weight=600 color="-exact-label" font-variant-numeric="tabular-nums" white-space="nowrap"
98
+
99
+ // The app's text where the chart would be, in the chart's own height.
100
+ component ChartEmpty
101
+ props
102
+ id: string
103
+ text: string
104
+ height: number
105
+ view
106
+ column testId=`${id}-empty` height=height align-items="center" justify-content="center" padding=16 border-radius=12 background-color="-exact-secondary-fill"
107
+ text text font="-exact-footnote" color="-exact-secondary-label" text-align="center"
108
+
109
+ // A pulsing placeholder in the chart's height while its data loads, with the
110
+ // platform's spinner named by the chart's label. Still under reduced motion.
111
+ component ChartLoading
112
+ props
113
+ id: string
114
+ label: string
115
+ height: number
116
+ still: bool
117
+ view
118
+ column testId=`${id}-loading` aria-busy=true height=height align-items="center" justify-content="center" border-radius=12 background-color="-exact-secondary-fill" animation=(still ? "none" : "chartBreathe 1.6s ease-in-out infinite")
119
+ progress aria-label=label
@@ -0,0 +1,68 @@
1
+ // exact-charts: pie and donut charts. Slices run clockwise from the top in
2
+ // the order given, a hairline of the page's background between them. The
3
+ // legend beside the chart lists each slice with its value and share and is
4
+ // where a person (or a screen reader) picks one; a picked slice stays full
5
+ // and the rest fade, and a donut's centre names it.
6
+
7
+ use ChartSlice, ChartAxis from "./shapes.contract"
8
+ use labelAt, tintOf, slicePath from "./scale.contract"
9
+ use chartValue from "./format.contract"
10
+ use ChartViewport, ChartEmpty, ChartLoading, chartReveal from "./parts.contract"
11
+
12
+ fn sliceTotal(slices: ChartSlice[]): number = sum(slices.map(s => max(0, s.value)))
13
+ fn sliceStart(slices: ChartSlice[], j: number): number = sum(slices.slice(0, j).map(s => max(0, s.value))) / max(sliceTotal(slices), 0.000001)
14
+ fn sliceShare(slices: ChartSlice[], j: number): number = sliceStart(slices, j + 1) - sliceStart(slices, j)
15
+ fn sliceAt(slices: ChartSlice[], j: number): string = match slices.at(j) { case some(s) => s.label, case none => "" }
16
+ fn sliceValueAt(slices: ChartSlice[], j: number): number = match slices.at(j) { case some(s) => s.value, case none => 0 }
17
+
18
+ // A pie (`donut` false) or donut. `centerTitle` and `centerValue` are the
19
+ // donut's centre with nothing picked (a total and its name); a picked
20
+ // slice's label and value replace them. `size` is the chart's width and
21
+ // height. `pick` hears the slice's index, or -1 when it is picked again.
22
+ component PieChart
23
+ props
24
+ id: string
25
+ slices: ChartSlice[]
26
+ axis: ChartAxis
27
+ donut: bool
28
+ centerTitle: string
29
+ centerValue: string
30
+ label: string
31
+ emptyText: string
32
+ loading: bool
33
+ size: number
34
+ pick: action
35
+ resource screen = exactViewport() as shape ChartViewport
36
+ state chosen = -1
37
+ derive still = screen.prefersReducedMotion
38
+ derive picked = chosen < slices.length ? chosen : -1
39
+ derive inner = donut ? 58 : 0
40
+ action tapSlice(j: number)
41
+ let next = chosen == j ? -1 : j
42
+ chosen = next
43
+ pick(next)
44
+ view
45
+ if loading
46
+ ChartLoading(id=id, label=label, height=size, still=still)
47
+ else if sliceTotal(slices) <= 0
48
+ ChartEmpty(id=id, text=emptyText, height=size)
49
+ else
50
+ row flex-wrap="wrap" align-items="center" gap=20 testId=id
51
+ view position="relative" width=size height=size flex-shrink=0 role="img" aria-label=label testId=`${id}-plot`
52
+ svg width="100%" height="100%" viewBox="0 0 200 200" aria-hidden=true
53
+ g animation=(still ? "none" : "chartReveal 500ms ease-out both")
54
+ for s, j in slices key=s.label
55
+ if s.value > 0
56
+ path d=slicePath(sliceStart(slices, j), sliceStart(slices, j + 1), 96, inner) fill=tintOf(s.tint, j) stroke="-exact-background" stroke-width=(slices.length > 1 ? 2 : 0) stroke-linejoin="round" opacity=(picked < 0 or picked == j ? 1 : 0.35) transition=(still ? "none" : "opacity 150ms ease")
57
+ if donut
58
+ column position="absolute" inset=0 align-items="center" justify-content="center" padding=`${size / 5}px` pointer-events="none" aria-hidden=true
59
+ text (picked >= 0 ? chartValue(sliceValueAt(slices, picked), axis) : centerValue) font="-exact-headline" color="-exact-label" font-variant-numeric="tabular-nums" text-align="center" testId=`${id}-center`
60
+ text (picked >= 0 ? sliceAt(slices, picked) : centerTitle) font="-exact-caption1" color="-exact-secondary-label" text-align="center"
61
+ column flex="1 1 12rem" min-width=0 gap=2
62
+ for s, j in slices key=s.label
63
+ row flex-wrap="wrap" column-gap=8 row-gap=2 align-items="center" padding="6px 8px" min-height=44 border-radius=8 background-color=(picked == j ? "-exact-secondary-fill" : "transparent") press=tapSlice(j) role="button" aria-label=`${s.label}, ${chartValue(s.value, axis)}, ${formatNumber(sliceShare(slices, j), "percent")}` aria-pressed=(picked == j) testId=`${id}-slice-${j}`
64
+ view width=10 height=10 border-radius=3 flex-shrink=0 background-color=tintOf(s.tint, j)
65
+ text s.label flex="1 1 5rem" min-width=0 font="-exact-footnote" color="-exact-label"
66
+ row gap=8 align-items="baseline"
67
+ text chartValue(s.value, axis) font="-exact-footnote" color="-exact-secondary-label" font-variant-numeric="tabular-nums" white-space="nowrap"
68
+ text formatNumber(sliceShare(slices, j), "percent") min-width=36 text-align="end" font="-exact-footnote" font-weight=600 color="-exact-label" font-variant-numeric="tabular-nums" white-space="nowrap"
@@ -0,0 +1,120 @@
1
+ // exact-charts: scales, ticks and geometry. Contract has no `pow` or `log`,
2
+ // so a nice step is the first of a fixed 1, 2, 2.5, 5 table that fits.
3
+ // Every plot is drawn in a 1000 by 1000 view box that stretches to its
4
+ // box (`preserveAspectRatio="none"`, strokes `non-scaling-stroke`).
5
+
6
+ use ChartSeries, ChartAxis from "./shapes.contract"
7
+
8
+ fn chartSteps(): number[] = [0.000001, 0.000002, 0.0000025, 0.000005, 0.00001, 0.00002, 0.000025, 0.00005, 0.0001, 0.0002, 0.00025, 0.0005, 0.001, 0.002, 0.0025, 0.005, 0.01, 0.02, 0.025, 0.05, 0.1, 0.2, 0.25, 0.5, 1, 2, 2.5, 5, 10, 20, 25, 50, 100, 200, 250, 500, 1000, 2000, 2500, 5000, 10000, 20000, 25000, 50000, 100000, 200000, 250000, 500000, 1000000, 2000000, 2500000, 5000000, 10000000, 20000000, 25000000, 50000000, 100000000, 200000000, 250000000, 500000000, 1000000000, 2000000000, 2500000000, 5000000000, 10000000000, 20000000000, 25000000000, 50000000000, 100000000000, 200000000000, 250000000000, 500000000000, 1000000000000, 2000000000000, 2500000000000, 5000000000000, 10000000000000, 20000000000000, 25000000000000, 50000000000000, 100000000000000, 200000000000000, 250000000000000, 500000000000000, 1000000000000000]
9
+
10
+ // The smallest step that splits `span` into at most `count` intervals and
11
+ // is a whole number of `unit`s (0: any step), so a tick written to that unit
12
+ // is the tick's own value: an axis of whole numbers never steps by 2.5.
13
+ fn wholeUnits(step: number, unit: number): bool = unit <= 0 or (step > unit / 2 and absOf(step / unit - round(step / unit)) < 0.001)
14
+ fn niceStep(span: number, count: number, unit: number): number = match first(chartSteps().filter(s => span / s <= count and wholeUnits(s, unit))) { case some(v) => v, case none => 1000000000000000 }
15
+
16
+ fn listMin(xs: number[]): number = match first(sortBy(xs, x => x)) { case some(v) => v, case none => 0 }
17
+ fn listMax(xs: number[]): number = match first(sortBy(xs, x => x, "desc")) { case some(v) => v, case none => 0 }
18
+ fn valueAt(xs: number[], i: number): number = match xs.at(i) { case some(v) => v, case none => 0 }
19
+ fn labelAt(xs: string[], i: number): string = match xs.at(i) { case some(v) => v, case none => "" }
20
+ fn absOf(n: number): number = max(n, -n)
21
+ fn clampTo(n: number, lo: number, hi: number): number = max(lo, min(hi, n))
22
+
23
+ // Every value of every series, and the longest series' length.
24
+ fn seriesValues(series: ChartSeries[]): number[] = series.map(s => s.values).flat()
25
+ fn seriesLength(series: ChartSeries[]): number = listMax(series.map(s => s.values.length))
26
+ fn hasData(series: ChartSeries[]): bool = seriesValues(series).length > 0
27
+
28
+ // Stacked totals at each x, and the sum of the series below `j` at `i`.
29
+ fn stackTotals(series: ChartSeries[]): number[] = range(seriesLength(series)).map(i => sum(series.map(s => valueAt(s.values, i))))
30
+ fn stackBelow(series: ChartSeries[], j: number, i: number): number = sum(series.slice(0, j).map(s => valueAt(s.values, i)))
31
+
32
+ // The data's ends, with zero in them when `zero` (bars always), widened
33
+ // around a flat line so it has a span (all zeros: from zero to one).
34
+ fn dataLo(values: number[], zero: bool): number = zero ? min(0, listMin(values)) : listMin(values)
35
+ fn dataHi(values: number[], zero: bool): number = zero ? max(0, listMax(values)) : listMax(values)
36
+ fn flatPad(v: number): number = v == 0 ? 1 : absOf(v) / 2
37
+ fn padLo(lo: number, hi: number): number = hi > lo or lo == 0 ? lo : lo - flatPad(lo)
38
+ fn padHi(lo: number, hi: number): number = hi > lo ? hi : hi + flatPad(hi)
39
+
40
+ fn ticksFrom(a: number, b: number, step: number): number[] = range(round((b - a) / step) + 1).map(i => a + i * step)
41
+ fn niceTicksStep(lo: number, hi: number, step: number): number[] = ticksFrom(floor(lo / step) * step, ceil(hi / step) * step, step)
42
+ // Nice ticks over [lo, hi]: about `count` intervals of a 1, 2, 2.5 or 5 step,
43
+ // the first at or below `lo` and the last at or above `hi`.
44
+ fn niceTicks(lo: number, hi: number, count: number): number[] = unitTicks(lo, hi, count, 0)
45
+ fn unitTicks(lo: number, hi: number, count: number, unit: number): number[] = niceTicksStep(padLo(lo, hi), padHi(lo, hi), niceStep(padHi(lo, hi) - padLo(lo, hi), count, unit))
46
+ // The smallest difference an axis' numbers show (0 for `compact`, whose
47
+ // digits follow the number).
48
+ fn axisUnit(axis: ChartAxis): number = axis.format == "compact" ? 0 : (axis.format == "percent" ? 0.01 : (axis.digits >= 3 ? 0.001 : (axis.digits == 2 ? 0.01 : (axis.digits == 1 ? 0.1 : 1))))
49
+ fn evenTicks(lo: number, hi: number, count: number): number[] = range(count + 1).map(i => lo + i * (hi - lo) / count)
50
+ fn optionOr(o: option<number>, fallback: number): number = match o { case some(v) => v, case none => fallback }
51
+ fn isPinned(axis: ChartAxis): bool = match axis.min { case some(v) => true, case none => match axis.max { case some(w) => true, case none => false } }
52
+ fn pinnedTicks(lo: number, hi: number, count: number): number[] = hi > lo ? evenTicks(lo, hi, count) : evenTicks(padLo(lo, hi), padHi(lo, hi), count)
53
+
54
+ // The value axis' ticks for these values: the app's, or even ones between
55
+ // a pinned end and the data's, or nice ones. The axis spans first to last.
56
+ fn axisTicks(values: number[], axis: ChartAxis, zero: bool, count: number): number[] = axis.ticks.length >= 2 ? axis.ticks : (isPinned(axis) ? pinnedTicks(optionOr(axis.min, dataLo(values, zero)), optionOr(axis.max, dataHi(values, zero)), count) : unitTicks(dataLo(values, zero), dataHi(values, zero), count, axisUnit(axis)))
57
+
58
+ // View-box positions: y of a value, x of a line's point, a bar band's left.
59
+ fn yAt(v: number, lo: number, hi: number): number = 1000 - (clampTo(v, lo, hi) - lo) / (hi - lo) * 1000
60
+ fn xAt(i: number, n: number): number = n <= 1 ? 500 : i * 1000 / (n - 1)
61
+ fn bandAt(i: number, n: number): number = i * 1000 / max(n, 1)
62
+
63
+ // A label's box centred on `at` percent of the plot: one label slot wide, or
64
+ // as wide as fits inside the plot. Centred with no translate (Linux doubles
65
+ // glyphs at a fraction) and starting inside the plot (Android drops a clipped
66
+ // text that starts before it).
67
+ fn centredWidth(at: number, slot: number): number = min(slot, 2 * min(at, 100 - at))
68
+ fn centredLeft(at: number, slot: number): number = at - centredWidth(at, slot) / 2
69
+
70
+ fn baseOf(lo: number, hi: number): number = clampTo(0, lo, hi)
71
+
72
+ // A line through `values` on an x axis of `n` points, and the same closed
73
+ // down to the baseline (zero, or the nearer end) as an area.
74
+ fn linePath(values: number[], n: number, lo: number, hi: number): string = values.map((v, i) => `${i == 0 ? "M" : "L"}${xAt(i, n)} ${yAt(v, lo, hi)}`).join(" ")
75
+ fn areaPath(values: number[], n: number, lo: number, hi: number): string = values.length == 0 ? "" : `${linePath(values, n, lo, hi)} L${xAt(values.length - 1, n)} ${yAt(baseOf(lo, hi), lo, hi)} L${xAt(0, n)} ${yAt(baseOf(lo, hi), lo, hi)} Z`
76
+
77
+ // Bars: a band per x; grouped bars share 72% of it side by side, a stack
78
+ // takes 56% of it. A stacked segment above the first leaves a hairline gap.
79
+ fn barLeft(i: number, j: number, n: number, k: number, stacked: bool): number = stacked ? bandAt(i, n) + 220 / max(n, 1) : bandAt(i, n) + 140 / max(n, 1) + j * 720 / max(n, 1) / max(k, 1) + 36 / max(n, 1) / max(k, 1)
80
+ fn barWidth(n: number, k: number, stacked: bool): number = stacked ? 560 / max(n, 1) : 720 / max(n, 1) / max(k, 1) * 0.9
81
+ fn barTop(v: number, below: number, lo: number, hi: number): number = min(yAt(below + v, lo, hi), yAt(below, lo, hi))
82
+ fn barHeight(v: number, below: number, gap: number, lo: number, hi: number): number = max(0, absOf(yAt(below, lo, hi) - yAt(below + v, lo, hi)) - gap)
83
+
84
+ // A pie's point at `turn` (0 at the top, clockwise) on radius `r` around
85
+ // (100, 100), and a slice's path from turn a to b; `inner` > 0 is a donut.
86
+ fn arcX(turn: number, r: number): number = 100 + r * sin(turn * 6.283185307179586)
87
+ fn arcY(turn: number, r: number): number = 100 - r * cos(turn * 6.283185307179586)
88
+ fn arcFlag(a: number, b: number): number = b - a > 0.5 ? 1 : 0
89
+ fn ringPath(r: number, inner: number): string = inner > 0 ? `M100 ${100 - r} A${r} ${r} 0 1 1 100 ${100 + r} A${r} ${r} 0 1 1 100 ${100 - r} Z M100 ${100 - inner} A${inner} ${inner} 0 1 0 100 ${100 + inner} A${inner} ${inner} 0 1 0 100 ${100 - inner} Z` : `M100 ${100 - r} A${r} ${r} 0 1 1 100 ${100 + r} A${r} ${r} 0 1 1 100 ${100 - r} Z`
90
+ fn wedgePath(a: number, b: number, r: number, inner: number): string = inner > 0 ? `M${arcX(a, r)} ${arcY(a, r)} A${r} ${r} 0 ${arcFlag(a, b)} 1 ${arcX(b, r)} ${arcY(b, r)} L${arcX(b, inner)} ${arcY(b, inner)} A${inner} ${inner} 0 ${arcFlag(a, b)} 0 ${arcX(a, inner)} ${arcY(a, inner)} Z` : `M100 100 L${arcX(a, r)} ${arcY(a, r)} A${r} ${r} 0 ${arcFlag(a, b)} 1 ${arcX(b, r)} ${arcY(b, r)} Z`
91
+ fn slicePath(a: number, b: number, r: number, inner: number): string = b - a >= 0.9999 ? ringPath(r, inner) : wedgePath(a, b, r, inner)
92
+
93
+ // A point's touch band, as percentages of the plot's width: halfway to each
94
+ // neighbour, clamped to the plot.
95
+ fn hitLeft(i: number, n: number): number = n <= 1 ? 0 : max(0, (i - 0.5) / (n - 1)) * 100
96
+ fn hitWidth(i: number, n: number): number = n <= 1 ? 100 : min(1, (i + 0.5) / (n - 1)) * 100 - hitLeft(i, n)
97
+
98
+ // A dense series gets fewer touch bands than points, about
99
+ // 24 points wide: band `b` of `bands` covers an equal slice of the plot and
100
+ // selects the point at its middle.
101
+ fn touchBands(n: number, most: number): number = min(n, most)
102
+ fn bandPoint(b: number, bands: number, n: number): number = bands >= n ? b : round((b + 0.5) / bands * (n - 1))
103
+ fn touchLeft(b: number, bands: number, n: number): number = bands >= n ? hitLeft(b, n) : b * 100 / bands
104
+ fn touchWidth(b: number, bands: number, n: number): number = bands >= n ? hitWidth(b, n) : 100 / bands
105
+
106
+ // Which x labels show: every `stride`-th, so at most `most` of `n` do.
107
+ fn labelStride(n: number, most: number): number = max(1, ceil(n / max(most, 1)))
108
+ // How many x labels of this text fit a plot about `width` points wide (the
109
+ // screen's, less the value axis, up to a 45rem column) at the 14-point cap,
110
+ // about 7 points a character with a gap between.
111
+ fn longestLabel(labels: string[]): number = listMax(labels.map(t => t.length))
112
+ fn labelRoom(width: number, labels: string[], most: number): number = max(2, min(most, floor((min(width, 720) - 96) / (longestLabel(labels) * 7 + 24))))
113
+ fn showsLabel(i: number, n: number, most: number): bool = i % labelStride(n, most) == 0
114
+
115
+ // The palette: platform roles that follow light and dark, in a fixed order
116
+ // (blue, orange, purple, green, pink, indigo; validated for a normal-vision
117
+ // floor; legends and tooltips carry identity besides colour).
118
+ fn chartPalette(): string[] = ["-exact-system-blue", "-exact-system-orange", "-exact-system-purple", "-exact-system-green", "-exact-system-pink", "-exact-system-indigo"]
119
+ fn chartTint(i: number): string = labelAt(chartPalette(), i % 6)
120
+ fn tintOf(tint: string, i: number): string = tint == "" ? chartTint(i) : tint
@@ -0,0 +1,31 @@
1
+ // exact-charts: the records a chart draws. Every string here is the app's
2
+ // own (a series' name, a slice's label): the package has no words of its own.
3
+
4
+ // One line, area or bar series. `values` are in x order, one per x label;
5
+ // `tint` is a colour role or token (`-exact-system-blue`, `var(--brand)`),
6
+ // or "" for the package's palette slot at the series' place.
7
+ shape ChartSeries
8
+ name: string
9
+ values: number[]
10
+ tint: string
11
+
12
+ // One slice of a pie or donut. `value` is its size; `tint` as a series'.
13
+ shape ChartSlice
14
+ label: string
15
+ value: number
16
+ tint: string
17
+
18
+ // How the value axis is ranged and its numbers written.
19
+ // `format` is a `formatNumber` style ("decimal", "compact", "percent"), and
20
+ // `digits` its fraction digits; `unit` follows every number (" kW", "%").
21
+ // `min` and `max` pin an end (none: a nice end from the data). `ticks`, when
22
+ // it has two or more, are the axis' gridlines, evenly spaced, and
23
+ // `tickLabels` (same length, or empty) the app's own text for them.
24
+ shape ChartAxis
25
+ format: string
26
+ digits: number
27
+ unit: string
28
+ min: option<number>
29
+ max: option<number>
30
+ ticks: number[]
31
+ tickLabels: string[]
@@ -0,0 +1,58 @@
1
+ // exact-charts: small charts with no axes, for a row or a card. Each is one
2
+ // image to a screen reader, named by the app's `label` (say what it shows:
3
+ // "Rising, 12 to 31 kW this week").
4
+
5
+ use listMin, listMax, labelAt, linePath, areaPath, padLo, padHi from "./scale.contract"
6
+ use ChartViewport, chartReveal, chartGrow from "./parts.contract"
7
+
8
+ // A sparkline: the values' line in `tint`, filled below when `filled`,
9
+ // scaled to their own range. It takes the width it is given.
10
+ component Sparkline
11
+ props
12
+ values: number[]
13
+ tint: string
14
+ filled: bool
15
+ label: string
16
+ height: number
17
+ resource screen = exactViewport() as shape ChartViewport
18
+ derive lo = padLo(listMin(values), listMax(values))
19
+ derive hi = padHi(listMin(values), listMax(values))
20
+ view
21
+ view height=height min-width=24 role="img" aria-label=label
22
+ if values.length > 1
23
+ svg width="100%" height="100%" viewBox="0 0 1000 1000" preserveAspectRatio="none" overflow="visible" aria-hidden=true
24
+ g animation=(screen.prefersReducedMotion ? "none" : "chartReveal 400ms ease-out both")
25
+ if filled
26
+ path d=areaPath(values, values.length, lo, hi) fill=tint fill-opacity=0.18 stroke="none"
27
+ path d=linePath(values, values.length, lo, hi) fill="none" stroke=tint stroke-width=1.5 stroke-linejoin="round" stroke-linecap="round" vector-effect="non-scaling-stroke"
28
+
29
+ // A strip of bars from zero, one per value, for a small fact (a station's
30
+ // usual occupancy by hour). `max` is the top (0: the largest value);
31
+ // `highlight` is the index drawn in full `tint` (now, today), the rest
32
+ // paler, or -1 for all full. `labels` are the app's, one per bar or "" for
33
+ // none; the label at the start of every `ceil(n / 8)` bars shows, so at
34
+ // most eight do. The strip follows the writing direction.
35
+ component Bars
36
+ props
37
+ id: string
38
+ values: number[]
39
+ labels: string[]
40
+ highlight: number
41
+ tint: string
42
+ max: number
43
+ label: string
44
+ height: number
45
+ resource screen = exactViewport() as shape ChartViewport
46
+ derive top = max > 0 ? max : max(listMax(values), 0.000001)
47
+ derive stride = max(1, ceil(labels.length / 8))
48
+ view
49
+ column gap=4 role="img" aria-label=label testId=id
50
+ row height=height align-items="flex-end" gap=2
51
+ // exact-accept lower-key-position
52
+ for v, i in values key=`${i}`
53
+ column flex=1 min-width=0 height="100%" justify-content="flex-end" overflow="hidden"
54
+ view height=`${min(1, max(0, v) / top) * 100}%` min-height=2 border-radius="3px 3px 1px 1px" background-color=tint opacity=(highlight < 0 or highlight == i ? 1 : 0.38) animation=(screen.prefersReducedMotion ? "none" : `chartGrow 450ms ${i * 18}ms ease-out both`) testId=`${id}-bar-${i}`
55
+ if labels.length > 0
56
+ row aria-hidden=true
57
+ for g in range(ceil(values.length / stride)) key=`${g}`
58
+ text labelAt(labels, g * stride) flex=min(stride, values.length - g * stride) min-width=0 text-align="start" font-size="min(-exact-caption2, 13px)" color="-exact-secondary-label" white-space="nowrap" -exact-fit="shrink"
@@ -0,0 +1,36 @@
1
+ // exact-charts: the same data as a table, a chart's accessible twin (and a
2
+ // way to read exact values). A row per x label, a column per series.
3
+
4
+ use ChartSeries, ChartAxis from "./shapes.contract"
5
+ use labelAt, valueAt, seriesLength from "./scale.contract"
6
+ use chartValue from "./format.contract"
7
+
8
+ // `caption` names the table (the chart's label) and `xTitle` heads the
9
+ // x labels' column ("Day").
10
+ component ChartTable
11
+ props
12
+ id: string
13
+ series: ChartSeries[]
14
+ xLabels: string[]
15
+ axis: ChartAxis
16
+ caption: string
17
+ xTitle: string
18
+ view
19
+ table testId=id width="100%"
20
+ caption
21
+ text caption font="-exact-footnote" color="-exact-secondary-label" text-align="start"
22
+ thead
23
+ tr
24
+ th scope="col" text-align="start"
25
+ text xTitle font="-exact-footnote" font-weight=600
26
+ for s, j in series key=s.name
27
+ th scope="col" text-align="end"
28
+ text s.name font="-exact-footnote" font-weight=600
29
+ tbody
30
+ for i in range(seriesLength(series)) key=`${i}`
31
+ tr
32
+ th scope="row" text-align="start"
33
+ text labelAt(xLabels, i) font="-exact-footnote" font-weight=400
34
+ for s, j in series key=s.name
35
+ td text-align="end"
36
+ text (i < s.values.length ? chartValue(valueAt(s.values, i), axis) : "") font="-exact-footnote" font-variant-numeric="tabular-nums"