@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,54 @@
1
+ import { type AppItemAccess, type AppItemsClient, type AppModelInput, type AppModelQuantityResult, type AppModelQueuedRunFailure, type AppModelVersion } from "@haakco/custd-sdk/browser";
2
+ import { type CSSProperties } from "react";
3
+ /** One input value the calculator tries, in place of the saved one, for this run only. */
4
+ export type ModelCalculatorInput = {
5
+ name: string;
6
+ input: AppModelInput;
7
+ };
8
+ /** A run over a saved version with some inputs replaced. It must never save a version. */
9
+ export type ModelCalculatorRequest = {
10
+ versionNumber: number;
11
+ inputs: ModelCalculatorInput[];
12
+ outputs: string[];
13
+ };
14
+ /** A calculation's results, or a latest run's, which may say its queued live-input run failed. */
15
+ export type ModelCalculatorResult = {
16
+ quantities: AppModelQuantityResult[] | null;
17
+ queuedRunFailure?: AppModelQueuedRunFailure;
18
+ };
19
+ export type ModelCalculatorLabels = {
20
+ inputs: string;
21
+ outputs: string;
22
+ calculate: string;
23
+ calculating: string;
24
+ unavailable: string;
25
+ failed: string;
26
+ limited: string;
27
+ queuedRunFailed: (failure: AppModelQueuedRunFailure) => string;
28
+ notCalculated: string;
29
+ formulaRefused: string;
30
+ output: (mean: string, low: string, high: string) => string;
31
+ };
32
+ export type ModelCalculatorProps = {
33
+ version: AppModelVersion;
34
+ /** The input quantities the form offers; bound and formula quantities are skipped. */
35
+ inputs: string[];
36
+ /** The quantities whose results it shows. */
37
+ outputs: string[];
38
+ /** Results shown before the first calculation, such as the latest run. */
39
+ baseline?: ModelCalculatorResult;
40
+ /**
41
+ * Runs the version with the form's values without saving anything. Defaults to the client's
42
+ * `calculateModel` when `access` is given; absent both, the form is read-only.
43
+ */
44
+ calculate?: (request: ModelCalculatorRequest) => Promise<ModelCalculatorResult>;
45
+ /** The item's link token, or `{ item }` for a signed-in owner; any link may calculate. */
46
+ access?: AppItemAccess;
47
+ /** Defaults to the `CustdHostedAppProvider` app's `appItems`. */
48
+ client?: AppItemsClient;
49
+ labels?: Partial<ModelCalculatorLabels>;
50
+ className?: string;
51
+ style?: CSSProperties;
52
+ };
53
+ /** A form over chosen inputs and outputs of a saved version. Calculating never changes the model. */
54
+ export declare function ModelCalculator({ version, inputs, outputs, baseline, calculate: given, access, client, labels: overrides, className, style, }: ModelCalculatorProps): import("react").JSX.Element;
@@ -0,0 +1,89 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { APP_MODEL_ERROR_CODES, APP_MODEL_INPUT_SHAPES, APP_MODEL_QUANTITY_KINDS, AppItemError, HOSTED_APP_STATUSES, } from "@haakco/custd-sdk/browser";
3
+ import { useId, useState } from "react";
4
+ import { useOptionalCustdHostedApp } from "./hosted-app.js";
5
+ import { formatModelNumber, formatModelValue, parseModelValue, rangeDistributionOf } from "./model-shorthand.js";
6
+ const DEFAULT_LABELS = {
7
+ inputs: "Try values",
8
+ outputs: "Results",
9
+ calculate: "Calculate",
10
+ calculating: "Calculating…",
11
+ unavailable: "Calculating with other values is not available here yet.",
12
+ failed: "The calculation did not run.",
13
+ limited: "Too many calculations just now. Try again in a minute.",
14
+ queuedRunFailed: ({ error, attempts, failedAt }) => `Live inputs changed but the new run failed after ${attempts} ${attempts === 1 ? "try" : "tries"} (last ${new Date(failedAt).toLocaleString()}): ${error}. These results are older.`,
15
+ notCalculated: "not calculated",
16
+ formulaRefused: "A calculator takes a value, a range or k of n, not a formula.",
17
+ output: (mean, low, high) => `${mean} (90%: ${low} to ${high})`,
18
+ };
19
+ /** A form over chosen inputs and outputs of a saved version. Calculating never changes the model. */
20
+ export function ModelCalculator({ version, inputs, outputs, baseline, calculate: given, access, client, labels: overrides, className, style, }) {
21
+ const labels = { ...DEFAULT_LABELS, ...overrides };
22
+ const hosted = useOptionalCustdHostedApp();
23
+ const runner = client ?? (hosted?.status === HOSTED_APP_STATUSES.ready ? hosted.app.appItems : undefined);
24
+ const calculate = given ??
25
+ (runner && access ? (request) => runner.calculateModel(access, request) : undefined);
26
+ const formId = useId();
27
+ const [fields, setFields] = useState(() => calculatorFields(version.quantities, inputs));
28
+ const [errors, setErrors] = useState({});
29
+ const [result, setResult] = useState();
30
+ const [state, setState] = useState("idle");
31
+ const shown = result ?? baseline;
32
+ const submit = async (event) => {
33
+ event.preventDefault();
34
+ if (!calculate)
35
+ return;
36
+ const checked = checkFields(fields, labels);
37
+ setErrors(checked.errors);
38
+ if (!checked.inputs)
39
+ return;
40
+ setState("running");
41
+ try {
42
+ setResult(await calculate({ versionNumber: version.versionNumber, inputs: checked.inputs, outputs }));
43
+ setState("idle");
44
+ }
45
+ catch (error) {
46
+ const limited = error instanceof AppItemError && error.code === APP_MODEL_ERROR_CODES.calculateLimited;
47
+ setState(limited ? "limited" : "failed");
48
+ }
49
+ };
50
+ return (_jsxs("form", { className: className, style: style, onSubmit: submit, noValidate: true, "data-custd-model-calculator": "", children: [_jsxs("fieldset", { children: [_jsx("legend", { children: labels.inputs }), fields.map((field, index) => {
51
+ const id = `${formId}-${field.quantity.name}`;
52
+ const error = errors[field.quantity.name];
53
+ return (_jsxs("div", { style: { display: "grid" }, children: [_jsxs("label", { htmlFor: id, children: [field.quantity.name, field.quantity.unit ? ` (${field.quantity.unit})` : ""] }), _jsx("input", { id: id, value: field.text, readOnly: !calculate, "aria-invalid": error ? true : undefined, "aria-describedby": error ? `${id}-error` : undefined, onChange: (event) => setFields((current) => current.map((other, at) => (at === index ? { ...other, text: event.target.value } : other))) }), error ? _jsx("span", { id: `${id}-error`, children: error }) : null] }, field.quantity.name));
54
+ })] }), calculate ? (_jsx("button", { type: "submit", disabled: state === "running", children: state === "running" ? labels.calculating : labels.calculate })) : (_jsx("p", { children: labels.unavailable })), state === "failed" || state === "limited" ? _jsx("p", { role: "alert", children: labels[state] }) : null, !result && baseline?.queuedRunFailure ? (_jsx("p", { role: "status", children: labels.queuedRunFailed(baseline.queuedRunFailure) })) : null, _jsx("section", { "aria-live": "polite", "aria-label": labels.outputs, children: _jsx("dl", { children: outputs.map((name) => (_jsx(OutputRow, { name: name, result: shown, labels: labels, version: version }, name))) }) })] }));
55
+ }
56
+ function OutputRow({ name, result, labels, version, }) {
57
+ const quantity = result?.quantities?.find((candidate) => candidate.name === name);
58
+ const unit = version.quantities.find((candidate) => candidate.name === name)?.unit;
59
+ const show = (value) => (unit ? `${formatModelNumber(value)} ${unit}` : formatModelNumber(value));
60
+ const summary = quantity?.summary;
61
+ return (_jsxs("div", { "data-custd-calculator-output": name, children: [_jsx("dt", { children: name }), _jsx("dd", { children: summary
62
+ ? labels.output(show(summary.mean), show(summary.percentiles.p5), show(summary.percentiles.p95))
63
+ : (quantity?.error?.detail ?? labels.notCalculated) })] }));
64
+ }
65
+ function calculatorFields(quantities, names) {
66
+ const fields = [];
67
+ for (const name of names) {
68
+ const quantity = quantities.find((candidate) => candidate.name === name);
69
+ if (quantity?.kind !== APP_MODEL_QUANTITY_KINDS.input || quantity.input.shape === APP_MODEL_INPUT_SHAPES.bound) {
70
+ continue;
71
+ }
72
+ fields.push({ quantity, text: formatModelValue(quantity) });
73
+ }
74
+ return fields;
75
+ }
76
+ function checkFields(fields, labels) {
77
+ const errors = {};
78
+ const inputs = [];
79
+ for (const field of fields) {
80
+ const parsed = parseModelValue(field.text, rangeDistributionOf(field.quantity));
81
+ if (!parsed.ok)
82
+ errors[field.quantity.name] = parsed.message;
83
+ else if (parsed.value.kind !== APP_MODEL_QUANTITY_KINDS.input)
84
+ errors[field.quantity.name] = labels.formulaRefused;
85
+ else
86
+ inputs.push({ name: field.quantity.name, input: parsed.value.input });
87
+ }
88
+ return Object.keys(errors).length > 0 ? { errors } : { errors, inputs };
89
+ }
@@ -0,0 +1,9 @@
1
+ import { type AppModelQuantity, type AppModelRun } from "@haakco/custd-sdk/browser";
2
+ /**
3
+ * Saves a run's per-quantity summary (mean, spread, percentiles or failure) as a CSV file the
4
+ * browser downloads. Pass the version's quantities to include their units.
5
+ */
6
+ export declare function downloadSummaryCsv(run: Pick<AppModelRun, "quantities" | "runUuid">, options?: {
7
+ quantities?: AppModelQuantity[];
8
+ filename?: string;
9
+ }): void;
@@ -0,0 +1,17 @@
1
+ import { modelRunSummaryCsv } from "@haakco/custd-sdk/browser";
2
+ /**
3
+ * Saves a run's per-quantity summary (mean, spread, percentiles or failure) as a CSV file the
4
+ * browser downloads. Pass the version's quantities to include their units.
5
+ */
6
+ export function downloadSummaryCsv(run, options = {}) {
7
+ const blob = new Blob([modelRunSummaryCsv(run, options.quantities)], { type: "text/csv;charset=utf-8" });
8
+ const url = URL.createObjectURL(blob);
9
+ const link = document.createElement("a");
10
+ link.href = url;
11
+ link.download = options.filename ?? `model-run-${run.runUuid}.csv`;
12
+ document.body.append(link);
13
+ link.click();
14
+ link.remove();
15
+ // Revoke after the click has been handled, or some browsers cancel the download.
16
+ setTimeout(() => URL.revokeObjectURL(url), 0);
17
+ }
@@ -0,0 +1,37 @@
1
+ import { type AppModelQuantity, type AppModelRangeDistribution, type AppModelVersionCreateRequest } from "@haakco/custd-sdk/browser";
2
+ import { type CSSProperties } from "react";
3
+ export type ModelEditorLabels = {
4
+ title: string;
5
+ name: string;
6
+ value: string;
7
+ valueHint: string;
8
+ unit: string;
9
+ description: string;
10
+ rangeShape: string;
11
+ distributions: Record<AppModelRangeDistribution, string>;
12
+ bound: (source: string) => string;
13
+ add: string;
14
+ remove: (name: string) => string;
15
+ note: string;
16
+ save: string;
17
+ saving: string;
18
+ saved: string;
19
+ nameInvalid: string;
20
+ nameTaken: string;
21
+ saveFailed: string;
22
+ };
23
+ export type ModelEditorProps = {
24
+ /** The version being edited. Remount with a new `key` to load another version. */
25
+ quantities: AppModelQuantity[];
26
+ /** Saves the edited list as a new version, e.g. `appItems.addModelVersion(ownerToken, request)`. */
27
+ onSave: (request: AppModelVersionCreateRequest) => Promise<unknown>;
28
+ labels?: Partial<ModelEditorLabels>;
29
+ className?: string;
30
+ style?: CSSProperties;
31
+ };
32
+ /**
33
+ * Edits a model's quantities in one list: name, value shorthand, unit and a Markdown description
34
+ * shown back safely. Saving sends the whole list as a new version; the server's validation
35
+ * message is shown on the quantity it names, or above the save button.
36
+ */
37
+ export declare function ModelEditor({ quantities, onSave, labels: overrides, className, style }: ModelEditorProps): import("react").JSX.Element;
@@ -0,0 +1,181 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { APP_MODEL_INPUT_SHAPES, APP_MODEL_QUANTITY_KINDS, APP_MODEL_RANGE_DISTRIBUTIONS, AppItemError, } from "@haakco/custd-sdk/browser";
3
+ import { useEffect, useId, useRef, useState } from "react";
4
+ import { formatModelValue, parseModelValue, rangeDistributionOf } from "./model-shorthand.js";
5
+ import { SafeMarkdown } from "./safe-markdown.js";
6
+ const DEFAULT_LABELS = {
7
+ title: "Quantities",
8
+ name: "Name",
9
+ value: "Value",
10
+ valueHint: "A number, 5 to 10 (90% range), 1 of 5, pasted numbers, or =formula.",
11
+ unit: "Unit",
12
+ description: "Description (Markdown)",
13
+ rangeShape: "Range shape",
14
+ distributions: { normal: "Normal", lognormal: "Lognormal", uniform: "Uniform" },
15
+ bound: (source) => `Live from ${source}`,
16
+ add: "Add quantity",
17
+ remove: (name) => `Remove ${name || "quantity"}`,
18
+ note: "Version note",
19
+ save: "Save version",
20
+ saving: "Saving…",
21
+ saved: "Saved.",
22
+ nameInvalid: "Start with a letter or _, then letters, digits or _.",
23
+ nameTaken: "Another quantity has this name.",
24
+ saveFailed: "The version was not saved.",
25
+ };
26
+ const NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
27
+ /**
28
+ * Edits a model's quantities in one list: name, value shorthand, unit and a Markdown description
29
+ * shown back safely. Saving sends the whole list as a new version; the server's validation
30
+ * message is shown on the quantity it names, or above the save button.
31
+ */
32
+ export function ModelEditor({ quantities, onSave, labels: overrides, className, style }) {
33
+ const labels = { ...DEFAULT_LABELS, ...overrides };
34
+ const nextId = useRef(quantities.length);
35
+ const [rows, setRows] = useState(() => quantities.map(rowOf));
36
+ const [note, setNote] = useState("");
37
+ const [errors, setErrors] = useState({});
38
+ const [status, setStatus] = useState({ state: "idle" });
39
+ const formId = useId();
40
+ const addButton = useRef(null);
41
+ // Where focus goes after adding or removing a row: a row's name field, or the Add button.
42
+ const [focusTarget, setFocusTarget] = useState();
43
+ useEffect(() => {
44
+ if (focusTarget === undefined)
45
+ return;
46
+ const target = focusTarget === "add" ? addButton.current : document.getElementById(`${formId}-${focusTarget}-name`);
47
+ target?.focus();
48
+ setFocusTarget(undefined);
49
+ }, [focusTarget, formId]);
50
+ const remove = (id) => {
51
+ const at = rows.findIndex((row) => row.id === id);
52
+ const neighbour = rows[at + 1] ?? rows[at - 1];
53
+ setRows((current) => current.filter((row) => row.id !== id));
54
+ setFocusTarget(neighbour ? neighbour.id : "add");
55
+ };
56
+ const update = (id, change) => {
57
+ setRows((current) => current.map((row) => (row.id === id ? { ...row, ...change } : row)));
58
+ setErrors(({ [id]: _cleared, ...rest }) => rest);
59
+ };
60
+ const submit = async (event) => {
61
+ event.preventDefault();
62
+ const checked = checkRows(rows, labels);
63
+ setErrors(checked.errors);
64
+ if (!checked.quantities)
65
+ return;
66
+ setStatus({ state: "saving" });
67
+ try {
68
+ await onSave(note.trim() === "" ? { quantities: checked.quantities } : { quantities: checked.quantities, note });
69
+ setStatus({ state: "saved" });
70
+ }
71
+ catch (error) {
72
+ const placed = placeFieldErrors(error, rows);
73
+ if (placed)
74
+ setErrors(placed);
75
+ setStatus({ state: "failed", message: placed ? labels.saveFailed : problemMessage(error, labels.saveFailed) });
76
+ }
77
+ };
78
+ return (_jsxs("form", { className: className, style: style, onSubmit: submit, noValidate: true, "data-custd-model-editor": "", children: [_jsxs("fieldset", { children: [_jsx("legend", { children: labels.title }), _jsx("ol", { style: { listStyle: "none", padding: 0, margin: 0, display: "grid", gap: "0.75rem" }, children: rows.map((row, index) => (_jsx(QuantityRow, { row: row, idPrefix: `${formId}-${row.id}`, errors: errors[row.id] ?? {}, labels: labels, position: index, onChange: (change) => update(row.id, change), onRemove: () => remove(row.id) }, row.id))) }), _jsx("button", { ref: addButton, type: "button", onClick: () => {
79
+ nextId.current += 1;
80
+ setRows((current) => [...current, emptyRow(nextId.current)]);
81
+ setFocusTarget(nextId.current);
82
+ }, children: labels.add })] }), _jsx("label", { htmlFor: `${formId}-note`, children: labels.note }), _jsx("input", { id: `${formId}-note`, value: note, onChange: (event) => setNote(event.target.value) }), status.state === "failed" ? _jsx("p", { role: "alert", children: status.message }) : null, _jsx("button", { type: "submit", disabled: status.state === "saving" || rows.length === 0, children: status.state === "saving" ? labels.saving : labels.save }), _jsx("p", { "aria-live": "polite", children: status.state === "saved" ? labels.saved : "" })] }));
83
+ }
84
+ function QuantityRow({ row, idPrefix, errors, labels, position, onChange, onRemove }) {
85
+ const ids = {
86
+ name: `${idPrefix}-name`,
87
+ value: `${idPrefix}-value`,
88
+ hint: `${idPrefix}-hint`,
89
+ valueError: `${idPrefix}-value-error`,
90
+ nameError: `${idPrefix}-name-error`,
91
+ unit: `${idPrefix}-unit`,
92
+ shape: `${idPrefix}-shape`,
93
+ description: `${idPrefix}-description`,
94
+ };
95
+ const parsed = row.bound ? undefined : parseModelValue(row.value, row.distribution);
96
+ const isRange = parsed?.ok === true && parsed.value.kind === "input" && parsed.value.input.shape === "range";
97
+ return (_jsxs("li", { "data-custd-model-quantity": row.name || `#${position + 1}`, children: [_jsxs("div", { style: { display: "flex", flexWrap: "wrap", gap: "0.5rem", alignItems: "flex-start" }, children: [_jsxs("span", { style: { display: "grid" }, children: [_jsx("label", { htmlFor: ids.name, children: labels.name }), _jsx("input", { id: ids.name, value: row.name, spellCheck: false, "aria-invalid": errors.name ? true : undefined, "aria-describedby": errors.name ? ids.nameError : undefined, onChange: (event) => onChange({ name: event.target.value }) }), errors.name ? _jsx("span", { id: ids.nameError, children: errors.name }) : null] }), _jsxs("span", { style: { display: "grid", flex: "1 1 14rem" }, children: [_jsx("label", { htmlFor: ids.value, children: labels.value }), row.bound?.shape === APP_MODEL_INPUT_SHAPES.bound ? (_jsx("output", { id: ids.value, children: labels.bound(row.bound.source.field.replace(/_/g, " ")) })) : (_jsx("input", { id: ids.value, value: row.value, spellCheck: false, "aria-invalid": errors.value ? true : undefined, "aria-describedby": errors.value ? `${ids.valueError} ${ids.hint}` : ids.hint, onChange: (event) => onChange({ value: event.target.value }), onPaste: (event) => pasteSamples(event, (value) => onChange({ value })) })), _jsx("span", { id: ids.hint, style: { fontSize: "0.85em", opacity: 0.75 }, children: row.bound ? "" : labels.valueHint }), errors.value ? _jsx("span", { id: ids.valueError, children: errors.value }) : null] }), _jsxs("span", { style: { display: "grid" }, children: [_jsx("label", { htmlFor: ids.shape, children: labels.rangeShape }), _jsx("select", { id: ids.shape, value: row.distribution, disabled: !isRange, onChange: (event) => onChange({ distribution: event.target.value }), children: Object.values(APP_MODEL_RANGE_DISTRIBUTIONS).map((shape) => (_jsx("option", { value: shape, children: labels.distributions[shape] }, shape))) })] }), _jsxs("span", { style: { display: "grid" }, children: [_jsx("label", { htmlFor: ids.unit, children: labels.unit }), _jsx("input", { id: ids.unit, value: row.unit, onChange: (event) => onChange({ unit: event.target.value }) })] }), _jsx("button", { type: "button", onClick: onRemove, style: { alignSelf: "end" }, children: labels.remove(row.name) })] }), _jsx("label", { htmlFor: ids.description, children: labels.description }), _jsx("textarea", { id: ids.description, value: row.description, rows: 2, onChange: (event) => onChange({ description: event.target.value }) }), row.description.trim() !== "" ? _jsx(SafeMarkdown, { source: row.description }) : null] }));
98
+ }
99
+ /** A pasted spreadsheet column is one number per line; a one-line field keeps them apart as `a, b`. */
100
+ function pasteSamples(event, setValue) {
101
+ const pasted = event.clipboardData.getData("text");
102
+ if (!/[\r\n]/.test(pasted))
103
+ return;
104
+ event.preventDefault();
105
+ const field = event.currentTarget;
106
+ const joined = pasted
107
+ .split(/[\r\n]+/)
108
+ .map((line) => line.trim())
109
+ .filter((line) => line !== "")
110
+ .join(", ");
111
+ const start = field.selectionStart ?? field.value.length;
112
+ const end = field.selectionEnd ?? field.value.length;
113
+ setValue(`${field.value.slice(0, start)}${joined}${field.value.slice(end)}`);
114
+ }
115
+ function rowOf(quantity, index) {
116
+ const bound = quantity.kind === APP_MODEL_QUANTITY_KINDS.input && quantity.input.shape === APP_MODEL_INPUT_SHAPES.bound
117
+ ? quantity.input
118
+ : undefined;
119
+ return {
120
+ id: index,
121
+ name: quantity.name,
122
+ unit: quantity.unit ?? "",
123
+ description: quantity.description ?? "",
124
+ value: formatModelValue(quantity),
125
+ distribution: rangeDistributionOf(quantity),
126
+ bound,
127
+ };
128
+ }
129
+ function emptyRow(id) {
130
+ return { id, name: "", unit: "", description: "", value: "", distribution: APP_MODEL_RANGE_DISTRIBUTIONS.normal };
131
+ }
132
+ function checkRows(rows, labels) {
133
+ const errors = {};
134
+ const seen = new Set();
135
+ const quantities = [];
136
+ for (const row of rows) {
137
+ const rowErrors = {};
138
+ if (!NAME.test(row.name))
139
+ rowErrors.name = labels.nameInvalid;
140
+ else if (seen.has(row.name))
141
+ rowErrors.name = labels.nameTaken;
142
+ seen.add(row.name);
143
+ const base = { name: row.name, ...optional("unit", row.unit), ...optional("description", row.description) };
144
+ if (row.bound) {
145
+ quantities.push({ ...base, kind: APP_MODEL_QUANTITY_KINDS.input, input: row.bound });
146
+ }
147
+ else {
148
+ const parsed = parseModelValue(row.value, row.distribution);
149
+ if (parsed.ok)
150
+ quantities.push({ ...base, ...parsed.value });
151
+ else
152
+ rowErrors.value = parsed.message;
153
+ }
154
+ if (rowErrors.name || rowErrors.value)
155
+ errors[row.id] = rowErrors;
156
+ }
157
+ return Object.keys(errors).length > 0 ? { errors } : { errors, quantities };
158
+ }
159
+ function optional(key, value) {
160
+ return value.trim() === "" ? {} : { [key]: value };
161
+ }
162
+ /**
163
+ * Puts the server's field errors on the rows they name: `subject` is the quantity name, so a cycle
164
+ * marks every quantity in it. Undefined when none names a row on screen.
165
+ */
166
+ function placeFieldErrors(error, rows) {
167
+ const fieldErrors = error instanceof AppItemError ? (error.problem?.fieldErrors ?? []) : [];
168
+ const placed = {};
169
+ for (const fieldError of fieldErrors) {
170
+ const row = rows.find((candidate) => candidate.name === fieldError.subject);
171
+ if (!row)
172
+ continue;
173
+ const slot = fieldError.field === "name" ? "name" : "value";
174
+ placed[row.id] = { ...placed[row.id], [slot]: fieldError.message };
175
+ }
176
+ return Object.keys(placed).length > 0 ? placed : undefined;
177
+ }
178
+ function problemMessage(error, fallback) {
179
+ const detail = error instanceof AppItemError ? error.problem?.detail : undefined;
180
+ return detail ? detail.replace(/^uncertainty model: invalid:\s*/, "") : fallback;
181
+ }
@@ -0,0 +1,28 @@
1
+ import { APP_MODEL_QUANTITY_KINDS, type AppModelInput, type AppModelQuantity, type AppModelRangeDistribution } from "@haakco/custd-sdk/browser";
2
+ /** What a value cell holds once read: an input or a formula (without its `=`). */
3
+ export type ModelValue = {
4
+ kind: typeof APP_MODEL_QUANTITY_KINDS.input;
5
+ input: AppModelInput;
6
+ } | {
7
+ kind: typeof APP_MODEL_QUANTITY_KINDS.formula;
8
+ formula: string;
9
+ };
10
+ export type ModelValueParse = {
11
+ ok: true;
12
+ value: ModelValue;
13
+ } | {
14
+ ok: false;
15
+ message: string;
16
+ };
17
+ /**
18
+ * Reads the value shorthand: `=a * b` is a formula, `5 to 10` a 90% range shaped by `distribution`,
19
+ * `1 of 5` a proportion, several numbers pasted data, and one number a point. The server checks
20
+ * the result again; this only gives the editor an early, local message.
21
+ */
22
+ export declare function parseModelValue(text: string, distribution?: AppModelRangeDistribution): ModelValueParse;
23
+ /** Writes a stored quantity back as shorthand. A bound input has none: it is shown, not typed. */
24
+ export declare function formatModelValue(quantity: AppModelQuantity): string;
25
+ /** The range shape a stored quantity uses, or the default for a new one. */
26
+ export declare function rangeDistributionOf(quantity: AppModelQuantity | undefined): AppModelRangeDistribution;
27
+ /** Shows a number compactly for labels and tables. */
28
+ export declare function formatModelNumber(value: number): string;
@@ -0,0 +1,85 @@
1
+ import { APP_MODEL_INPUT_SHAPES, APP_MODEL_QUANTITY_KINDS, APP_MODEL_RANGE_DISTRIBUTIONS, } from "@haakco/custd-sdk/browser";
2
+ const NUMBER = String.raw `[-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?`;
3
+ const POINT = new RegExp(`^${NUMBER}$`, "i");
4
+ const RANGE = new RegExp(`^(${NUMBER})\\s*(?:to|\\.\\.|–|—)\\s*(${NUMBER})$`, "i");
5
+ const PROPORTION = /^(\d+)\s*(?:of|\/)\s*(\d+)$/i;
6
+ const SAMPLE_SEPARATOR = /[\s,;]+/;
7
+ /**
8
+ * Reads the value shorthand: `=a * b` is a formula, `5 to 10` a 90% range shaped by `distribution`,
9
+ * `1 of 5` a proportion, several numbers pasted data, and one number a point. The server checks
10
+ * the result again; this only gives the editor an early, local message.
11
+ */
12
+ export function parseModelValue(text, distribution = APP_MODEL_RANGE_DISTRIBUTIONS.normal) {
13
+ const value = text.trim();
14
+ if (value.startsWith("=")) {
15
+ const formula = value.slice(1).trim();
16
+ if (formula === "")
17
+ return { ok: false, message: "Write a formula after =." };
18
+ return { ok: true, value: { kind: APP_MODEL_QUANTITY_KINDS.formula, formula } };
19
+ }
20
+ if (value === "")
21
+ return { ok: false, message: "Enter a value, a range like 5 to 10, k of n or =formula." };
22
+ if (POINT.test(value))
23
+ return input({ shape: APP_MODEL_INPUT_SHAPES.point, value: Number(value) });
24
+ const range = RANGE.exec(value);
25
+ if (range)
26
+ return parseRange(Number(range[1]), Number(range[2]), distribution);
27
+ const proportion = PROPORTION.exec(value);
28
+ if (proportion)
29
+ return parseProportion(Number(proportion[1]), Number(proportion[2]));
30
+ const samples = value.split(SAMPLE_SEPARATOR).filter((part) => part !== "");
31
+ if (samples.length >= 2 && samples.every((part) => POINT.test(part))) {
32
+ return input({ shape: APP_MODEL_INPUT_SHAPES.samples, samples: samples.map(Number) });
33
+ }
34
+ return { ok: false, message: "Use a number, a range like 5 to 10, k of n, pasted numbers or =formula." };
35
+ }
36
+ function parseRange(low, high, distribution) {
37
+ if (!(low < high))
38
+ return { ok: false, message: "The low end of a range must be below the high end." };
39
+ if (distribution === APP_MODEL_RANGE_DISTRIBUTIONS.lognormal && low <= 0) {
40
+ return { ok: false, message: "A lognormal range needs a low end above 0." };
41
+ }
42
+ return input({ shape: APP_MODEL_INPUT_SHAPES.range, low, high, distribution });
43
+ }
44
+ function parseProportion(successes, trials) {
45
+ if (trials < 1 || successes > trials)
46
+ return { ok: false, message: "k of n needs n at least 1 and k at most n." };
47
+ return input({ shape: APP_MODEL_INPUT_SHAPES.proportion, successes, trials });
48
+ }
49
+ function input(value) {
50
+ return { ok: true, value: { kind: APP_MODEL_QUANTITY_KINDS.input, input: value } };
51
+ }
52
+ /** Writes a stored quantity back as shorthand. A bound input has none: it is shown, not typed. */
53
+ export function formatModelValue(quantity) {
54
+ if (quantity.kind === APP_MODEL_QUANTITY_KINDS.formula)
55
+ return `=${quantity.formula}`;
56
+ const value = quantity.input;
57
+ switch (value.shape) {
58
+ case APP_MODEL_INPUT_SHAPES.point:
59
+ return String(value.value);
60
+ case APP_MODEL_INPUT_SHAPES.range:
61
+ return `${value.low} to ${value.high}`;
62
+ case APP_MODEL_INPUT_SHAPES.proportion:
63
+ return `${value.successes} of ${value.trials}`;
64
+ case APP_MODEL_INPUT_SHAPES.samples:
65
+ return value.samples.join(", ");
66
+ case APP_MODEL_INPUT_SHAPES.bound:
67
+ return "";
68
+ }
69
+ }
70
+ /** The range shape a stored quantity uses, or the default for a new one. */
71
+ export function rangeDistributionOf(quantity) {
72
+ if (quantity?.kind === APP_MODEL_QUANTITY_KINDS.input && quantity.input.shape === APP_MODEL_INPUT_SHAPES.range) {
73
+ return quantity.input.distribution;
74
+ }
75
+ return APP_MODEL_RANGE_DISTRIBUTIONS.normal;
76
+ }
77
+ /** Shows a number compactly for labels and tables. */
78
+ export function formatModelNumber(value) {
79
+ if (!Number.isFinite(value))
80
+ return String(value);
81
+ const magnitude = Math.abs(value);
82
+ if (magnitude !== 0 && (magnitude >= 1e6 || magnitude < 1e-3))
83
+ return value.toExponential(2);
84
+ return value.toLocaleString("en-US", { maximumSignificantDigits: 4 });
85
+ }
@@ -0,0 +1,23 @@
1
+ import type { AppModelQuantityResult } from "@haakco/custd-sdk/browser";
2
+ import type { CSSProperties } from "react";
3
+ export type QuantityHistogramLabels = {
4
+ empty: string;
5
+ failed: (detail: string) => string;
6
+ summary: (mean: string, low: string, high: string) => string;
7
+ bin: (low: string, high: string, count: number) => string;
8
+ mean: string;
9
+ interval: string;
10
+ };
11
+ export type QuantityHistogramProps = {
12
+ result: AppModelQuantityResult;
13
+ title: string;
14
+ unit?: string;
15
+ formatValue?: (value: number) => string;
16
+ labels?: Partial<QuantityHistogramLabels>;
17
+ width?: number;
18
+ height?: number;
19
+ className?: string;
20
+ style?: CSSProperties;
21
+ };
22
+ /** One quantity's samples as bars, with its mean and its 5th–95th percentile interval marked. */
23
+ export declare function QuantityHistogram({ result, title, unit, formatValue, labels: overrides, width, height, className, style, }: QuantityHistogramProps): import("react").JSX.Element;
@@ -0,0 +1,53 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { scaleLinear } from "./chart-scale.js";
3
+ import { formatModelNumber } from "./model-shorthand.js";
4
+ const DEFAULT_LABELS = {
5
+ empty: "No samples to show.",
6
+ failed: (detail) => `Not calculated: ${detail}`,
7
+ summary: (mean, low, high) => `Mean ${mean}; 90% of samples between ${low} and ${high}.`,
8
+ bin: (low, high, count) => `${low} to ${high}: ${count} samples`,
9
+ mean: "Mean",
10
+ interval: "90% interval",
11
+ };
12
+ /** The server sends 20 bins; anything past this is not drawn, so a bad payload stays cheap. */
13
+ const MAX_BINS = 100;
14
+ const MARGIN = { top: 8, right: 8, bottom: 34, left: 8 };
15
+ const COLOR = {
16
+ bar: "var(--custd-chart-forecast, currentColor)",
17
+ interval: "var(--custd-chart-band, currentColor)",
18
+ mean: "var(--custd-chart-target, currentColor)",
19
+ median: "var(--custd-chart-observed, currentColor)",
20
+ };
21
+ /** One quantity's samples as bars, with its mean and its 5th–95th percentile interval marked. */
22
+ export function QuantityHistogram({ result, title, unit, formatValue = formatModelNumber, labels: overrides, width = 480, height = 140, className, style, }) {
23
+ const labels = { ...DEFAULT_LABELS, ...overrides };
24
+ const withUnit = (value) => (unit ? `${formatValue(value)} ${unit}` : formatValue(value));
25
+ if (result.error) {
26
+ return (_jsx("div", { className: className, style: style, "data-custd-chart": "quantity-histogram", "data-custd-chart-state": "failed", children: _jsx("p", { children: labels.failed(result.error.detail) }) }));
27
+ }
28
+ const summary = result.summary;
29
+ const counts = (summary?.histogram.counts ?? []).slice(0, MAX_BINS);
30
+ const total = counts.reduce((sum, count) => sum + count, 0);
31
+ if (!summary || total === 0) {
32
+ return (_jsx("div", { className: className, style: style, "data-custd-chart": "quantity-histogram", "data-custd-chart-state": "empty", children: _jsx("p", { children: labels.empty }) }));
33
+ }
34
+ const { min, max } = summary.histogram;
35
+ const { p5, p50, p95 } = summary.percentiles;
36
+ // Every sample the same value gives zero-width bins: draw one centred bar.
37
+ const single = !(max > min);
38
+ const domain = single ? { start: min - 1, end: min + 1 } : { start: min, end: max };
39
+ const binWidth = (max - min) / (summary.histogram.counts?.length ?? counts.length);
40
+ const bins = single
41
+ ? [{ low: min, high: min, count: total }]
42
+ : counts.map((count, index) => ({ low: min + binWidth * index, high: min + binWidth * (index + 1), count }));
43
+ const px = scaleLinear(domain, MARGIN.left, width - MARGIN.right);
44
+ const baseline = height - MARGIN.bottom;
45
+ const py = scaleLinear({ start: 0, end: Math.max(...bins.map((bin) => bin.count)) }, baseline, MARGIN.top);
46
+ const text = { fill: "currentColor", fontSize: 11, fontVariantNumeric: "tabular-nums" };
47
+ const described = labels.summary(withUnit(summary.mean), withUnit(p5), withUnit(p95));
48
+ const clamp = (value) => Math.min(width - MARGIN.right, Math.max(MARGIN.left, px(value)));
49
+ return (_jsxs("figure", { className: className, style: { margin: 0, ...style }, "data-custd-chart": "quantity-histogram", children: [_jsxs("svg", { role: "img", "aria-label": `${title}: ${described}`, viewBox: `0 0 ${width} ${height}`, width: "100%", style: { display: "block" }, children: [_jsx("title", { children: title }), bins.map(({ low, high, count }) => {
50
+ const left = single ? px(min) - 3 : px(low) + 0.5;
51
+ return (_jsx("rect", { "data-custd-chart-bar": "", x: left, y: py(count), width: single ? 6 : Math.max(0, px(high) - px(low) - 1), height: baseline - py(count), style: { fill: COLOR.bar, fillOpacity: 0.75 }, children: _jsx("title", { children: labels.bin(withUnit(low), withUnit(high), count) }) }, low));
52
+ }), _jsxs("g", { "data-custd-chart-layer": "interval", children: [_jsx("title", { children: `${labels.interval}: ${withUnit(p5)} to ${withUnit(p95)}` }), _jsx("rect", { x: clamp(p5), y: baseline + 6, width: Math.max(2, clamp(p95) - clamp(p5)), height: 5, rx: 2.5, style: { fill: COLOR.interval, fillOpacity: 0.6 } }), _jsx("circle", { cx: clamp(p50), cy: baseline + 8.5, r: 3.5, style: { fill: COLOR.median } })] }), _jsx("line", { "data-custd-chart-layer": "mean", x1: clamp(summary.mean), x2: clamp(summary.mean), y1: MARGIN.top, y2: baseline, style: { stroke: COLOR.mean, strokeWidth: 1.5, strokeDasharray: "4 3" }, children: _jsx("title", { children: `${labels.mean}: ${withUnit(summary.mean)}` }) }), _jsx("text", { x: MARGIN.left, y: height - 4, style: text, children: withUnit(domain.start) }), _jsx("text", { x: width - MARGIN.right, y: height - 4, textAnchor: "end", style: text, children: withUnit(domain.end) })] }), _jsx("figcaption", { children: described })] }));
53
+ }
@@ -0,0 +1,10 @@
1
+ export type SafeMarkdownProps = {
2
+ source: string;
3
+ className?: string;
4
+ };
5
+ /**
6
+ * A small Markdown subset (paragraphs, `-` lists, `code`, **bold**, *italic* and http, https or
7
+ * mailto links) built as React elements. Text is never parsed as HTML, so markup in a
8
+ * description is shown as written.
9
+ */
10
+ export declare function SafeMarkdown({ source, className }: SafeMarkdownProps): import("react").JSX.Element;