@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.
Files changed (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +269 -2
  3. package/dist/account-menu-item.d.ts +13 -0
  4. package/dist/account-menu-item.js +20 -0
  5. package/dist/app-items.d.ts +33 -0
  6. package/dist/app-items.js +86 -0
  7. package/dist/arrival-histogram.d.ts +22 -0
  8. package/dist/arrival-histogram.js +39 -0
  9. package/dist/chart-scale.d.ts +21 -0
  10. package/dist/chart-scale.js +94 -0
  11. package/dist/convergence-story.d.ts +29 -0
  12. package/dist/convergence-story.js +65 -0
  13. package/dist/forecast-chart.d.ts +30 -0
  14. package/dist/forecast-chart.js +175 -0
  15. package/dist/forecast-types.d.ts +69 -0
  16. package/dist/forecast-types.js +6 -0
  17. package/dist/hosted-app.d.ts +28 -0
  18. package/dist/hosted-app.js +48 -0
  19. package/dist/index.d.ts +43 -0
  20. package/dist/index.js +67 -0
  21. package/dist/measure-next-panel.d.ts +24 -0
  22. package/dist/measure-next-panel.js +23 -0
  23. package/dist/model-calculator.d.ts +54 -0
  24. package/dist/model-calculator.js +89 -0
  25. package/dist/model-csv.d.ts +9 -0
  26. package/dist/model-csv.js +17 -0
  27. package/dist/model-editor.d.ts +37 -0
  28. package/dist/model-editor.js +181 -0
  29. package/dist/model-shorthand.d.ts +28 -0
  30. package/dist/model-shorthand.js +85 -0
  31. package/dist/quantity-histogram.d.ts +23 -0
  32. package/dist/quantity-histogram.js +53 -0
  33. package/dist/safe-markdown.d.ts +10 -0
  34. package/dist/safe-markdown.js +74 -0
  35. package/dist/sensitivity-view.d.ts +21 -0
  36. package/dist/sensitivity-view.js +60 -0
  37. package/dist/session.d.ts +18 -0
  38. package/dist/session.js +43 -0
  39. package/dist/testing.d.ts +11 -0
  40. package/dist/testing.js +9 -0
  41. package/package.json +54 -4
@@ -0,0 +1,74 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ /** Link targets a description may open; anything else is shown as plain text. */
3
+ const SAFE_HREF = /^(?:https?:\/\/|mailto:)/i;
4
+ // Emphasis needs text hard against its asterisks, so `a * b * c` in a formula stays as written;
5
+ // underscores are left alone because quantity names use them.
6
+ const INLINE = /(`[^`]+`)|(\*\*[^\s*](?:[^*]*[^\s*])?\*\*)|(\*[^\s*](?:[^*]*[^\s*])?\*)|(\[[^\]]+\]\([^)\s]+\))/g;
7
+ const LIST_ITEM = /^\s*[-*]\s+/;
8
+ /**
9
+ * A small Markdown subset (paragraphs, `-` lists, `code`, **bold**, *italic* and http, https or
10
+ * mailto links) built as React elements. Text is never parsed as HTML, so markup in a
11
+ * description is shown as written.
12
+ */
13
+ export function SafeMarkdown({ source, className }) {
14
+ return (_jsx("div", { className: className, "data-custd-markdown": "", children: blocksOf(source.replace(/\r\n?/g, "\n")).map((block) => block.items ? (_jsx("ul", { children: block.items.map((item) => (_jsx("li", { children: inline(item.text) }, item.at))) }, block.at)) : (_jsx("p", { children: inline(block.text) }, block.at))) }));
15
+ }
16
+ /** Splits on blank lines; a block whose every line starts with `-` or `*` is a list. Keys are offsets. */
17
+ function blocksOf(source) {
18
+ const blocks = [];
19
+ let lines = [];
20
+ let at = 0;
21
+ const flush = () => {
22
+ const first = lines[0];
23
+ if (first) {
24
+ const list = lines.every((line) => LIST_ITEM.test(line.text));
25
+ blocks.push({
26
+ at: first.at,
27
+ text: lines.map((line) => line.text).join(" "),
28
+ items: list ? lines.map((line) => ({ at: line.at, text: line.text.replace(LIST_ITEM, "") })) : undefined,
29
+ });
30
+ }
31
+ lines = [];
32
+ };
33
+ for (const text of source.split("\n")) {
34
+ if (text.trim() === "")
35
+ flush();
36
+ else
37
+ lines.push({ at, text });
38
+ at += text.length + 1;
39
+ }
40
+ flush();
41
+ return blocks;
42
+ }
43
+ function inline(text) {
44
+ const nodes = [];
45
+ let at = 0;
46
+ for (const match of text.matchAll(INLINE)) {
47
+ const index = match.index ?? 0;
48
+ if (index > at)
49
+ nodes.push(text.slice(at, index));
50
+ nodes.push(inlineNode(match, index));
51
+ at = index + match[0].length;
52
+ }
53
+ if (at < text.length)
54
+ nodes.push(text.slice(at));
55
+ return nodes;
56
+ }
57
+ function inlineNode(match, key) {
58
+ const [whole, code, bold, italic, link] = match;
59
+ if (code)
60
+ return _jsx("code", { children: code.slice(1, -1) }, key);
61
+ if (bold)
62
+ return _jsx("strong", { children: bold.slice(2, -2) }, key);
63
+ if (italic)
64
+ return _jsx("em", { children: italic.slice(1, -1) }, key);
65
+ if (link) {
66
+ const split = link.indexOf("](");
67
+ const label = link.slice(1, split);
68
+ const href = link.slice(split + 2, -1);
69
+ if (!SAFE_HREF.test(href))
70
+ return label;
71
+ return (_jsx("a", { href: href, rel: "noopener noreferrer nofollow", target: "_blank", children: label }, key));
72
+ }
73
+ return whole;
74
+ }
@@ -0,0 +1,21 @@
1
+ import type { AppModelInputSensitivity, AppModelSensitivity } from "@haakco/custd-sdk/browser";
2
+ import type { CSSProperties } from "react";
3
+ export type SensitivityViewLabels = {
4
+ empty: string;
5
+ heading: (output: string) => string;
6
+ correlation: (value: string) => string;
7
+ direction: (positive: boolean) => string;
8
+ scatter: (input: string, output: string) => string;
9
+ };
10
+ export type SensitivityViewProps = {
11
+ sensitivity: AppModelSensitivity | undefined;
12
+ /** How many of the strongest inputs get a scatter plot. Default 3. */
13
+ scatterInputs?: number;
14
+ labels?: Partial<SensitivityViewLabels>;
15
+ className?: string;
16
+ style?: CSSProperties;
17
+ };
18
+ /** Orders inputs by the strength of their rank correlation with the output, strongest first. */
19
+ export declare function rankSensitivityInputs(inputs: readonly AppModelInputSensitivity[]): AppModelInputSensitivity[];
20
+ /** The inputs that move one output most, as signed bars, with small scatter plots for the top few. */
21
+ export declare function SensitivityView({ sensitivity, scatterInputs, labels: overrides, className, style, }: SensitivityViewProps): import("react").JSX.Element;
@@ -0,0 +1,60 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { domainOf, scaleLinear } from "./chart-scale.js";
3
+ import { formatModelNumber } from "./model-shorthand.js";
4
+ const DEFAULT_LABELS = {
5
+ empty: "Choose an output to see which inputs drive it.",
6
+ heading: (output) => `What drives ${output}`,
7
+ correlation: (value) => `rank correlation ${value}`,
8
+ direction: (positive) => (positive ? "raises it" : "lowers it"),
9
+ scatter: (input, output) => `${input} against ${output}, one dot per sampled trial`,
10
+ };
11
+ /** The server keeps up to 500 scatter points per input; draw no more than that. */
12
+ const MAX_SCATTER_POINTS = 500;
13
+ const BAR = { width: 160, height: 12 };
14
+ const SCATTER = { width: 160, height: 120, margin: 6 };
15
+ const COLOR = {
16
+ raises: "var(--custd-chart-forecast, currentColor)",
17
+ lowers: "var(--custd-chart-late, currentColor)",
18
+ axis: "var(--custd-chart-grid, currentColor)",
19
+ dot: "var(--custd-chart-observed, currentColor)",
20
+ };
21
+ /** Orders inputs by the strength of their rank correlation with the output, strongest first. */
22
+ export function rankSensitivityInputs(inputs) {
23
+ return [...inputs].sort((left, right) => Math.abs(right.rankCorrelation) - Math.abs(left.rankCorrelation));
24
+ }
25
+ /** The inputs that move one output most, as signed bars, with small scatter plots for the top few. */
26
+ export function SensitivityView({ sensitivity, scatterInputs = 3, labels: overrides, className, style, }) {
27
+ const labels = { ...DEFAULT_LABELS, ...overrides };
28
+ const ranked = rankSensitivityInputs(sensitivity?.inputs ?? []);
29
+ if (!sensitivity || ranked.length === 0) {
30
+ return (_jsx("div", { className: className, style: style, "data-custd-chart": "sensitivity", "data-custd-chart-state": "empty", children: _jsx("p", { children: labels.empty }) }));
31
+ }
32
+ const scattered = ranked.filter((input) => (input.scatter?.length ?? 0) > 0).slice(0, scatterInputs);
33
+ return (_jsxs("section", { className: className, style: style, "data-custd-chart": "sensitivity", children: [_jsx("h3", { children: labels.heading(sensitivity.output) }), _jsx("ol", { style: { listStyle: "none", padding: 0, margin: 0, display: "grid", gap: "0.25rem" }, children: ranked.map((input) => (_jsx(SensitivityRow, { input: input, labels: labels }, input.name))) }), scattered.length > 0 ? (_jsx("div", { style: { display: "flex", flexWrap: "wrap", gap: "0.75rem", marginTop: "0.75rem" }, children: scattered.map((input) => (_jsx(ScatterPlot, { points: input.scatter ?? [], label: labels.scatter(input.name, sensitivity.output), name: input.name }, input.name))) })) : null] }));
34
+ }
35
+ function SensitivityRow({ input, labels }) {
36
+ const positive = input.rankCorrelation >= 0;
37
+ const centre = BAR.width / 2;
38
+ const length = Math.min(1, Math.abs(input.rankCorrelation)) * centre;
39
+ return (_jsxs("li", { "data-custd-sensitivity-input": input.name, style: { display: "flex", flexWrap: "wrap", alignItems: "center", gap: "0.5rem" }, children: [_jsx("span", { style: { minWidth: "8rem", fontWeight: 600 }, children: input.name }), _jsxs("svg", { viewBox: `0 0 ${BAR.width} ${BAR.height}`, width: BAR.width, height: BAR.height, "aria-hidden": "true", children: [_jsx("line", { x1: centre, x2: centre, y1: 0, y2: BAR.height, style: { stroke: COLOR.axis, strokeWidth: 1 } }), _jsx("rect", { x: positive ? centre : centre - length, y: 2, width: length, height: BAR.height - 4, style: { fill: positive ? COLOR.raises : COLOR.lowers } })] }), _jsxs("span", { style: { fontVariantNumeric: "tabular-nums" }, children: [labels.correlation(formatSigned(input.rankCorrelation)), ", ", labels.direction(positive)] })] }));
40
+ }
41
+ function ScatterPlot({ points, label, name }) {
42
+ const drawn = points.slice(0, MAX_SCATTER_POINTS);
43
+ const x = domainOf(drawn.map((point) => point.input), 1e-9);
44
+ const y = domainOf(drawn.map((point) => point.output), 1e-9);
45
+ if (!x || !y)
46
+ return null;
47
+ const { width, height, margin } = SCATTER;
48
+ const px = scaleLinear(x, margin, width - margin);
49
+ const py = scaleLinear(y, height - margin, margin);
50
+ return (_jsxs("figure", { style: { margin: 0 }, "data-custd-chart": "sensitivity-scatter", "data-custd-sensitivity-input": name, children: [_jsxs("svg", { role: "img", "aria-label": label, viewBox: `0 0 ${width} ${height}`, width: width, height: height, children: [_jsx("rect", { x: 0.5, y: 0.5, width: width - 1, height: height - 1, style: { fill: "none", stroke: COLOR.axis, strokeOpacity: 0.5 } }), _jsx("path", { "data-custd-chart-layer": "scatter", d: drawn.map((point) => dot(px(point.input), py(point.output))).join(""), style: { fill: COLOR.dot, fillOpacity: 0.45 } })] }), _jsx("figcaption", { children: name })] }));
51
+ }
52
+ const DOT_RADIUS = 1.75;
53
+ /** One dot as a path segment, so a plot of hundreds of trials is one element. */
54
+ function dot(cx, cy) {
55
+ const r = DOT_RADIUS;
56
+ return `M${cx - r},${cy}a${r},${r} 0 1,0 ${2 * r},0a${r},${r} 0 1,0 ${-2 * r},0`;
57
+ }
58
+ function formatSigned(value) {
59
+ return `${value > 0 ? "+" : ""}${formatModelNumber(Math.round(value * 100) / 100)}`;
60
+ }
@@ -0,0 +1,18 @@
1
+ import { type BrowserSignIn, type SignInError, type SignInSession, type SignInStartOptions, type SignInStatus, type SignOutOptions, type SignOutResult } from "@haakco/custd-sdk";
2
+ import { type ReactNode } from "react";
3
+ export type CustdSession = {
4
+ status: SignInStatus;
5
+ session: SignInSession | null;
6
+ error: SignInError | null;
7
+ signIn: (options?: SignInStartOptions) => Promise<void>;
8
+ signOut: (options?: SignOutOptions) => SignOutResult;
9
+ };
10
+ export type CustdSessionProviderProps = {
11
+ client: BrowserSignIn;
12
+ children?: ReactNode;
13
+ /** Called after a sign-in redirect completes. Defaults to replacing the URL with `returnTo`. */
14
+ onSignInComplete?: (returnTo: string) => void;
15
+ };
16
+ /** Restores the session on mount (completing a sign-in redirect) and shares the client. */
17
+ export declare function CustdSessionProvider({ client, children, onSignInComplete }: CustdSessionProviderProps): import("react").JSX.Element;
18
+ export declare function useCustdSession(): CustdSession;
@@ -0,0 +1,43 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { SIGN_IN_STATUSES, } from "@haakco/custd-sdk";
3
+ import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useSyncExternalStore, } from "react";
4
+ const SessionContext = createContext(null);
5
+ /** Restores the session on mount (completing a sign-in redirect) and shares the client. */
6
+ export function CustdSessionProvider({ client, children, onSignInComplete }) {
7
+ const onComplete = useRef(onSignInComplete);
8
+ onComplete.current = onSignInComplete;
9
+ useEffect(() => {
10
+ let active = true;
11
+ void client.restore().then((result) => {
12
+ if (!active || result.returnTo === undefined)
13
+ return;
14
+ (onComplete.current ?? replaceUrl)(result.returnTo);
15
+ });
16
+ return () => {
17
+ active = false;
18
+ };
19
+ }, [client]);
20
+ return _jsx(SessionContext.Provider, { value: client, children: children });
21
+ }
22
+ export function useCustdSession() {
23
+ const client = useContext(SessionContext);
24
+ if (!client)
25
+ throw new Error("custd: useCustdSession must be used inside CustdSessionProvider");
26
+ const subscribe = useCallback((listener) => client.subscribe(listener), [client]);
27
+ const getState = useCallback(() => client.getState(), [client]);
28
+ const state = useSyncExternalStore(subscribe, getState, getState);
29
+ return useMemo(() => toSession(client, state), [client, state]);
30
+ }
31
+ function toSession(client, state) {
32
+ return {
33
+ status: state.status,
34
+ session: state.status === SIGN_IN_STATUSES.signedIn ? state.session : null,
35
+ error: state.status === SIGN_IN_STATUSES.error ? state.error : null,
36
+ // A failed start is already published as the error state.
37
+ signIn: (options) => client.signIn(options).catch(() => undefined),
38
+ signOut: (options) => client.signOut(options),
39
+ };
40
+ }
41
+ function replaceUrl(returnTo) {
42
+ window.history.replaceState(null, "", returnTo);
43
+ }
@@ -0,0 +1,11 @@
1
+ import type { FakeCustd } from "@haakco/custd-sdk/testing";
2
+ import { type CustdHostedAppProviderProps } from "./hosted-app.js";
3
+ export type CustdFakeHostedAppProviderProps = Omit<CustdHostedAppProviderProps, "options"> & {
4
+ /** The fake every hook under this provider reaches, with its own in-memory sign-in storage. */
5
+ fake: FakeCustd;
6
+ };
7
+ /**
8
+ * `CustdHostedAppProvider` started against a `FakeCustd`, so `useCustdHostedApp`, `useCustdSession`
9
+ * and the app item hooks run in tests with no network. Sign a user in with `signInWithFake`.
10
+ */
11
+ export declare function CustdFakeHostedAppProvider({ fake, ...props }: CustdFakeHostedAppProviderProps): import("react").JSX.Element;
@@ -0,0 +1,9 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { CustdHostedAppProvider } from "./hosted-app.js";
3
+ /**
4
+ * `CustdHostedAppProvider` started against a `FakeCustd`, so `useCustdHostedApp`, `useCustdSession`
5
+ * and the app item hooks run in tests with no network. Sign a user in with `signInWithFake`.
6
+ */
7
+ export function CustdFakeHostedAppProvider({ fake, ...props }) {
8
+ return _jsx(CustdHostedAppProvider, { ...props, options: fake.hostedAppOptions() });
9
+ }
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@haakco/custd-react",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "3.71.2",
4
+ "type": "module",
5
+ "engines": {
6
+ "node": ">=24 <27"
7
+ },
8
+ "main": "dist/index.js",
9
+ "module": "dist/index.js",
10
+ "types": "dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js"
15
+ },
16
+ "./testing": {
17
+ "types": "./dist/testing.d.ts",
18
+ "import": "./dist/testing.js"
19
+ }
20
+ },
21
+ "files": [
22
+ "dist"
23
+ ],
24
+ "scripts": {
25
+ "build": "tsc -p tsconfig.build.json",
26
+ "typecheck": "tsc -p tsconfig.json --noEmit",
27
+ "lint": "biome check src",
28
+ "lint:fix": "biome check --write src",
29
+ "test": "vitest run src"
30
+ },
31
+ "peerDependencies": {
32
+ "@haakco/custd-sdk": ">=3.64.8 <4",
33
+ "@tanstack/react-query": ">=5 <6",
34
+ "react": ">=18 <20"
35
+ },
36
+ "devDependencies": {
37
+ "@biomejs/biome": "^2.6.8",
38
+ "@haakco/custd-sdk": "workspace:*",
39
+ "@tanstack/react-query": "^5.107.2",
40
+ "@testing-library/dom": "^10.4.2",
41
+ "@testing-library/react": "^16.3.3",
42
+ "@types/react": "^19.3.0",
43
+ "@types/react-dom": "^19.3.0",
44
+ "jsdom": "^31.0.1",
45
+ "react": "^19.3.1",
46
+ "react-dom": "^19.3.1",
47
+ "typescript": "^7.0.2",
48
+ "vitest": "^5.1.0"
49
+ },
50
+ "license": "MIT",
51
+ "repository": {
52
+ "type": "git",
53
+ "url": "git+https://github.com/haakco/custd-sdk.git",
54
+ "directory": "sdk-react"
55
+ }
56
+ }