@haakco/custd-react 0.0.0-stage → 3.71.1

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 (40) hide show
  1. package/README.md +269 -2
  2. package/dist/account-menu-item.d.ts +13 -0
  3. package/dist/account-menu-item.js +20 -0
  4. package/dist/app-items.d.ts +33 -0
  5. package/dist/app-items.js +86 -0
  6. package/dist/arrival-histogram.d.ts +22 -0
  7. package/dist/arrival-histogram.js +39 -0
  8. package/dist/chart-scale.d.ts +21 -0
  9. package/dist/chart-scale.js +94 -0
  10. package/dist/convergence-story.d.ts +29 -0
  11. package/dist/convergence-story.js +65 -0
  12. package/dist/forecast-chart.d.ts +30 -0
  13. package/dist/forecast-chart.js +175 -0
  14. package/dist/forecast-types.d.ts +69 -0
  15. package/dist/forecast-types.js +6 -0
  16. package/dist/hosted-app.d.ts +28 -0
  17. package/dist/hosted-app.js +48 -0
  18. package/dist/index.d.ts +43 -0
  19. package/dist/index.js +67 -0
  20. package/dist/measure-next-panel.d.ts +24 -0
  21. package/dist/measure-next-panel.js +23 -0
  22. package/dist/model-calculator.d.ts +54 -0
  23. package/dist/model-calculator.js +89 -0
  24. package/dist/model-csv.d.ts +9 -0
  25. package/dist/model-csv.js +17 -0
  26. package/dist/model-editor.d.ts +37 -0
  27. package/dist/model-editor.js +181 -0
  28. package/dist/model-shorthand.d.ts +28 -0
  29. package/dist/model-shorthand.js +85 -0
  30. package/dist/quantity-histogram.d.ts +23 -0
  31. package/dist/quantity-histogram.js +53 -0
  32. package/dist/safe-markdown.d.ts +10 -0
  33. package/dist/safe-markdown.js +74 -0
  34. package/dist/sensitivity-view.d.ts +21 -0
  35. package/dist/sensitivity-view.js +60 -0
  36. package/dist/session.d.ts +18 -0
  37. package/dist/session.js +43 -0
  38. package/dist/testing.d.ts +11 -0
  39. package/dist/testing.js +9 -0
  40. package/package.json +54 -4
@@ -0,0 +1,65 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { DAY_MS, domainOf, formatUtcDate, parseTime, scaleLinear } from "./chart-scale.js";
3
+ const DEFAULT_LABELS = {
4
+ empty: "No estimates yet.",
5
+ firstEstimate: "This is the first estimate.",
6
+ latest: (low, high) => `Latest estimate: ${low} to ${high}`,
7
+ change: (movementDays, widthChangeDays) => `${movementText(movementDays)}; ${widthText(widthChangeDays)}.`,
8
+ stale: (ageDays) => `Last estimate is ${ageDays} days old.`,
9
+ };
10
+ const MARGIN = { top: 12, right: 12, bottom: 28, left: 80 };
11
+ const COLOR = {
12
+ band: "var(--custd-chart-band, currentColor)",
13
+ forecast: "var(--custd-chart-forecast, currentColor)",
14
+ target: "var(--custd-chart-target, currentColor)",
15
+ stale: "var(--custd-chart-stale, currentColor)",
16
+ };
17
+ export function ConvergenceStory({ estimates, targetDate, title, summary, staleAfterDays, now, labels: labelOverrides, formatDate = formatUtcDate, width = 640, height = 220, className, style, }) {
18
+ const labels = { ...DEFAULT_LABELS, ...labelOverrides };
19
+ const latest = estimates[estimates.length - 1];
20
+ if (!latest) {
21
+ return (_jsx("div", { className: className, style: style, "data-custd-chart": "convergence", "data-custd-chart-state": "empty", children: _jsx("p", { children: labels.empty }) }));
22
+ }
23
+ const previous = estimates[estimates.length - 2];
24
+ const nowMs = now ? parseTime(now) : Date.now();
25
+ const ageDays = Math.floor((nowMs - parseTime(latest.estimatedAt)) / DAY_MS);
26
+ const stale = staleAfterDays !== undefined && ageDays > staleAfterDays;
27
+ const latestText = labels.latest(formatDate(parseTime(latest.low)), formatDate(parseTime(latest.high)));
28
+ return (_jsxs("div", { className: className, style: style, "data-custd-chart": "convergence", "data-custd-chart-stale": stale, children: [_jsx(ConvergencePlot, { estimates: estimates, targetDate: targetDate, staleAt: stale ? nowMs : undefined, title: title, summary: summary ?? `${title}: ${estimates.length} estimates. ${latestText}`, formatDate: formatDate, width: width, height: height }), _jsx("p", { children: latestText }), _jsx("p", { children: previous
29
+ ? labels.change(latest.movementDays ?? midpointShiftDays(previous, latest), latest.widthDays - previous.widthDays)
30
+ : labels.firstEstimate }), stale ? _jsx("p", { "data-custd-chart-stale-note": "", children: labels.stale(ageDays) }) : null] }));
31
+ }
32
+ function ConvergencePlot({ estimates, targetDate, staleAt, title, summary, formatDate, width, height }) {
33
+ const estimatedTimes = estimates.map((estimate) => parseTime(estimate.estimatedAt));
34
+ const x = domainOf(staleAt === undefined ? estimatedTimes : [...estimatedTimes, staleAt], DAY_MS);
35
+ const completionTimes = estimates.flatMap((estimate) => [parseTime(estimate.low), parseTime(estimate.high)]);
36
+ const y = domainOf(targetDate ? [...completionTimes, parseTime(targetDate)] : completionTimes, DAY_MS);
37
+ if (!x || !y)
38
+ return null;
39
+ const px = scaleLinear(x, MARGIN.left, width - MARGIN.right);
40
+ const py = scaleLinear(y, height - MARGIN.bottom, MARGIN.top);
41
+ const at = (estimate, value) => `${px(parseTime(estimate.estimatedAt))},${py(parseTime(value))}`;
42
+ const band = [
43
+ ...estimates.map((estimate) => at(estimate, estimate.high)),
44
+ ...[...estimates].reverse().map((estimate) => at(estimate, estimate.low)),
45
+ ];
46
+ const midpoints = estimates.map((estimate) => `${px(parseTime(estimate.estimatedAt))},${py((parseTime(estimate.low) + parseTime(estimate.high)) / 2)}`);
47
+ const text = { fill: "currentColor", fontSize: 11, fontVariantNumeric: "tabular-nums" };
48
+ return (_jsxs("svg", { role: "img", "aria-label": summary, viewBox: `0 0 ${width} ${height}`, width: "100%", style: { display: "block" }, children: [_jsx("title", { children: title }), _jsx("polygon", { "data-custd-chart-layer": "band", points: band.join(" "), style: { fill: COLOR.band, fillOpacity: 0.18 } }), _jsx("polyline", { "data-custd-chart-layer": "midpoint", points: midpoints.join(" "), style: { fill: "none", stroke: COLOR.forecast, strokeWidth: 2 } }), targetDate ? (_jsx("line", { "data-custd-chart-layer": "target", x1: MARGIN.left, x2: width - MARGIN.right, y1: py(parseTime(targetDate)), y2: py(parseTime(targetDate)), style: { stroke: COLOR.target, strokeDasharray: "2 3" } })) : null, staleAt !== undefined ? (_jsx("line", { "data-custd-chart-layer": "stale", x1: px(staleAt), x2: px(staleAt), y1: MARGIN.top, y2: height - MARGIN.bottom, style: { stroke: COLOR.stale, strokeDasharray: "4 4" } })) : null, _jsx("text", { x: MARGIN.left - 6, y: py(y.end), dy: "0.7em", textAnchor: "end", style: text, children: formatDate(y.end) }), _jsx("text", { x: MARGIN.left - 6, y: py(y.start), textAnchor: "end", style: text, children: formatDate(y.start) }), _jsx("text", { x: MARGIN.left, y: height - 8, style: text, children: formatDate(x.start) }), _jsx("text", { x: width - MARGIN.right, y: height - 8, textAnchor: "end", style: text, children: formatDate(x.end) })] }));
49
+ }
50
+ function midpointShiftDays(previous, latest) {
51
+ const midpoint = (estimate) => (parseTime(estimate.low) + parseTime(estimate.high)) / 2;
52
+ return (midpoint(latest) - midpoint(previous)) / DAY_MS;
53
+ }
54
+ function movementText(days) {
55
+ const rounded = Math.round(Math.abs(days));
56
+ if (rounded === 0)
57
+ return "Did not move";
58
+ return `Moved ${rounded} ${rounded === 1 ? "day" : "days"} ${days > 0 ? "later" : "earlier"}`;
59
+ }
60
+ function widthText(days) {
61
+ const rounded = Math.round(Math.abs(days));
62
+ if (rounded === 0)
63
+ return "range unchanged";
64
+ return `range ${days < 0 ? "narrowed" : "widened"} by ${rounded} ${rounded === 1 ? "day" : "days"}`;
65
+ }
@@ -0,0 +1,30 @@
1
+ import { type CSSProperties } from "react";
2
+ import type { ChartFormatters, ForecastChartData } from "./forecast-types.js";
3
+ export type ForecastChartLabels = {
4
+ zoomIn: string;
5
+ zoomOut: string;
6
+ panEarlier: string;
7
+ panLater: string;
8
+ reset: string;
9
+ zoomToData: string;
10
+ fullScreen: string;
11
+ controls: string;
12
+ empty: string;
13
+ noForecast: string;
14
+ /** The visible range, read out as it changes. */
15
+ range: (start: string, end: string) => string;
16
+ };
17
+ export type ForecastChartProps = ChartFormatters & {
18
+ data: ForecastChartData;
19
+ /** Names the chart; the default summary starts with it. */
20
+ title: string;
21
+ /** Replaces the generated text alternative. */
22
+ summary?: string;
23
+ labels?: Partial<ForecastChartLabels>;
24
+ /** Drawing size in SVG units; the chart scales to its container width. */
25
+ width?: number;
26
+ height?: number;
27
+ className?: string;
28
+ style?: CSSProperties;
29
+ };
30
+ export declare function ForecastChart({ data, title, summary, labels: labelOverrides, formatDate, formatValue, width, height, className, style, }: ForecastChartProps): import("react").JSX.Element;
@@ -0,0 +1,175 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useEffect, useId, useMemo, useRef, useState, } from "react";
3
+ import { DAY_MS, domainOf, formatNumber, formatUtcDate, panDomain, parseTime, sameDomain, scaleLinear, ticksOf, usePrefersReducedMotion, useTweenedDomain, zoomDomain, } from "./chart-scale.js";
4
+ const DEFAULT_LABELS = {
5
+ zoomIn: "Zoom in",
6
+ zoomOut: "Zoom out",
7
+ panEarlier: "Pan earlier",
8
+ panLater: "Pan later",
9
+ reset: "Reset view",
10
+ zoomToData: "Zoom to data",
11
+ fullScreen: "Full screen",
12
+ controls: "Chart view",
13
+ empty: "No measurements yet.",
14
+ noForecast: "No forecast yet.",
15
+ range: (start, end) => `Showing ${start} to ${end}`,
16
+ };
17
+ const MARGIN = { top: 12, right: 12, bottom: 28, left: 48 };
18
+ const MIN_SPAN_MS = DAY_MS / 24;
19
+ const ZOOM_FACTOR = 0.5;
20
+ const PAN_FRACTION = 0.25;
21
+ /** Colours come from these CSS variables, so the client's theme owns them. */
22
+ const COLOR = {
23
+ observed: "var(--custd-chart-observed, currentColor)",
24
+ forecast: "var(--custd-chart-forecast, currentColor)",
25
+ band: "var(--custd-chart-band, currentColor)",
26
+ target: "var(--custd-chart-target, currentColor)",
27
+ deadline: "var(--custd-chart-deadline, currentColor)",
28
+ trail: "var(--custd-chart-trail, currentColor)",
29
+ grid: "var(--custd-chart-grid, currentColor)",
30
+ surface: "var(--custd-chart-surface, Canvas)",
31
+ };
32
+ export function ForecastChart({ data, title, summary, labels: labelOverrides, formatDate = formatUtcDate, formatValue = formatNumber, width = 640, height = 280, className, style, }) {
33
+ const labels = { ...DEFAULT_LABELS, ...labelOverrides };
34
+ const domains = useMemo(() => chartDomains(data), [data]);
35
+ if (!domains) {
36
+ return (_jsx("div", { className: className, style: style, "data-custd-chart": "forecast", "data-custd-chart-state": "empty", children: _jsx("p", { children: labels.empty }) }));
37
+ }
38
+ return (_jsx(ForecastChartView, { data: data, domains: domains, title: title, summary: summary ?? forecastSummary(title, data, formatDate, formatValue), labels: labels, formatDate: formatDate, formatValue: formatValue, width: width, height: height, className: className, style: style }));
39
+ }
40
+ function ForecastChartView({ data, domains, labels, formatDate, ...props }) {
41
+ const { full } = domains;
42
+ const [selection, setSelection] = useState(null);
43
+ const view = selection ? zoomDomain(selection, 1, full, MIN_SPAN_MS) : full;
44
+ const [fullScreen, setFullScreen] = useState(false);
45
+ const reducedMotion = usePrefersReducedMotion();
46
+ const shown = useTweenedDomain(view, reducedMotion);
47
+ useEffect(() => {
48
+ if (!fullScreen)
49
+ return;
50
+ const exit = (event) => event.key === "Escape" && setFullScreen(false);
51
+ document.addEventListener("keydown", exit);
52
+ return () => document.removeEventListener("keydown", exit);
53
+ }, [fullScreen]);
54
+ const changeView = (update) => {
55
+ setSelection((current) => {
56
+ const bounded = current ? zoomDomain(current, 1, full, MIN_SPAN_MS) : full;
57
+ const next = update(bounded);
58
+ return sameDomain(next, full) ? null : next;
59
+ });
60
+ };
61
+ const zoom = (factor) => changeView((current) => zoomDomain(current, factor, full, MIN_SPAN_MS));
62
+ const pan = (fraction) => changeView((current) => panDomain(current, fraction, full));
63
+ const atFull = sameDomain(view, full);
64
+ return (_jsxs("div", { className: props.className, style: fullScreen ? { ...props.style, ...FULL_SCREEN_STYLE } : props.style, "data-custd-chart": "forecast", "data-custd-chart-fullscreen": fullScreen, "data-reduced-motion": reducedMotion, children: [_jsxs("fieldset", { "data-custd-chart-controls": "", style: { border: 0, margin: 0, padding: 0 }, children: [_jsx("legend", { style: VISUALLY_HIDDEN, children: labels.controls }), _jsx(ChartButton, { label: labels.zoomIn, onClick: () => zoom(ZOOM_FACTOR), disabled: view.end - view.start <= MIN_SPAN_MS }), _jsx(ChartButton, { label: labels.zoomOut, onClick: () => zoom(1 / ZOOM_FACTOR), disabled: atFull }), _jsx(ChartButton, { label: labels.panEarlier, onClick: () => pan(-PAN_FRACTION), disabled: view.start <= full.start }), _jsx(ChartButton, { label: labels.panLater, onClick: () => pan(PAN_FRACTION), disabled: view.end >= full.end }), _jsx(ChartButton, { label: labels.reset, onClick: () => setSelection(null), disabled: atFull }), _jsx(ChartButton, { label: labels.zoomToData, onClick: () => changeView(() => domains.observed), disabled: sameDomain(view, domains.observed) }), _jsx(ChartButton, { label: labels.fullScreen, pressed: fullScreen, onClick: () => setFullScreen((on) => !on) })] }), _jsx("p", { role: "status", "aria-live": "polite", style: VISUALLY_HIDDEN, children: labels.range(formatDate(view.start), formatDate(view.end)) }), _jsx(ForecastPlot, { data: data, x: shown, y: domains.y, formatDate: formatDate, onPan: pan, ...props }), data.completionMedian === undefined && data.completionInterval === undefined ? _jsx("p", { children: labels.noForecast }) : null] }));
65
+ }
66
+ function ChartButton({ label, onClick, disabled, pressed, }) {
67
+ return (_jsx("button", { type: "button", "data-custd-chart-action": "", onClick: onClick, disabled: disabled, "aria-pressed": pressed, children: label }));
68
+ }
69
+ function ForecastPlot({ data, x, y, title, summary, width, height, formatDate, formatValue, onPan }) {
70
+ const clipId = `custd-forecast-${useId().replace(/[^a-zA-Z0-9]/g, "")}`;
71
+ const drag = useRef(undefined);
72
+ const px = scaleLinear(x, MARGIN.left, width - MARGIN.right);
73
+ const py = scaleLinear(y, height - MARGIN.bottom, MARGIN.top);
74
+ const line = (points) => points.map((point) => `${px(parseTime(point.at))},${py(point.value)}`).join(" ");
75
+ const forecastFrom = data.forecastFrom ? parseTime(data.forecastFrom) : Number.NEGATIVE_INFINITY;
76
+ const fitted = data.observations.filter((point) => parseTime(point.at) >= forecastFrom);
77
+ const dimmed = data.observations.filter((point) => parseTime(point.at) < forecastFrom);
78
+ const last = data.observations[data.observations.length - 1];
79
+ const onPointerDown = (event) => {
80
+ const rendered = event.currentTarget.getBoundingClientRect().width;
81
+ if (rendered > 0)
82
+ drag.current = { clientX: event.clientX, width: rendered };
83
+ };
84
+ const onWheel = (event) => {
85
+ const delta = event.shiftKey && event.deltaX === 0 ? event.deltaY : event.deltaX;
86
+ if (delta === 0 || (!event.shiftKey && Math.abs(delta) < Math.abs(event.deltaY)))
87
+ return;
88
+ const distance = event.deltaMode === 1 ? delta * 16 : delta;
89
+ const rendered = event.currentTarget.getBoundingClientRect().width;
90
+ if (rendered > 0)
91
+ onPan(event.deltaMode === 2 ? delta : distance / rendered);
92
+ };
93
+ const endDrag = () => {
94
+ drag.current = undefined;
95
+ };
96
+ const onPointerUp = (event) => {
97
+ const start = drag.current;
98
+ drag.current = undefined;
99
+ if (!start || event.clientX === start.clientX)
100
+ return;
101
+ const plotShare = (width - MARGIN.left - MARGIN.right) / width;
102
+ onPan((start.clientX - event.clientX) / (start.width * plotShare));
103
+ };
104
+ return (_jsxs("svg", { role: "img", "aria-label": summary, viewBox: `0 0 ${width} ${height}`, width: "100%", style: { display: "block", touchAction: "pan-y" }, onWheel: onWheel, onPointerDown: onPointerDown, onPointerUp: onPointerUp, onPointerLeave: endDrag, onPointerCancel: endDrag, children: [_jsx("title", { children: title }), _jsx("defs", { children: _jsx("clipPath", { id: clipId, children: _jsx("rect", { x: MARGIN.left, y: 0, width: width - MARGIN.left - MARGIN.right, height: height }) }) }), _jsx(Axes, { x: x, y: y, width: width, height: height, formatDate: formatDate, formatValue: formatValue }), _jsxs("g", { clipPath: `url(#${clipId})`, children: [(data.earlierRuns ?? []).map((run) => (_jsx("polyline", { "data-custd-chart-layer": "trail", points: line(run.points), style: trailStyle, children: _jsx("title", { children: run.label }) }, run.label))), last && data.target !== undefined && data.completionInterval ? (_jsx("polygon", { "data-custd-chart-layer": "band", points: line([
105
+ last,
106
+ { at: data.completionInterval.lower, value: data.target },
107
+ { at: data.completionInterval.upper, value: data.target },
108
+ ]), style: { fill: COLOR.band, fillOpacity: 0.18, stroke: "none" } })) : null, data.posteriorLines && data.posteriorLines.length > 0 ? (_jsx("path", { "data-custd-chart-layer": "posterior", d: data.posteriorLines.map((posterior) => `M${line(posterior.points).split(" ").join("L")}`).join(" "), style: { fill: "none", stroke: COLOR.forecast, strokeOpacity: 0.2, strokeWidth: 1 } })) : null, last && data.target !== undefined && data.completionMedian ? (_jsx("polyline", { "data-custd-chart-layer": "median", points: line([last, { at: data.completionMedian, value: data.target }]), style: { fill: "none", stroke: COLOR.forecast, strokeWidth: 2, strokeDasharray: "6 4" } })) : null, dimmed.length > 0 ? _jsx(Observations, { layer: "dimmed", points: dimmed, px: px, py: py, opacity: 0.35 }) : null, _jsx(Observations, { layer: "observed", points: fitted, px: px, py: py, opacity: 1 })] }), data.target !== undefined ? (_jsx("line", { "data-custd-chart-layer": "target", x1: MARGIN.left, x2: width - MARGIN.right, y1: py(data.target), y2: py(data.target), style: { stroke: COLOR.target, strokeDasharray: "2 3" } })) : null, data.deadline !== undefined ? (_jsx(DeadlineLine, { at: px(parseTime(data.deadline)), width: width, height: height })) : null] }));
109
+ }
110
+ const trailStyle = { fill: "none", stroke: COLOR.trail, strokeOpacity: 0.25, strokeWidth: 1.5 };
111
+ function DeadlineLine({ at, width, height }) {
112
+ if (at < MARGIN.left || at > width - MARGIN.right)
113
+ return null;
114
+ return (_jsx("line", { "data-custd-chart-layer": "deadline", x1: at, x2: at, y1: MARGIN.top, y2: height - MARGIN.bottom, style: { stroke: COLOR.deadline, strokeWidth: 1.5 } }));
115
+ }
116
+ function Observations({ layer, points, px, py, opacity, }) {
117
+ return (_jsxs("g", { "data-custd-chart-layer": layer, style: { opacity }, children: [_jsx("polyline", { points: points.map((point) => `${px(parseTime(point.at))},${py(point.value)}`).join(" "), style: { fill: "none", stroke: COLOR.observed, strokeWidth: 2 } }), points.map((point) => (_jsx("circle", { cx: px(parseTime(point.at)), cy: py(point.value), r: 3, style: { fill: COLOR.observed } }, point.at)))] }));
118
+ }
119
+ function Axes({ x, y, width, height, formatDate, formatValue, }) {
120
+ const px = scaleLinear(x, MARGIN.left, width - MARGIN.right);
121
+ const py = scaleLinear(y, height - MARGIN.bottom, MARGIN.top);
122
+ const text = { fill: "currentColor", fontSize: 11, fontVariantNumeric: "tabular-nums" };
123
+ return (_jsxs("g", { "data-custd-chart-layer": "axes", children: [ticksOf(y, 4).map((tick) => (_jsxs("g", { children: [_jsx("line", { x1: MARGIN.left, x2: width - MARGIN.right, y1: py(tick), y2: py(tick), style: GRID }), _jsx("text", { x: MARGIN.left - 6, y: py(tick), dy: "0.32em", textAnchor: "end", style: text, children: formatValue(tick) })] }, `y${tick}`))), ticksOf(x, 4).map((tick, index) => (_jsx("text", { x: px(tick), y: height - MARGIN.bottom + 18, textAnchor: index === 0 ? "start" : index === 3 ? "end" : "middle", style: text, children: formatDate(tick) }, `x${tick}`)))] }));
124
+ }
125
+ const GRID = { stroke: COLOR.grid, strokeOpacity: 0.2 };
126
+ const VISUALLY_HIDDEN = {
127
+ position: "absolute",
128
+ width: 1,
129
+ height: 1,
130
+ overflow: "hidden",
131
+ clip: "rect(0 0 0 0)",
132
+ whiteSpace: "nowrap",
133
+ };
134
+ const FULL_SCREEN_STYLE = {
135
+ position: "fixed",
136
+ inset: 0,
137
+ zIndex: 1000,
138
+ overflow: "auto",
139
+ padding: 16,
140
+ background: COLOR.surface,
141
+ };
142
+ function chartDomains(data) {
143
+ const observedTimes = data.observations.map((point) => parseTime(point.at));
144
+ const observed = domainOf(observedTimes, DAY_MS);
145
+ if (!observed)
146
+ return undefined;
147
+ const lines = [...(data.posteriorLines ?? []), ...(data.earlierRuns ?? [])].flatMap((line) => line.points);
148
+ const times = [
149
+ ...observedTimes,
150
+ ...lines.map((point) => parseTime(point.at)),
151
+ ...[data.deadline, data.completionMedian, data.completionInterval?.lower, data.completionInterval?.upper]
152
+ .filter((value) => value !== undefined)
153
+ .map(parseTime),
154
+ ];
155
+ const values = [0, ...data.observations.map((point) => point.value), ...lines.map((point) => point.value)];
156
+ if (data.target !== undefined)
157
+ values.push(data.target);
158
+ const y = domainOf(values, 1) ?? { start: 0, end: 1 };
159
+ return { full: domainOf(times, DAY_MS) ?? observed, observed, y: { start: y.start, end: y.end * 1.05 } };
160
+ }
161
+ function forecastSummary(title, data, formatDate, formatValue) {
162
+ const parts = [`${title}: ${data.observations.length} measurements`];
163
+ if (data.target !== undefined)
164
+ parts.push(`target ${formatValue(data.target)}`);
165
+ if (data.completionMedian)
166
+ parts.push(`expected ${formatDate(parseTime(data.completionMedian))}`);
167
+ const interval = data.completionInterval;
168
+ if (interval) {
169
+ const confidence = Math.round(interval.confidence * 100);
170
+ parts.push(`${confidence}% likely between ${formatDate(parseTime(interval.lower))} and ${formatDate(parseTime(interval.upper))}`);
171
+ }
172
+ if (data.deadline)
173
+ parts.push(`deadline ${formatDate(parseTime(data.deadline))}`);
174
+ return parts.join("; ");
175
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Props DTOs for the forecast building blocks. Field names match the Custd analytics API
3
+ * forecast run (`counter` result) and forecast story (`delivery`) JSON, so a response can be
4
+ * passed through with at most a rename. Times are ISO-8601 strings.
5
+ */
6
+ /** One value at one time: a measurement, or a point on a projected line (`MeasurementForecastPoint`). */
7
+ export type ForecastPoint = {
8
+ at: string;
9
+ value: number;
10
+ };
11
+ /** A completion-date interval at a stated confidence (`counter.completionInterval`). */
12
+ export type ForecastInterval = {
13
+ confidence: number;
14
+ lower: string;
15
+ upper: string;
16
+ };
17
+ /** One posterior draw projected from the latest measurement (`counter.detail.posteriorLines[]`). */
18
+ export type ForecastPosteriorLine = {
19
+ points: readonly ForecastPoint[];
20
+ };
21
+ /** An earlier run of the same work, drawn as a faint trail. */
22
+ export type ForecastEarlierRun = {
23
+ label: string;
24
+ points: readonly ForecastPoint[];
25
+ };
26
+ export type ForecastChartData = {
27
+ /** The run's measurements, oldest first. */
28
+ observations: readonly ForecastPoint[];
29
+ /** The value the run is counting towards. */
30
+ target?: number;
31
+ /** The deadline the run must reach the target by. */
32
+ deadline?: string;
33
+ /** Median completion date (`percentiles.p50`). */
34
+ completionMedian?: string;
35
+ /** Central completion interval (`counter.completionInterval`, 90%). */
36
+ completionInterval?: ForecastInterval;
37
+ /** Measurements before this time were left out of the fit and are drawn dimmed (`forecastFrom`). */
38
+ forecastFrom?: string;
39
+ /** `counter.detail.posteriorLines`. */
40
+ posteriorLines?: readonly ForecastPosteriorLine[];
41
+ earlierRuns?: readonly ForecastEarlierRun[];
42
+ };
43
+ /** One arrival-time bin (`counter.detail.arrivalHistogram.bins[]`). */
44
+ export type ArrivalHistogramBin = {
45
+ start: string;
46
+ end: string;
47
+ count: number;
48
+ };
49
+ /** Posterior draws counted by arrival time (`counter.detail.arrivalHistogram`). */
50
+ export type ArrivalHistogramData = {
51
+ bins: readonly ArrivalHistogramBin[];
52
+ neverCount: number;
53
+ };
54
+ /** One dated 90% estimate of the completion date (`delivery.estimates[]`). */
55
+ export type ConvergenceEstimate = {
56
+ estimatedAt: string;
57
+ low: string;
58
+ high: string;
59
+ note?: string;
60
+ /** Spread of the estimate in days; a narrowing width is the estimate converging. */
61
+ widthDays: number;
62
+ /** How far the midpoint moved from the previous estimate, in days; positive is later. */
63
+ movementDays?: number;
64
+ };
65
+ /** Formatters let the client own date and number wording. */
66
+ export type ChartFormatters = {
67
+ formatDate?: (epochMs: number) => string;
68
+ formatValue?: (value: number) => string;
69
+ };
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Props DTOs for the forecast building blocks. Field names match the Custd analytics API
3
+ * forecast run (`counter` result) and forecast story (`delivery`) JSON, so a response can be
4
+ * passed through with at most a rename. Times are ISO-8601 strings.
5
+ */
6
+ export {};
@@ -0,0 +1,28 @@
1
+ import { type AppEventMap, type HostedAppOptions, type HostedAppStart } from "@haakco/custd-sdk/browser";
2
+ import { type ReactNode } from "react";
3
+ export declare const CUSTD_HOSTED_APP_LOADING = "loading";
4
+ export type CustdHostedAppState<TEvents extends AppEventMap = AppEventMap> = {
5
+ status: typeof CUSTD_HOSTED_APP_LOADING;
6
+ } | HostedAppStart<TEvents>;
7
+ export type CustdHostedAppProviderProps = {
8
+ /** Read once on mount; later changes do not restart the app. */
9
+ options?: HostedAppOptions;
10
+ /** Called after a sign-in redirect completes. Defaults to replacing the URL with `returnTo`. */
11
+ onSignInComplete?: (returnTo: string) => void;
12
+ children?: ReactNode;
13
+ };
14
+ /**
15
+ * Starts the hosted app once and shares its state. Children render while the
16
+ * discovery file loads and after it fails; when sign-in is enabled they are
17
+ * wrapped in `CustdSessionProvider`, so `useCustdSession` works once ready.
18
+ */
19
+ export declare function CustdHostedAppProvider({ options, onSignInComplete, children }: CustdHostedAppProviderProps): import("react").JSX.Element;
20
+ /** The hosted app's state: loading, ready with its handle, or a typed error. */
21
+ export declare function useCustdHostedApp<TEvents extends AppEventMap = AppEventMap>(): CustdHostedAppState<TEvents>;
22
+ /** The hosted app's state, or null outside `CustdHostedAppProvider`. */
23
+ export declare function useOptionalCustdHostedApp(): CustdHostedAppState | null;
24
+ /**
25
+ * Starts the app and reports its result while active. The returned cleanup
26
+ * stops the app, including one that resolves after cleanup.
27
+ */
28
+ export declare function watchHostedApp(start: () => Promise<HostedAppStart>, onResult: (result: HostedAppStart) => void): () => void;
@@ -0,0 +1,48 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { HOSTED_APP_STATUSES, startHostedApp, } from "@haakco/custd-sdk/browser";
3
+ import { createContext, useContext, useEffect, useRef, useState } from "react";
4
+ import { CustdSessionProvider } from "./session.js";
5
+ export const CUSTD_HOSTED_APP_LOADING = "loading";
6
+ const HostedAppContext = createContext(null);
7
+ /**
8
+ * Starts the hosted app once and shares its state. Children render while the
9
+ * discovery file loads and after it fails; when sign-in is enabled they are
10
+ * wrapped in `CustdSessionProvider`, so `useCustdSession` works once ready.
11
+ */
12
+ export function CustdHostedAppProvider({ options, onSignInComplete, children }) {
13
+ const [state, setState] = useState({ status: CUSTD_HOSTED_APP_LOADING });
14
+ const initialOptions = useRef(options);
15
+ useEffect(() => watchHostedApp(() => startHostedApp(initialOptions.current), setState), []);
16
+ const signIn = state.status === HOSTED_APP_STATUSES.ready ? state.app.signIn : undefined;
17
+ return (_jsx(HostedAppContext.Provider, { value: state, children: signIn ? (_jsx(CustdSessionProvider, { client: signIn, onSignInComplete: onSignInComplete, children: children })) : (children) }));
18
+ }
19
+ /** The hosted app's state: loading, ready with its handle, or a typed error. */
20
+ export function useCustdHostedApp() {
21
+ const state = useContext(HostedAppContext);
22
+ if (!state)
23
+ throw new Error("custd: useCustdHostedApp must be used inside CustdHostedAppProvider");
24
+ return state;
25
+ }
26
+ /** The hosted app's state, or null outside `CustdHostedAppProvider`. */
27
+ export function useOptionalCustdHostedApp() {
28
+ return useContext(HostedAppContext);
29
+ }
30
+ /**
31
+ * Starts the app and reports its result while active. The returned cleanup
32
+ * stops the app, including one that resolves after cleanup.
33
+ */
34
+ export function watchHostedApp(start, onResult) {
35
+ let active = true;
36
+ const pending = start();
37
+ void pending.then((result) => {
38
+ if (active)
39
+ onResult(result);
40
+ });
41
+ return () => {
42
+ active = false;
43
+ void pending.then((result) => {
44
+ if (result.status === HOSTED_APP_STATUSES.ready)
45
+ result.app.stop();
46
+ });
47
+ };
48
+ }
@@ -0,0 +1,43 @@
1
+ import { type RenderedWidgetData, type ReportingDataState, type ReportingViewState } from "@haakco/custd-sdk";
2
+ import { type QueryFunction, type QueryKey, type UseQueryOptions, type UseQueryResult } from "@tanstack/react-query";
3
+ import type { ReactNode } from "react";
4
+ export type CustdReportingViewState<TData extends RenderedWidgetData> = ReportingViewState<TData>;
5
+ export type CustdReportingDisplayState = "loading" | "error" | ReportingDataState;
6
+ export type CustdReportingQueryOptions<TData extends RenderedWidgetData, TError = unknown, TQueryKey extends QueryKey = QueryKey> = Omit<UseQueryOptions<TData, TError, TData, TQueryKey>, "queryKey" | "queryFn"> & {
7
+ queryKey: TQueryKey;
8
+ queryFn: QueryFunction<TData, TQueryKey>;
9
+ };
10
+ export type CustdReportingQueryResult<TData extends RenderedWidgetData, TError = unknown> = UseQueryResult<TData, TError> & {
11
+ view: CustdReportingViewState<TData>;
12
+ };
13
+ export declare function getCustdReportingViewState<TData extends RenderedWidgetData, TError = unknown>(query: UseQueryResult<TData, TError>): CustdReportingViewState<TData>;
14
+ export declare function useCustdReportingViewState<TData extends RenderedWidgetData, TError = unknown>(query: UseQueryResult<TData, TError>): CustdReportingViewState<TData>;
15
+ export declare function useCustdReportingQuery<TData extends RenderedWidgetData, TError = unknown, TQueryKey extends QueryKey = QueryKey>(options: CustdReportingQueryOptions<TData, TError, TQueryKey>): CustdReportingQueryResult<TData, TError>;
16
+ export type CustdReportingLabels = Partial<Record<CustdReportingDisplayState, string>>;
17
+ export type CustdReportingStateProps<TData extends RenderedWidgetData> = {
18
+ view: CustdReportingViewState<TData>;
19
+ children?: ReactNode | ((data: TData) => ReactNode);
20
+ onRetry?: () => void | Promise<void>;
21
+ retryLabel?: string;
22
+ labels?: CustdReportingLabels;
23
+ renderState?: (state: CustdReportingDisplayState, view: CustdReportingViewState<TData>) => ReactNode;
24
+ className?: string;
25
+ };
26
+ export declare function getCustdReportingDisplayState<TData extends RenderedWidgetData>(view: CustdReportingViewState<TData>): CustdReportingDisplayState;
27
+ export declare function CustdReportingState<TData extends RenderedWidgetData>({ view, children, onRetry, retryLabel, labels, renderState, className, }: CustdReportingStateProps<TData>): import("react").JSX.Element;
28
+ export { CustdAccountMenuItem, type CustdAccountMenuItemProps } from "./account-menu-item.js";
29
+ export { CUSTD_APP_LIVE_IDLE, type CustdAppItemAccess, type CustdAppLiveResult, type CustdAppLiveState, type UseAppLiveOptions, useAppForecast, useAppForecastStory, useAppItem, useAppMeeting, useAppModelRun, } from "./app-items.js";
30
+ export { ArrivalHistogram, type ArrivalHistogramLabels, type ArrivalHistogramProps, } from "./arrival-histogram.js";
31
+ export { ConvergenceStory, type ConvergenceStoryLabels, type ConvergenceStoryProps } from "./convergence-story.js";
32
+ export { ForecastChart, type ForecastChartLabels, type ForecastChartProps } from "./forecast-chart.js";
33
+ export type { ArrivalHistogramBin, ArrivalHistogramData, ChartFormatters, ConvergenceEstimate, ForecastChartData, ForecastEarlierRun, ForecastInterval, ForecastPoint, ForecastPosteriorLine, } from "./forecast-types.js";
34
+ export { CUSTD_HOSTED_APP_LOADING, CustdHostedAppProvider, type CustdHostedAppProviderProps, type CustdHostedAppState, useCustdHostedApp, } from "./hosted-app.js";
35
+ export { MeasureNextPanel, type MeasureNextPanelLabels, type MeasureNextPanelProps, } from "./measure-next-panel.js";
36
+ export { ModelCalculator, type ModelCalculatorInput, type ModelCalculatorLabels, type ModelCalculatorProps, type ModelCalculatorRequest, type ModelCalculatorResult, } from "./model-calculator.js";
37
+ export { downloadSummaryCsv } from "./model-csv.js";
38
+ export { ModelEditor, type ModelEditorLabels, type ModelEditorProps } from "./model-editor.js";
39
+ export { formatModelNumber, formatModelValue, type ModelValue, type ModelValueParse, parseModelValue, } from "./model-shorthand.js";
40
+ export { QuantityHistogram, type QuantityHistogramLabels, type QuantityHistogramProps, } from "./quantity-histogram.js";
41
+ export { SafeMarkdown, type SafeMarkdownProps } from "./safe-markdown.js";
42
+ export { rankSensitivityInputs, SensitivityView, type SensitivityViewLabels, type SensitivityViewProps, } from "./sensitivity-view.js";
43
+ export { type CustdSession, CustdSessionProvider, type CustdSessionProviderProps, useCustdSession } from "./session.js";
package/dist/index.js ADDED
@@ -0,0 +1,67 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { getReportingViewState, } from "@haakco/custd-sdk";
3
+ import { useQuery, } from "@tanstack/react-query";
4
+ export function getCustdReportingViewState(query) {
5
+ return getReportingViewState(toReportingQueryState(query));
6
+ }
7
+ export function useCustdReportingViewState(query) {
8
+ return getCustdReportingViewState(query);
9
+ }
10
+ export function useCustdReportingQuery(options) {
11
+ const query = useQuery(options);
12
+ return { ...query, view: useCustdReportingViewState(query) };
13
+ }
14
+ const DEFAULT_LABELS = {
15
+ loading: "Loading report…",
16
+ error: "Report unavailable right now.",
17
+ unavailable: "Reporting is unavailable.",
18
+ empty: "No data for this period.",
19
+ stale: "Showing older data.",
20
+ partial: "Some report data is still being prepared.",
21
+ stale_partial: "Showing older, incomplete data.",
22
+ ready: "",
23
+ };
24
+ export function getCustdReportingDisplayState(view) {
25
+ if (view.phase === "loading")
26
+ return "loading";
27
+ if (view.phase === "error")
28
+ return "error";
29
+ return view.dataState;
30
+ }
31
+ export function CustdReportingState({ view, children, onRetry, retryLabel = "Try again", labels, renderState, className, }) {
32
+ const state = getCustdReportingDisplayState(view);
33
+ const data = view.data;
34
+ const message = renderState ? renderState(state, view) : (labels?.[state] ?? DEFAULT_LABELS[state]);
35
+ const showData = data !== undefined && state !== "empty" && state !== "unavailable";
36
+ const content = showData ? renderReportingContent(children, data) : null;
37
+ const retry = view.retryable && onRetry ? (_jsx("button", { type: "button", "data-custd-reporting-action": "retry", onClick: () => void onRetry(), children: retryLabel })) : null;
38
+ const feedback = state === "ready" && message === "" && retry === null ? null : (_jsxs("div", { role: state === "error" ? "alert" : "status", "aria-live": state === "error" ? "assertive" : "polite", "data-custd-reporting-feedback": state, children: [typeof message === "string" ? message !== "" ? _jsx("p", { children: message }) : null : message, retry] }));
39
+ return (_jsxs("div", { className: className, "data-custd-reporting-state": state, "aria-busy": state === "loading" ? true : undefined, children: [feedback, content] }));
40
+ }
41
+ function toReportingQueryState(query) {
42
+ if (query.status === "pending" || query.isFetching) {
43
+ return { status: "loading", data: query.data };
44
+ }
45
+ if (query.status === "error") {
46
+ return { status: "error", error: query.error, data: query.data };
47
+ }
48
+ return { status: "success", data: query.data };
49
+ }
50
+ function renderReportingContent(children, data) {
51
+ return typeof children === "function" ? children(data) : children;
52
+ }
53
+ export { CustdAccountMenuItem } from "./account-menu-item.js";
54
+ export { CUSTD_APP_LIVE_IDLE, useAppForecast, useAppForecastStory, useAppItem, useAppMeeting, useAppModelRun, } from "./app-items.js";
55
+ export { ArrivalHistogram, } from "./arrival-histogram.js";
56
+ export { ConvergenceStory } from "./convergence-story.js";
57
+ export { ForecastChart } from "./forecast-chart.js";
58
+ export { CUSTD_HOSTED_APP_LOADING, CustdHostedAppProvider, useCustdHostedApp, } from "./hosted-app.js";
59
+ export { MeasureNextPanel, } from "./measure-next-panel.js";
60
+ export { ModelCalculator, } from "./model-calculator.js";
61
+ export { downloadSummaryCsv } from "./model-csv.js";
62
+ export { ModelEditor } from "./model-editor.js";
63
+ export { formatModelNumber, formatModelValue, parseModelValue, } from "./model-shorthand.js";
64
+ export { QuantityHistogram, } from "./quantity-histogram.js";
65
+ export { SafeMarkdown } from "./safe-markdown.js";
66
+ export { rankSensitivityInputs, SensitivityView, } from "./sensitivity-view.js";
67
+ export { CustdSessionProvider, useCustdSession } from "./session.js";
@@ -0,0 +1,24 @@
1
+ import type { AppModelDecision, AppModelInformation } from "@haakco/custd-sdk/browser";
2
+ import type { CSSProperties } from "react";
3
+ export type MeasureNextPanelLabels = {
4
+ title: string;
5
+ noDecision: string;
6
+ recommendation: (recommended: "act" | "hold", actProbability: string) => string;
7
+ decision: (output: string, threshold: string) => string;
8
+ suggested: (input: string) => string;
9
+ nothingWorthwhile: string;
10
+ certaintyWorth: (value: string) => string;
11
+ inputWorth: (value: string) => string;
12
+ };
13
+ export type MeasureNextPanelProps = {
14
+ /** `run.information`; absent when the run had no decision. */
15
+ information: AppModelInformation | undefined;
16
+ /** `run.decision`, to say what was decided. */
17
+ decision?: AppModelDecision;
18
+ formatValue?: (value: number) => string;
19
+ labels?: Partial<MeasureNextPanelLabels>;
20
+ className?: string;
21
+ style?: CSSProperties;
22
+ };
23
+ /** The decision's recommendation and the inputs ranked by what knowing each exactly is worth. */
24
+ export declare function MeasureNextPanel({ information, decision, formatValue, labels: overrides, className, style, }: MeasureNextPanelProps): import("react").JSX.Element;
@@ -0,0 +1,23 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { formatModelNumber } from "./model-shorthand.js";
3
+ const DEFAULT_LABELS = {
4
+ title: "What to measure next",
5
+ noDecision: "Set a decision (a threshold on an output) to see which input is worth measuring first.",
6
+ recommendation: (recommended, chance) => recommended === "act" ? `Act now: ${chance} chance acting pays.` : `Hold: only ${chance} chance acting pays.`,
7
+ decision: (output, threshold) => `Deciding on ${output} against ${threshold}.`,
8
+ suggested: (input) => `Measure ${input} next.`,
9
+ nothingWorthwhile: "No single measurement is worth its cost now: decide with what you know.",
10
+ certaintyWorth: (value) => `Knowing everything exactly would be worth ${value}.`,
11
+ inputWorth: (value) => `worth ${value} to know exactly`,
12
+ };
13
+ /** The decision's recommendation and the inputs ranked by what knowing each exactly is worth. */
14
+ export function MeasureNextPanel({ information, decision, formatValue = formatModelNumber, labels: overrides, className, style, }) {
15
+ const labels = { ...DEFAULT_LABELS, ...overrides };
16
+ if (!information) {
17
+ return (_jsxs("section", { className: className, style: style, "data-custd-measure-next": "none", children: [_jsx("h3", { children: labels.title }), _jsx("p", { children: labels.noDecision })] }));
18
+ }
19
+ const ranked = [...(information.inputs ?? [])].sort((left, right) => right.expectedValueOfPerfectInformation - left.expectedValueOfPerfectInformation);
20
+ const suggested = information.suggestedNextMeasurement;
21
+ const chance = `${Math.round(information.actProbability * 100)}%`;
22
+ return (_jsxs("section", { className: className, style: style, "data-custd-measure-next": suggested || "nothing", children: [_jsx("h3", { children: labels.title }), decision ? _jsx("p", { children: labels.decision(decision.output, formatValue(decision.threshold)) }) : null, _jsx("p", { children: labels.recommendation(information.recommended, chance) }), _jsx("p", { children: _jsx("strong", { children: suggested ? labels.suggested(suggested) : labels.nothingWorthwhile }) }), _jsx("p", { children: labels.certaintyWorth(formatValue(information.expectedValueOfPerfectInformation)) }), ranked.length > 0 ? (_jsx("ol", { children: ranked.map((input) => (_jsxs("li", { "aria-current": input.name === suggested ? "true" : undefined, children: [input.name, ": ", labels.inputWorth(formatValue(input.expectedValueOfPerfectInformation))] }, input.name))) })) : null] }));
23
+ }