@haakco/custd-react 0.0.0-stage → 3.71.2
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/README.md +269 -2
- package/dist/account-menu-item.d.ts +13 -0
- package/dist/account-menu-item.js +20 -0
- package/dist/app-items.d.ts +33 -0
- package/dist/app-items.js +86 -0
- package/dist/arrival-histogram.d.ts +22 -0
- package/dist/arrival-histogram.js +39 -0
- package/dist/chart-scale.d.ts +21 -0
- package/dist/chart-scale.js +94 -0
- package/dist/convergence-story.d.ts +29 -0
- package/dist/convergence-story.js +65 -0
- package/dist/forecast-chart.d.ts +30 -0
- package/dist/forecast-chart.js +175 -0
- package/dist/forecast-types.d.ts +69 -0
- package/dist/forecast-types.js +6 -0
- package/dist/hosted-app.d.ts +28 -0
- package/dist/hosted-app.js +48 -0
- package/dist/index.d.ts +43 -0
- package/dist/index.js +67 -0
- package/dist/measure-next-panel.d.ts +24 -0
- package/dist/measure-next-panel.js +23 -0
- package/dist/model-calculator.d.ts +54 -0
- package/dist/model-calculator.js +89 -0
- package/dist/model-csv.d.ts +9 -0
- package/dist/model-csv.js +17 -0
- package/dist/model-editor.d.ts +37 -0
- package/dist/model-editor.js +181 -0
- package/dist/model-shorthand.d.ts +28 -0
- package/dist/model-shorthand.js +85 -0
- package/dist/quantity-histogram.d.ts +23 -0
- package/dist/quantity-histogram.js +53 -0
- package/dist/safe-markdown.d.ts +10 -0
- package/dist/safe-markdown.js +74 -0
- package/dist/sensitivity-view.d.ts +21 -0
- package/dist/sensitivity-view.js +60 -0
- package/dist/session.d.ts +18 -0
- package/dist/session.js +43 -0
- package/dist/testing.d.ts +11 -0
- package/dist/testing.js +9 -0
- package/package.json +54 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 HaakCo
|
|
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,3 +1,270 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Custd React reporting helpers
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`@haakco/custd-react` is the optional React layer for Custd reporting. It
|
|
4
|
+
adapts TanStack Query results to the core SDK's server-owned reporting state
|
|
5
|
+
model and provides a small accessible state display.
|
|
6
|
+
|
|
7
|
+
It also shares an app user's browser sign-in session (see below).
|
|
8
|
+
|
|
9
|
+
The core `@haakco/custd-sdk` remains framework-neutral. The reporting helpers
|
|
10
|
+
do not create a Custd client or make requests: the consumer supplies a query
|
|
11
|
+
function or existing `UseQueryResult`. The session helpers wrap a core
|
|
12
|
+
`BrowserSignIn`, which holds the signed-in user's tokens in `sessionStorage`.
|
|
13
|
+
|
|
14
|
+
## Install
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pnpm add @haakco/custd-sdk@^3.71.2 @haakco/custd-react@^3.71.2
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Use the same released version for both packages; both are public on npmjs. These examples were verified on
|
|
21
|
+
2026-11-17 against **3.52.0**. Keep the application's installed React 18/19 and
|
|
22
|
+
TanStack Query 5 peers; do not install a different React copy for this helper.
|
|
23
|
+
GitHub tags with checked-in distributions are the publication owner, not a
|
|
24
|
+
private registry. The state-display component renders DOM elements and is for
|
|
25
|
+
web applications; native apps use the core SDK and authenticated backend relay.
|
|
26
|
+
|
|
27
|
+
## Query and display
|
|
28
|
+
|
|
29
|
+
```tsx
|
|
30
|
+
import { CustdReportingState, useCustdReportingQuery } from "@haakco/custd-react";
|
|
31
|
+
|
|
32
|
+
const report = useCustdReportingQuery({
|
|
33
|
+
queryKey: ["report", request],
|
|
34
|
+
queryFn: () => appApi.reporting.query(request),
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
return (
|
|
38
|
+
<CustdReportingState view={report.view} onRetry={() => report.refetch()}>
|
|
39
|
+
{(data) => <ReportChart data={data} />}
|
|
40
|
+
</CustdReportingState>
|
|
41
|
+
);
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Use `getCustdReportingViewState(query)` or
|
|
45
|
+
`useCustdReportingViewState(query)` when the application already owns the
|
|
46
|
+
TanStack Query call. `getCustdReportingDisplayState(view)` returns one of
|
|
47
|
+
`loading`, `error`, `unavailable`, `empty`, `stale`, `partial`,
|
|
48
|
+
`stale_partial`, or `ready`.
|
|
49
|
+
|
|
50
|
+
`CustdReportingState` preserves useful stale/partial data for the consumer's
|
|
51
|
+
content renderer, renders semantic `status` or `alert` feedback, and only
|
|
52
|
+
shows the retry button when Custd marks the result retryable. Consumers own
|
|
53
|
+
placement, wording, and styling through `labels`, `renderState`, and
|
|
54
|
+
`className`.
|
|
55
|
+
|
|
56
|
+
## App user sign-in
|
|
57
|
+
|
|
58
|
+
```tsx
|
|
59
|
+
import { BrowserSignIn } from "@haakco/custd-sdk";
|
|
60
|
+
import { CustdSessionProvider, useCustdSession } from "@haakco/custd-react";
|
|
61
|
+
|
|
62
|
+
const signIn = new BrowserSignIn(config); // see the core SDK README
|
|
63
|
+
|
|
64
|
+
<CustdSessionProvider client={signIn}>
|
|
65
|
+
<App />
|
|
66
|
+
</CustdSessionProvider>;
|
|
67
|
+
|
|
68
|
+
function Account() {
|
|
69
|
+
const { status, session, error, signIn, signOut } = useCustdSession();
|
|
70
|
+
if (status === "signing_in") return <p role="status">Signing in…</p>;
|
|
71
|
+
if (status === "error") return <p role="alert">Sign-in failed ({error?.code}). <button onClick={() => signIn()}>Try again</button></p>;
|
|
72
|
+
if (status === "signed_in") return <button onClick={() => signOut()}>Sign out</button>;
|
|
73
|
+
return <button onClick={() => signIn()}>Sign in</button>;
|
|
74
|
+
}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
The provider calls `restore()` on mount, which completes a sign-in redirect
|
|
78
|
+
and then replaces the URL with the saved `returnTo` path (override with
|
|
79
|
+
`onSignInComplete`), or refreshes an expired session. `status` is one of
|
|
80
|
+
`signed_out`, `signing_in`, `signed_in` or `error`; `session` is set only when
|
|
81
|
+
signed in. The consumer owns placement, wording and styling.
|
|
82
|
+
|
|
83
|
+
## Application account settings
|
|
84
|
+
|
|
85
|
+
Put the account button in the signed-in application menu. It asks the issuer for
|
|
86
|
+
a one-use ticket and opens hosted settings in the same tab, and settings shows a
|
|
87
|
+
verified **Back to <app>** link. Pass `returnPath` to choose the page that link
|
|
88
|
+
opens; it is recommended, and without it the link opens the app's home. Use a
|
|
89
|
+
fixed path such as `/mine`, never the current URL: apps keep link tokens in paths
|
|
90
|
+
and fragments.
|
|
91
|
+
|
|
92
|
+
```tsx
|
|
93
|
+
import { CustdAccountMenuItem, useCustdSession } from "@haakco/custd-react";
|
|
94
|
+
|
|
95
|
+
function AccountMenu({ issuer }: { issuer: string }) {
|
|
96
|
+
const { session } = useCustdSession();
|
|
97
|
+
if (!session) return null;
|
|
98
|
+
return <CustdAccountMenuItem issuer={issuer} accessToken={() => session.accessToken} returnPath="/mine" />;
|
|
99
|
+
}
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
The page's origin must be registered for the application, which a hosted app's
|
|
103
|
+
is. Without React, call `openAppAccountSettings` from `@haakco/custd-sdk/browser`
|
|
104
|
+
with the same options.
|
|
105
|
+
|
|
106
|
+
Read and change the signed-in member's profile with the current app profile client:
|
|
107
|
+
|
|
108
|
+
```tsx
|
|
109
|
+
import { CurrentAppProfileClient } from "@haakco/custd-sdk/browser";
|
|
110
|
+
|
|
111
|
+
const profile = new CurrentAppProfileClient({
|
|
112
|
+
apiBaseUrl: "https://api.custd.com",
|
|
113
|
+
accessToken: getCurrentAppAccessToken,
|
|
114
|
+
});
|
|
115
|
+
const { fields, managedPhoto } = await profile.read();
|
|
116
|
+
const photo = managedPhoto ? await profile.readPhoto() : null;
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
The access token getter returns the signed-in member's current application
|
|
120
|
+
grant with the `profile` scope. On a gateway-owned session, keep the forwarded
|
|
121
|
+
grant on the app server and read the profile there. The field policy reports
|
|
122
|
+
which values can be edited. Use `uploadPhoto` and `removePhoto` for a managed
|
|
123
|
+
photo, and release any object URL the app creates from a returned blob. When importing
|
|
124
|
+
existing app data, `initialize` and `initializePhoto` fill only fields that
|
|
125
|
+
have never been written. Use the returned profile, which includes any current
|
|
126
|
+
value saved concurrently. A cleared value remains initialized.
|
|
127
|
+
|
|
128
|
+
A gateway-owned session keeps the app bearer on the server. There the backend
|
|
129
|
+
calls `createAppAccountEntry` (or Go's `CreateAppAccountEntry`) with the
|
|
130
|
+
forwarded bearer, the configured issuer, the registered app origin and an
|
|
131
|
+
optional `returnPath`. It renders the returned action and ticket as an escaped
|
|
132
|
+
native form on the app origin: a top-level, same-tab POST. Keep the ticket out of
|
|
133
|
+
URLs, logs, browser storage and cached responses.
|
|
134
|
+
|
|
135
|
+
```tsx
|
|
136
|
+
<form action={entry.actionUrl} method="post" target="_self">
|
|
137
|
+
<input type="hidden" name="ticket" value={entry.ticket} />
|
|
138
|
+
<button type="submit">Account settings</button>
|
|
139
|
+
</form>
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
## Hosted apps
|
|
143
|
+
|
|
144
|
+
An app Custd hosts wraps its root once. The provider calls the core
|
|
145
|
+
`startHostedApp` on mount, which reads `/.well-known/custd.json` and starts
|
|
146
|
+
tracking, error capture and sign-in as the file enables them, and stops them on
|
|
147
|
+
unmount.
|
|
148
|
+
|
|
149
|
+
```tsx
|
|
150
|
+
import { CustdHostedAppProvider, useCustdHostedApp, useCustdSession } from "@haakco/custd-react";
|
|
151
|
+
|
|
152
|
+
<CustdHostedAppProvider options={{ release: import.meta.env.VITE_COMMIT }}>
|
|
153
|
+
<App />
|
|
154
|
+
</CustdHostedAppProvider>;
|
|
155
|
+
|
|
156
|
+
function Header() {
|
|
157
|
+
const hosted = useCustdHostedApp();
|
|
158
|
+
if (hosted.status !== "ready") return null; // "loading", or "error" with a typed `error.code`
|
|
159
|
+
return hosted.app.signIn ? <Account /> : null; // Account calls useCustdSession()
|
|
160
|
+
}
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
Children render while discovery loads and when it fails, so the app never
|
|
164
|
+
waits on Custd. When `sign_in` is enabled the children are wrapped in
|
|
165
|
+
`CustdSessionProvider` once ready; call `useCustdSession` only below a ready
|
|
166
|
+
app with `app.signIn`. Send typed app events with
|
|
167
|
+
`hosted.app.trackAppEvent(name, properties)`.
|
|
168
|
+
|
|
169
|
+
### Live items and forecasts
|
|
170
|
+
|
|
171
|
+
`useAppItem(token, options)`, `useAppForecast(token, options)` (latest run,
|
|
172
|
+
`empty` until the first run), `useAppForecastStory(token, options)` and
|
|
173
|
+
`useAppModelRun(token, options)` read through the provider's `app.appItems`, or
|
|
174
|
+
`options.client`. `token` is a link token, or `{ item }` for an item the
|
|
175
|
+
signed-in user owns. They return the core watched state (`loading`, `fresh`,
|
|
176
|
+
`empty`, `stale`, `offline`, `error`), `idle` while the token is empty, and
|
|
177
|
+
`refresh()`. Components watching the same item and link on the same client
|
|
178
|
+
share one poller.
|
|
179
|
+
|
|
180
|
+
`useAppMeeting(token, options)` reads a meeting item's `meeting` through the
|
|
181
|
+
same item poller, so it adds no request beside `useAppItem` on that link; an
|
|
182
|
+
item of another kind is an `error` with code `app_item_wrong_kind`.
|
|
183
|
+
|
|
184
|
+
```tsx
|
|
185
|
+
import { useAppForecast, useAppItem } from "@haakco/custd-react";
|
|
186
|
+
|
|
187
|
+
function Counter({ shareToken }: { shareToken: string }) {
|
|
188
|
+
const item = useAppItem(shareToken);
|
|
189
|
+
const forecast = useAppForecast(shareToken);
|
|
190
|
+
if (item.status === "error" && !item.data) return <p role="alert">{item.error.code}</p>;
|
|
191
|
+
if (!("data" in item) || !item.data) return <p role="status">Loading…</p>; // idle, loading, offline first read
|
|
192
|
+
return (
|
|
193
|
+
<CounterView
|
|
194
|
+
item={item.data}
|
|
195
|
+
forecast={"data" in forecast ? forecast.data : undefined}
|
|
196
|
+
stale={item.status !== "fresh"}
|
|
197
|
+
updatedAt={item.lastUpdatedAt}
|
|
198
|
+
/>
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
### Uncertainty models
|
|
204
|
+
|
|
205
|
+
`ModelEditor` edits a model's quantities (values, ranges, k of n, samples or
|
|
206
|
+
formulas) and saves a version through `onSave`; the server's `fieldErrors` land
|
|
207
|
+
on the quantity they name, and a cycle marks every quantity in it.
|
|
208
|
+
`ModelCalculator` tries other input values against a saved version: given
|
|
209
|
+
`access` (a link token) it calculates with `appItems.calculateModel`, which
|
|
210
|
+
stores nothing, and it says when the caller is rate-limited. Pass the latest run
|
|
211
|
+
as `baseline`; its `queuedRunFailure` shows when live inputs changed but the
|
|
212
|
+
queued run failed. `QuantityHistogram`, `SensitivityView` and `MeasureNextPanel`
|
|
213
|
+
draw a run's results, sensitivity and value of information, and
|
|
214
|
+
`downloadSummaryCsv` saves its summary.
|
|
215
|
+
|
|
216
|
+
```tsx
|
|
217
|
+
const run = useAppModelRun(shareToken);
|
|
218
|
+
const baseline = "data" in run ? run.data : undefined;
|
|
219
|
+
<ModelCalculator version={version} inputs={["price"]} outputs={["revenue"]} access={shareToken} baseline={baseline} />;
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
In tests, `CustdFakeHostedAppProvider` from `@haakco/custd-react/testing`
|
|
223
|
+
starts the provider against a `FakeCustd` from `@haakco/custd-sdk/testing`, so
|
|
224
|
+
the hooks above run with no network:
|
|
225
|
+
|
|
226
|
+
```tsx
|
|
227
|
+
const fake = new FakeCustd();
|
|
228
|
+
render(<CustdFakeHostedAppProvider fake={fake}><App /></CustdFakeHostedAppProvider>);
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
## Forecast charts
|
|
232
|
+
|
|
233
|
+
`ForecastChart`, `ConvergenceStory` and `ArrivalHistogram` draw Custd
|
|
234
|
+
measurement forecasts as plain SVG with no chart library. Their props use the
|
|
235
|
+
analytics API's forecast field names, so a response passes straight through:
|
|
236
|
+
|
|
237
|
+
```tsx
|
|
238
|
+
import { ArrivalHistogram, ConvergenceStory, ForecastChart } from "@haakco/custd-react";
|
|
239
|
+
|
|
240
|
+
<ForecastChart
|
|
241
|
+
title="Signups"
|
|
242
|
+
data={{
|
|
243
|
+
observations, // [{ at, value }]
|
|
244
|
+
target: project.targetValue,
|
|
245
|
+
deadline: project.deadline,
|
|
246
|
+
completionMedian: run.percentiles.p50,
|
|
247
|
+
completionInterval: run.counter?.completionInterval,
|
|
248
|
+
forecastFrom: run.forecastFrom,
|
|
249
|
+
posteriorLines: run.counter?.detail.posteriorLines,
|
|
250
|
+
}}
|
|
251
|
+
/>
|
|
252
|
+
<ArrivalHistogram title="Arrival" histogram={run.counter.detail.arrivalHistogram} deadline={project.deadline} />
|
|
253
|
+
<ConvergenceStory title="Delivery" estimates={story.delivery.estimates} targetDate={story.delivery.targetDate} staleAfterDays={7} />
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
- `ForecastChart` has zoom, pan, reset, zoom-to-data and full-screen buttons,
|
|
257
|
+
plus drag-to-pan. Escape leaves full screen. The visible range
|
|
258
|
+
is announced politely, and zoom animates only when the user has not asked for
|
|
259
|
+
reduced motion. The median line and the band run from the latest
|
|
260
|
+
measurement to the target at the median date and at the interval ends.
|
|
261
|
+
- Clients own the wording and the theme. Wording comes through `labels`,
|
|
262
|
+
`formatDate` and `formatValue`. The theme comes through `className`, `style`
|
|
263
|
+
and these CSS variables, which fall back to `currentColor`:
|
|
264
|
+
`--custd-chart-observed`, `--custd-chart-forecast`, `--custd-chart-band`,
|
|
265
|
+
`--custd-chart-target`, `--custd-chart-deadline`, `--custd-chart-trail`,
|
|
266
|
+
`--custd-chart-grid`, `--custd-chart-late`, `--custd-chart-stale` and
|
|
267
|
+
`--custd-chart-surface` (the full-screen background).
|
|
268
|
+
- Each chart has an empty state, and `ForecastChart` also shows a
|
|
269
|
+
measurements-only state. Each has a `role="img"` text alternative that can be
|
|
270
|
+
overridden with `summary`.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type ComponentPropsWithoutRef } from "react";
|
|
2
|
+
export type CustdAccountMenuItemProps = Omit<ComponentPropsWithoutRef<"button">, "onClick" | "type"> & {
|
|
3
|
+
/** The application's configured Custd issuer. */
|
|
4
|
+
issuer: string;
|
|
5
|
+
/** Returns the signed-in member's current application access token. */
|
|
6
|
+
accessToken: () => string | Promise<string>;
|
|
7
|
+
/** The page settings links back to, such as "/mine". Defaults to the application's home. */
|
|
8
|
+
returnPath?: string;
|
|
9
|
+
/** Called when the issuer refuses or cannot be reached; the button becomes usable again. */
|
|
10
|
+
onError?: (error: unknown) => void;
|
|
11
|
+
};
|
|
12
|
+
/** Opens hosted account settings in the same tab, with a verified link back to this app. */
|
|
13
|
+
export declare function CustdAccountMenuItem({ issuer, accessToken, returnPath, onError, children, disabled, ...props }: CustdAccountMenuItemProps): import("react").JSX.Element;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { openAppAccountSettings } from "@haakco/custd-sdk/browser";
|
|
3
|
+
import { useState } from "react";
|
|
4
|
+
/** Opens hosted account settings in the same tab, with a verified link back to this app. */
|
|
5
|
+
export function CustdAccountMenuItem({ issuer, accessToken, returnPath, onError, children, disabled, ...props }) {
|
|
6
|
+
const [opening, setOpening] = useState(false);
|
|
7
|
+
const open = async () => {
|
|
8
|
+
setOpening(true);
|
|
9
|
+
try {
|
|
10
|
+
await openAppAccountSettings({ issuer, accessToken: await accessToken(), returnPath });
|
|
11
|
+
}
|
|
12
|
+
catch (error) {
|
|
13
|
+
setOpening(false);
|
|
14
|
+
onError?.(error);
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
return (_jsx("button", { ...props, type: "button", disabled: disabled || opening, onClick: () => {
|
|
18
|
+
void open();
|
|
19
|
+
}, children: children ?? "Account settings" }));
|
|
20
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type AppForecastRun, type AppForecastStory, type AppItemAccess, type AppItemRead, type AppItemsClient, type AppLiveState, type AppLiveWatchOptions, type AppMeeting, type AppModelRun } from "@haakco/custd-sdk/browser";
|
|
2
|
+
/** No link token yet: nothing is read. */
|
|
3
|
+
export declare const CUSTD_APP_LIVE_IDLE = "idle";
|
|
4
|
+
export type CustdAppLiveState<T> = AppLiveState<T> | {
|
|
5
|
+
status: typeof CUSTD_APP_LIVE_IDLE;
|
|
6
|
+
};
|
|
7
|
+
/** A watched read and a `refresh` that polls now. */
|
|
8
|
+
export type CustdAppLiveResult<T> = CustdAppLiveState<T> & {
|
|
9
|
+
refresh: () => void;
|
|
10
|
+
};
|
|
11
|
+
export type UseAppLiveOptions = AppLiveWatchOptions & {
|
|
12
|
+
/** Defaults to the `CustdHostedAppProvider` app's `appItems`. */
|
|
13
|
+
client?: AppItemsClient;
|
|
14
|
+
};
|
|
15
|
+
/** A link token, or `{ item }` for an item the signed-in user owns; empty reads nothing. */
|
|
16
|
+
export type CustdAppItemAccess = AppItemAccess | null | undefined;
|
|
17
|
+
/**
|
|
18
|
+
* The item a link opens, kept fresh by conditional polling (paused while the tab is hidden).
|
|
19
|
+
* Every component watching the same item and link shares one poller.
|
|
20
|
+
*/
|
|
21
|
+
export declare function useAppItem(token: CustdAppItemAccess, options?: UseAppLiveOptions): CustdAppLiveResult<AppItemRead>;
|
|
22
|
+
/** The item's latest forecast run, kept fresh; its data is null until the first run exists. */
|
|
23
|
+
export declare function useAppForecast(token: CustdAppItemAccess, options?: UseAppLiveOptions): CustdAppLiveResult<AppForecastRun | null>;
|
|
24
|
+
/** The item's measurements and forecast story, kept fresh. */
|
|
25
|
+
export declare function useAppForecastStory(token: CustdAppItemAccess, options?: UseAppLiveOptions): CustdAppLiveResult<AppForecastStory>;
|
|
26
|
+
/** The model item's latest run, kept fresh; `empty` until the first run exists. */
|
|
27
|
+
export declare function useAppModelRun(token: CustdAppItemAccess, options?: UseAppLiveOptions): CustdAppLiveResult<AppModelRun>;
|
|
28
|
+
/**
|
|
29
|
+
* The meeting a meeting item runs, kept fresh through the item's shared poller, so it costs no
|
|
30
|
+
* extra request beside `useAppItem` on the same link. An item of another kind is an `error`
|
|
31
|
+
* with code `app_item_wrong_kind`.
|
|
32
|
+
*/
|
|
33
|
+
export declare function useAppMeeting(token: CustdAppItemAccess, options?: UseAppLiveOptions): CustdAppLiveResult<AppMeeting>;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { APP_ITEM_ERROR_CODES, APP_LIVE_STATUSES, AppItemError, HOSTED_APP_STATUSES, } from "@haakco/custd-sdk/browser";
|
|
2
|
+
import { useMemo, useSyncExternalStore } from "react";
|
|
3
|
+
import { CUSTD_HOSTED_APP_LOADING, useOptionalCustdHostedApp } from "./hosted-app.js";
|
|
4
|
+
/** No link token yet: nothing is read. */
|
|
5
|
+
export const CUSTD_APP_LIVE_IDLE = "idle";
|
|
6
|
+
const IDLE = { status: CUSTD_APP_LIVE_IDLE };
|
|
7
|
+
const LOADING = { status: APP_LIVE_STATUSES.loading };
|
|
8
|
+
const UNAVAILABLE = {
|
|
9
|
+
status: APP_LIVE_STATUSES.error,
|
|
10
|
+
error: new AppItemError(null, APP_ITEM_ERROR_CODES.unavailable),
|
|
11
|
+
retrying: false,
|
|
12
|
+
};
|
|
13
|
+
const noSubscription = () => () => { };
|
|
14
|
+
const noRefresh = () => { };
|
|
15
|
+
/**
|
|
16
|
+
* The item a link opens, kept fresh by conditional polling (paused while the tab is hidden).
|
|
17
|
+
* Every component watching the same item and link shares one poller.
|
|
18
|
+
*/
|
|
19
|
+
export function useAppItem(token, options = {}) {
|
|
20
|
+
return useAppLive(token, options, watchItem);
|
|
21
|
+
}
|
|
22
|
+
/** The item's latest forecast run, kept fresh; its data is null until the first run exists. */
|
|
23
|
+
export function useAppForecast(token, options = {}) {
|
|
24
|
+
return useAppLive(token, options, watchLatestForecast);
|
|
25
|
+
}
|
|
26
|
+
/** The item's measurements and forecast story, kept fresh. */
|
|
27
|
+
export function useAppForecastStory(token, options = {}) {
|
|
28
|
+
return useAppLive(token, options, watchForecastStory);
|
|
29
|
+
}
|
|
30
|
+
/** The model item's latest run, kept fresh; `empty` until the first run exists. */
|
|
31
|
+
export function useAppModelRun(token, options = {}) {
|
|
32
|
+
return useAppLive(token, options, watchLatestModelRun);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* The meeting a meeting item runs, kept fresh through the item's shared poller, so it costs no
|
|
36
|
+
* extra request beside `useAppItem` on the same link. An item of another kind is an `error`
|
|
37
|
+
* with code `app_item_wrong_kind`.
|
|
38
|
+
*/
|
|
39
|
+
export function useAppMeeting(token, options = {}) {
|
|
40
|
+
const item = useAppItem(token, options);
|
|
41
|
+
return useMemo(() => meetingOf(item), [item]);
|
|
42
|
+
}
|
|
43
|
+
const NOT_A_MEETING = new AppItemError(null, APP_ITEM_ERROR_CODES.wrongKind);
|
|
44
|
+
function meetingOf(result) {
|
|
45
|
+
if (!("data" in result) || result.data === undefined)
|
|
46
|
+
return result;
|
|
47
|
+
const meeting = result.data.meeting;
|
|
48
|
+
if (meeting)
|
|
49
|
+
return { ...result, data: meeting };
|
|
50
|
+
return { status: APP_LIVE_STATUSES.error, error: NOT_A_MEETING, retrying: false, refresh: result.refresh };
|
|
51
|
+
}
|
|
52
|
+
function watchLatestModelRun(client, access, options) {
|
|
53
|
+
return client.watchLatestModelRun(access, options);
|
|
54
|
+
}
|
|
55
|
+
function watchItem(client, access, options) {
|
|
56
|
+
return client.watchItem(access, options);
|
|
57
|
+
}
|
|
58
|
+
function watchLatestForecast(client, access, options) {
|
|
59
|
+
return client.watchLatestForecast(access, options);
|
|
60
|
+
}
|
|
61
|
+
function watchForecastStory(client, access, options) {
|
|
62
|
+
return client.watchForecastStory(access, options);
|
|
63
|
+
}
|
|
64
|
+
function useAppLive(token, options, watchOf) {
|
|
65
|
+
const hosted = useOptionalCustdHostedApp();
|
|
66
|
+
const { item, intervalMs, maxBackoffMs } = options;
|
|
67
|
+
let client = options.client;
|
|
68
|
+
let fallback = UNAVAILABLE;
|
|
69
|
+
if (!client && hosted?.status === CUSTD_HOSTED_APP_LOADING)
|
|
70
|
+
fallback = LOADING;
|
|
71
|
+
if (!client && hosted?.status === HOSTED_APP_STATUSES.ready)
|
|
72
|
+
client = hosted.app.appItems;
|
|
73
|
+
// Primitive keys, so an inline `{ item }` does not start a new watch on every render.
|
|
74
|
+
const linkToken = typeof token === "string" ? token : undefined;
|
|
75
|
+
const ownedItem = typeof token === "object" && token ? token.item : undefined;
|
|
76
|
+
if (!linkToken && !ownedItem)
|
|
77
|
+
fallback = IDLE;
|
|
78
|
+
const watch = useMemo(() => {
|
|
79
|
+
const access = linkToken || (ownedItem ? { item: ownedItem } : undefined);
|
|
80
|
+
return client && access ? watchOf(client, access, { item, intervalMs, maxBackoffMs }) : null;
|
|
81
|
+
}, [client, linkToken, ownedItem, item, intervalMs, maxBackoffMs, watchOf]);
|
|
82
|
+
const getState = watch ? watch.getState : () => fallback;
|
|
83
|
+
const state = useSyncExternalStore(watch ? watch.subscribe : noSubscription, getState, getState);
|
|
84
|
+
const refresh = watch ? watch.refresh : noRefresh;
|
|
85
|
+
return useMemo(() => ({ ...state, refresh }), [state, refresh]);
|
|
86
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { CSSProperties } from "react";
|
|
2
|
+
import type { ArrivalHistogramData } from "./forecast-types.js";
|
|
3
|
+
export type ArrivalHistogramLabels = {
|
|
4
|
+
empty: string;
|
|
5
|
+
never: (neverCount: number, total: number) => string;
|
|
6
|
+
bin: (start: string, end: string, count: number) => string;
|
|
7
|
+
};
|
|
8
|
+
export type ArrivalHistogramProps = {
|
|
9
|
+
/** `counter.detail.arrivalHistogram`. */
|
|
10
|
+
histogram: ArrivalHistogramData;
|
|
11
|
+
/** Bins ending on or before the deadline are drawn as on time. */
|
|
12
|
+
deadline?: string;
|
|
13
|
+
title: string;
|
|
14
|
+
summary?: string;
|
|
15
|
+
labels?: Partial<ArrivalHistogramLabels>;
|
|
16
|
+
formatDate?: (epochMs: number) => string;
|
|
17
|
+
width?: number;
|
|
18
|
+
height?: number;
|
|
19
|
+
className?: string;
|
|
20
|
+
style?: CSSProperties;
|
|
21
|
+
};
|
|
22
|
+
export declare function ArrivalHistogram({ histogram, deadline, title, summary, labels: labelOverrides, formatDate, width, height, className, style, }: ArrivalHistogramProps): import("react").JSX.Element;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { DAY_MS, formatUtcDate, parseTime, scaleLinear } from "./chart-scale.js";
|
|
3
|
+
const DEFAULT_LABELS = {
|
|
4
|
+
empty: "No draw reaches the target.",
|
|
5
|
+
never: (neverCount, total) => `${neverCount} of ${total} draws never reach the target.`,
|
|
6
|
+
bin: (start, end, count) => `${start} to ${end}: ${count} draws`,
|
|
7
|
+
};
|
|
8
|
+
const MARGIN = { top: 8, right: 8, bottom: 24, left: 8 };
|
|
9
|
+
const COLOR = {
|
|
10
|
+
before: "var(--custd-chart-forecast, currentColor)",
|
|
11
|
+
after: "var(--custd-chart-late, currentColor)",
|
|
12
|
+
deadline: "var(--custd-chart-deadline, currentColor)",
|
|
13
|
+
};
|
|
14
|
+
export function ArrivalHistogram({ histogram, deadline, title, summary, labels: labelOverrides, formatDate = formatUtcDate, width = 640, height = 160, className, style, }) {
|
|
15
|
+
const labels = { ...DEFAULT_LABELS, ...labelOverrides };
|
|
16
|
+
const { bins, neverCount } = histogram;
|
|
17
|
+
const first = bins[0];
|
|
18
|
+
const last = bins[bins.length - 1];
|
|
19
|
+
const arrived = bins.reduce((sum, bin) => sum + bin.count, 0);
|
|
20
|
+
const total = arrived + neverCount;
|
|
21
|
+
if (!first || !last || arrived === 0) {
|
|
22
|
+
return (_jsxs("div", { className: className, style: style, "data-custd-chart": "arrival-histogram", "data-custd-chart-state": "empty", children: [_jsx("p", { children: labels.empty }), neverCount > 0 ? _jsx("p", { children: labels.never(neverCount, total) }) : null] }));
|
|
23
|
+
}
|
|
24
|
+
const arrivals = { start: parseTime(first.start), end: parseTime(last.end) };
|
|
25
|
+
// Every draw arriving at one instant gives zero-width bins; draw them as one centred bar.
|
|
26
|
+
const instant = arrivals.end <= arrivals.start;
|
|
27
|
+
const drawn = instant ? [{ start: first.start, end: first.start, count: arrived }] : bins;
|
|
28
|
+
const x = instant ? { start: arrivals.start - DAY_MS / 2, end: arrivals.start + DAY_MS / 2 } : arrivals;
|
|
29
|
+
const px = scaleLinear(x, MARGIN.left, width - MARGIN.right);
|
|
30
|
+
const py = scaleLinear({ start: 0, end: Math.max(...drawn.map((bin) => bin.count)) }, height - MARGIN.bottom, MARGIN.top);
|
|
31
|
+
const deadlineMs = deadline ? parseTime(deadline) : undefined;
|
|
32
|
+
const text = { fill: "currentColor", fontSize: 11, fontVariantNumeric: "tabular-nums" };
|
|
33
|
+
const range = `${formatDate(arrivals.start)} and ${formatDate(arrivals.end)}`;
|
|
34
|
+
return (_jsxs("div", { className: className, style: style, "data-custd-chart": "arrival-histogram", children: [_jsxs("svg", { role: "img", "aria-label": summary ?? `${title}: ${total} draws, ${arrived} arrive between ${range}`, viewBox: `0 0 ${width} ${height}`, width: "100%", style: { display: "block" }, children: [_jsx("title", { children: title }), drawn.map((bin) => {
|
|
35
|
+
const late = deadlineMs !== undefined && parseTime(bin.end) > deadlineMs;
|
|
36
|
+
const left = px(parseTime(bin.start));
|
|
37
|
+
return (_jsx("rect", { "data-custd-chart-bar": late ? "after" : "before", x: instant ? left - 2 : left + 0.5, y: py(bin.count), width: instant ? 4 : Math.max(0, px(parseTime(bin.end)) - left - 1), height: height - MARGIN.bottom - py(bin.count), style: { fill: late ? COLOR.after : COLOR.before, fillOpacity: late ? 0.45 : 0.8 }, children: _jsx("title", { children: labels.bin(formatDate(parseTime(bin.start)), formatDate(parseTime(bin.end)), bin.count) }) }, bin.start));
|
|
38
|
+
}), deadlineMs !== undefined && deadlineMs >= x.start && deadlineMs <= x.end ? (_jsx("line", { "data-custd-chart-layer": "deadline", x1: px(deadlineMs), x2: px(deadlineMs), y1: MARGIN.top, y2: height - MARGIN.bottom, style: { stroke: COLOR.deadline, strokeWidth: 1.5 } })) : null, _jsx("text", { x: MARGIN.left, y: height - 6, style: text, children: formatDate(x.start) }), _jsx("text", { x: width - MARGIN.right, y: height - 6, textAnchor: "end", style: text, children: formatDate(x.end) })] }), neverCount > 0 ? _jsx("p", { children: labels.never(neverCount, total) }) : null] }));
|
|
39
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** A closed numeric range; time domains are milliseconds since the epoch. */
|
|
2
|
+
export type ChartDomain = {
|
|
3
|
+
start: number;
|
|
4
|
+
end: number;
|
|
5
|
+
};
|
|
6
|
+
export declare const DAY_MS = 86400000;
|
|
7
|
+
export declare function parseTime(value: string): number;
|
|
8
|
+
export declare function scaleLinear(domain: ChartDomain, rangeStart: number, rangeEnd: number): (value: number) => number;
|
|
9
|
+
/** The extent of the finite values, padded to at least `minSpan` so a single value stays visible. */
|
|
10
|
+
export declare function domainOf(values: readonly number[], minSpan: number): ChartDomain | undefined;
|
|
11
|
+
/** Scales the span around its centre by `factor` (below 1 zooms in), kept inside `bounds`. */
|
|
12
|
+
export declare function zoomDomain(view: ChartDomain, factor: number, bounds: ChartDomain, minSpan: number): ChartDomain;
|
|
13
|
+
/** Moves the view by `fraction` of its span (negative is earlier), kept inside `bounds`. */
|
|
14
|
+
export declare function panDomain(view: ChartDomain, fraction: number, bounds: ChartDomain): ChartDomain;
|
|
15
|
+
export declare function sameDomain(left: ChartDomain, right: ChartDomain): boolean;
|
|
16
|
+
export declare function ticksOf(domain: ChartDomain, count: number): number[];
|
|
17
|
+
export declare function formatUtcDate(value: number): string;
|
|
18
|
+
export declare function formatNumber(value: number): string;
|
|
19
|
+
export declare function usePrefersReducedMotion(): boolean;
|
|
20
|
+
/** Eases the drawn domain towards `target`; jumps straight there when motion is reduced. */
|
|
21
|
+
export declare function useTweenedDomain(target: ChartDomain, reducedMotion: boolean): ChartDomain;
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { useEffect, useRef, useState } from "react";
|
|
2
|
+
export const DAY_MS = 86400000;
|
|
3
|
+
export function parseTime(value) {
|
|
4
|
+
return Date.parse(value);
|
|
5
|
+
}
|
|
6
|
+
export function scaleLinear(domain, rangeStart, rangeEnd) {
|
|
7
|
+
const span = domain.end - domain.start || 1;
|
|
8
|
+
return (value) => rangeStart + ((value - domain.start) / span) * (rangeEnd - rangeStart);
|
|
9
|
+
}
|
|
10
|
+
/** The extent of the finite values, padded to at least `minSpan` so a single value stays visible. */
|
|
11
|
+
export function domainOf(values, minSpan) {
|
|
12
|
+
const finite = values.filter(Number.isFinite);
|
|
13
|
+
if (finite.length === 0)
|
|
14
|
+
return undefined;
|
|
15
|
+
const start = Math.min(...finite);
|
|
16
|
+
const end = Math.max(...finite);
|
|
17
|
+
if (end - start >= minSpan)
|
|
18
|
+
return { start, end };
|
|
19
|
+
const centre = (start + end) / 2;
|
|
20
|
+
return { start: centre - minSpan / 2, end: centre + minSpan / 2 };
|
|
21
|
+
}
|
|
22
|
+
/** Scales the span around its centre by `factor` (below 1 zooms in), kept inside `bounds`. */
|
|
23
|
+
export function zoomDomain(view, factor, bounds, minSpan) {
|
|
24
|
+
const maxSpan = bounds.end - bounds.start;
|
|
25
|
+
const span = Math.min(maxSpan, Math.max(Math.min(minSpan, maxSpan), (view.end - view.start) * factor));
|
|
26
|
+
const centre = (view.start + view.end) / 2;
|
|
27
|
+
return clampDomain({ start: centre - span / 2, end: centre + span / 2 }, bounds);
|
|
28
|
+
}
|
|
29
|
+
/** Moves the view by `fraction` of its span (negative is earlier), kept inside `bounds`. */
|
|
30
|
+
export function panDomain(view, fraction, bounds) {
|
|
31
|
+
const shift = (view.end - view.start) * fraction;
|
|
32
|
+
return clampDomain({ start: view.start + shift, end: view.end + shift }, bounds);
|
|
33
|
+
}
|
|
34
|
+
function clampDomain(view, bounds) {
|
|
35
|
+
if (view.start < bounds.start)
|
|
36
|
+
return { start: bounds.start, end: bounds.start + (view.end - view.start) };
|
|
37
|
+
if (view.end > bounds.end)
|
|
38
|
+
return { start: bounds.end - (view.end - view.start), end: bounds.end };
|
|
39
|
+
return view;
|
|
40
|
+
}
|
|
41
|
+
export function sameDomain(left, right) {
|
|
42
|
+
return left.start === right.start && left.end === right.end;
|
|
43
|
+
}
|
|
44
|
+
export function ticksOf(domain, count) {
|
|
45
|
+
const step = (domain.end - domain.start) / Math.max(1, count - 1);
|
|
46
|
+
return Array.from({ length: count }, (_, index) => domain.start + step * index);
|
|
47
|
+
}
|
|
48
|
+
export function formatUtcDate(value) {
|
|
49
|
+
return new Date(value).toISOString().slice(0, 10);
|
|
50
|
+
}
|
|
51
|
+
export function formatNumber(value) {
|
|
52
|
+
return value.toLocaleString("en-US", { maximumFractionDigits: 2 });
|
|
53
|
+
}
|
|
54
|
+
export function usePrefersReducedMotion() {
|
|
55
|
+
const [reduced, setReduced] = useState(false);
|
|
56
|
+
useEffect(() => {
|
|
57
|
+
if (typeof window === "undefined" || typeof window.matchMedia !== "function")
|
|
58
|
+
return;
|
|
59
|
+
const media = window.matchMedia("(prefers-reduced-motion: reduce)");
|
|
60
|
+
const update = () => setReduced(media.matches);
|
|
61
|
+
update();
|
|
62
|
+
media.addEventListener("change", update);
|
|
63
|
+
return () => media.removeEventListener("change", update);
|
|
64
|
+
}, []);
|
|
65
|
+
return reduced;
|
|
66
|
+
}
|
|
67
|
+
const TWEEN_MS = 180;
|
|
68
|
+
/** Eases the drawn domain towards `target`; jumps straight there when motion is reduced. */
|
|
69
|
+
export function useTweenedDomain(target, reducedMotion) {
|
|
70
|
+
const [shown, setShown] = useState(target);
|
|
71
|
+
const shownRef = useRef(target);
|
|
72
|
+
shownRef.current = shown;
|
|
73
|
+
const { start, end } = target;
|
|
74
|
+
useEffect(() => {
|
|
75
|
+
const goal = { start, end };
|
|
76
|
+
if (reducedMotion || typeof requestAnimationFrame !== "function") {
|
|
77
|
+
setShown(goal);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const from = shownRef.current;
|
|
81
|
+
const began = performance.now();
|
|
82
|
+
let frame = requestAnimationFrame(function step(now) {
|
|
83
|
+
const progress = Math.min(1, (now - began) / TWEEN_MS);
|
|
84
|
+
setShown({
|
|
85
|
+
start: from.start + (goal.start - from.start) * progress,
|
|
86
|
+
end: from.end + (goal.end - from.end) * progress,
|
|
87
|
+
});
|
|
88
|
+
if (progress < 1)
|
|
89
|
+
frame = requestAnimationFrame(step);
|
|
90
|
+
});
|
|
91
|
+
return () => cancelAnimationFrame(frame);
|
|
92
|
+
}, [start, end, reducedMotion]);
|
|
93
|
+
return shown;
|
|
94
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { CSSProperties } from "react";
|
|
2
|
+
import type { ConvergenceEstimate } from "./forecast-types.js";
|
|
3
|
+
export type ConvergenceStoryLabels = {
|
|
4
|
+
empty: string;
|
|
5
|
+
firstEstimate: string;
|
|
6
|
+
latest: (low: string, high: string) => string;
|
|
7
|
+
/** `movementDays` is positive when the estimate moved later; `widthChangeDays` is negative when it narrowed. */
|
|
8
|
+
change: (movementDays: number, widthChangeDays: number) => string;
|
|
9
|
+
stale: (ageDays: number) => string;
|
|
10
|
+
};
|
|
11
|
+
export type ConvergenceStoryProps = {
|
|
12
|
+
/** Dated estimates, oldest first (`delivery.estimates`). */
|
|
13
|
+
estimates: readonly ConvergenceEstimate[];
|
|
14
|
+
/** The delivery target date (`delivery.targetDate`). */
|
|
15
|
+
targetDate?: string;
|
|
16
|
+
title: string;
|
|
17
|
+
summary?: string;
|
|
18
|
+
/** Marks the latest estimate stale once it is older than this many days. */
|
|
19
|
+
staleAfterDays?: number;
|
|
20
|
+
/** The time staleness is measured against; defaults to now. */
|
|
21
|
+
now?: string;
|
|
22
|
+
labels?: Partial<ConvergenceStoryLabels>;
|
|
23
|
+
formatDate?: (epochMs: number) => string;
|
|
24
|
+
width?: number;
|
|
25
|
+
height?: number;
|
|
26
|
+
className?: string;
|
|
27
|
+
style?: CSSProperties;
|
|
28
|
+
};
|
|
29
|
+
export declare function ConvergenceStory({ estimates, targetDate, title, summary, staleAfterDays, now, labels: labelOverrides, formatDate, width, height, className, style, }: ConvergenceStoryProps): import("react").JSX.Element;
|