@vitavision/ui 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitavision/ui",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "The vitavision instrument design system: Tailwind v4 tokens, theme, and React primitives.",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "repository": {
@@ -28,6 +28,7 @@
28
28
  "import": "./dist/index.js"
29
29
  },
30
30
  "./styles.css": "./src/styles.css",
31
+ "./fonts.css": "./src/fonts/fonts.css",
31
32
  "./package.json": "./package.json"
32
33
  },
33
34
  "publishConfig": {
@@ -5,7 +5,7 @@
5
5
  * can still pick up the shared palette and focus treatment.
6
6
  */
7
7
 
8
- import type { ComponentProps } from "react";
8
+ import { useId, type ComponentProps } from "react";
9
9
 
10
10
  import { byDensity, useDensity } from "./Density";
11
11
  import { useFieldDescription } from "./Field";
@@ -54,22 +54,46 @@ export function Input({ className, "aria-describedby": describedBy, ...rest }: C
54
54
  );
55
55
  }
56
56
 
57
+ /** Props of `NumberInput`: every `<input>` prop, `ref` included, with numeric bounds and a `unit`. */
58
+ export type NumberInputProps = Omit<ComponentProps<"input">, "min" | "max"> & {
59
+ /** The smallest accepted value. */
60
+ min?: number | undefined;
61
+ /** The largest accepted value. */
62
+ max?: number | undefined;
63
+ /**
64
+ * The quantity's unit (`mm`, `m`, `°`, `px`), written inside the field after the number, in
65
+ * mono and muted. It is not part of the value. It is announced as the field's description
66
+ * (`aria-describedby`): after the caller's own `aria-describedby`, before a surrounding
67
+ * `Field`'s description and error.
68
+ */
69
+ unit?: string | undefined;
70
+ };
71
+
57
72
  /**
58
- * A number, with the schema's own bounds attached.
73
+ * A number, with the schema's own bounds attached and, optionally, its unit written in the
74
+ * field.
59
75
  *
60
76
  * `font-mono` because these are read as quantities and compared down a column. Takes every
61
- * `<input>` prop, `ref` included (`type` is always `number`).
77
+ * `<input>` prop, `ref` included (`type` is always `number`); `className`, `style` and `ref`
78
+ * always go to the `<input>`.
79
+ *
80
+ * With a `unit`, the input sits in a `relative` full-width wrapper carrying `data-unit`, keeps
81
+ * room on its right for the unit, and is described by it; size such a field through its
82
+ * container. Without one — or with `""` — the markup is exactly the plain input.
62
83
  */
63
- export function NumberInput({
84
+ export function NumberInput({ unit, ...props }: NumberInputProps) {
85
+ return unit === undefined || unit === "" ? (
86
+ <PlainNumberInput {...props} />
87
+ ) : (
88
+ <UnitNumberInput unit={unit} {...props} />
89
+ );
90
+ }
91
+
92
+ function PlainNumberInput({
64
93
  className,
65
94
  "aria-describedby": describedBy,
66
95
  ...rest
67
- }: Omit<ComponentProps<"input">, "min" | "max"> & {
68
- /** The smallest accepted value. */
69
- min?: number | undefined;
70
- /** The largest accepted value. */
71
- max?: number | undefined;
72
- }) {
96
+ }: Omit<NumberInputProps, "unit">) {
73
97
  return (
74
98
  <input
75
99
  {...useFieldDescription(describedBy)}
@@ -81,6 +105,39 @@ export function NumberInput({
81
105
  );
82
106
  }
83
107
 
108
+ /*
109
+ * A component of its own so that only a field with a unit calls `useId`: a plain
110
+ * `NumberInput` stays byte-identical to the one before `unit` existed, down to the ids React
111
+ * hands the elements rendered after it.
112
+ */
113
+ function UnitNumberInput({
114
+ unit,
115
+ style,
116
+ "aria-describedby": describedBy,
117
+ ...rest
118
+ }: Omit<NumberInputProps, "unit"> & { unit: string }) {
119
+ const unitId = useId();
120
+ return (
121
+ <span data-unit={unit} className="relative flex w-full min-w-0 items-center">
122
+ <PlainNumberInput
123
+ {...rest}
124
+ aria-describedby={describedBy ? `${describedBy} ${unitId}` : unitId}
125
+ // Room for the unit: its width in the unit's own characters, plus the field's padding.
126
+ style={{ paddingInlineEnd: `calc(${unit.length}ch + 1rem)`, ...style }}
127
+ />
128
+ {/* `aria-hidden` keeps the unit out of the field's *name* when a `<label>` wraps it;
129
+ `aria-describedby` still reads it, as the description. */}
130
+ <span
131
+ id={unitId}
132
+ aria-hidden
133
+ className="pointer-events-none absolute inset-y-0 right-2.5 flex items-center font-mono text-xs text-fg-subtle select-none"
134
+ >
135
+ {unit}
136
+ </span>
137
+ </span>
138
+ );
139
+ }
140
+
84
141
  /**
85
142
  * Multi-line text — set in mono, for JSON and lists. Takes every `<textarea>` prop, `ref`
86
143
  * included.
@@ -0,0 +1,181 @@
1
+ /*
2
+ * A rigid transform, edited the way people think about one.
3
+ *
4
+ * Poses travel as `{ rotation: [qx, qy, qz, qw], translation: [tx, ty, tz] }` — the SE(3) wire
5
+ * form — because a quaternion is the honest representation. Nobody edits one by hand,
6
+ * though: a rotation is read and typed as roll, pitch and yaw in degrees. This component
7
+ * shows that view and writes back the wire form.
8
+ *
9
+ * It owns no rotation mathematics. Which Euler convention "roll, pitch, yaw" means — the
10
+ * axis order, intrinsic or extrinsic — is a decision of the 3D package that defines the
11
+ * frames, so the conversion is passed in as a `RotationView`. This package stays pure UI.
12
+ */
13
+
14
+ import { useState } from "react";
15
+
16
+ import { byDensity, useDensity } from "./Density";
17
+ import { ReadoutStrip } from "./Panel";
18
+ import { cn } from "./cn";
19
+ import { formatNumber } from "./numberText";
20
+ import { VectorInput } from "./VectorInput";
21
+
22
+ /** Three numbers: a translation `[tx, ty, tz]`, or Euler angles. */
23
+ export type Vec3 = readonly [number, number, number];
24
+
25
+ /** A unit quaternion in the wire order `[qx, qy, qz, qw]` (scalar last). */
26
+ export type Quaternion = readonly [number, number, number, number];
27
+
28
+ /**
29
+ * An SE(3) pose in the wire form (`a_se3_b` as nalgebra's `Isometry3` serialises it):
30
+ * translation in metres, rotation as a unit quaternion `[qx, qy, qz, qw]`.
31
+ */
32
+ export interface PoseValue {
33
+ /** The rotation, `[qx, qy, qz, qw]`. */
34
+ rotation: Quaternion;
35
+ /** The translation `[tx, ty, tz]`, in metres. */
36
+ translation: Vec3;
37
+ }
38
+
39
+ /**
40
+ * How a rotation is shown as three angles: the conversion both ways, and the angles' names.
41
+ * Supplied by the package that owns the frame conventions; `PoseInput` only calls it.
42
+ */
43
+ export interface RotationView {
44
+ /** The quaternion as three angles, in radians, in the order of `labels`. */
45
+ toEuler: (rotation: Quaternion) => Vec3;
46
+ /** Three angles in radians, in the order of `labels`, as a unit quaternion `[qx, qy, qz, qw]`. */
47
+ fromEuler: (angles: Vec3) => Quaternion;
48
+ /** The angles' names, shown before each field. Defaults to roll, pitch, yaw. */
49
+ labels?: readonly [string, string, string] | undefined;
50
+ }
51
+
52
+ /** Props of `PoseInput`. */
53
+ export interface PoseInputProps {
54
+ /** The pose, in the wire form. */
55
+ value: PoseValue;
56
+ /** Called with a new pose (new arrays) whenever a component changes. */
57
+ onValueChange?: ((value: PoseValue) => void) | undefined;
58
+ /** The quaternion ↔ angles conversion and the angles' names. Required: see `RotationView`. */
59
+ rotationView: RotationView;
60
+ /** Show and edit the translation in metres (the default) or millimetres. The value is always metres. */
61
+ translationUnit?: "m" | "mm" | undefined;
62
+ /** Decimals of the translation. Defaults to 4 for m, 1 for mm. */
63
+ translationPrecision?: number | undefined;
64
+ /** Decimals of the angles, in degrees. Defaults to 2. */
65
+ rotationPrecision?: number | undefined;
66
+ /** Show a compact mono readout instead of fields. */
67
+ readOnly?: boolean | undefined;
68
+ /** Blocks every field. */
69
+ disabled?: boolean | undefined;
70
+ /** Names the pose (`role="group"`). Defaults to "Pose". */
71
+ "aria-label"?: string | undefined;
72
+ /** Merged with the component's own classes through `cn`. */
73
+ className?: string | undefined;
74
+ }
75
+
76
+ const DEGREES = 180 / Math.PI;
77
+ const DEFAULT_ANGLE_LABELS = ["roll", "pitch", "yaw"] as const;
78
+
79
+ const sameQuaternion = (a: Quaternion, b: Quaternion) => a.every((component, index) => component === b[index]);
80
+
81
+ /**
82
+ * An SE(3) pose shown and edited as a translation (m or mm) and three angles in degrees,
83
+ * reading and writing the wire form `{ rotation: [qx, qy, qz, qw], translation: [tx, ty, tz] }`.
84
+ *
85
+ * The angles come from `rotationView.toEuler` and go back through `rotationView.fromEuler`.
86
+ * The angles as typed are kept while the pose they produced is the one shown, so a yaw of
87
+ * 190° is not redisplayed as −170° and a gimbal-locked pitch does not scramble the other two
88
+ * angles mid-edit.
89
+ *
90
+ * A `role="group"` named by `aria-label`, holding two `VectorInput` groups ("Translation",
91
+ * "Rotation"). With `readOnly` it renders a `ReadoutStrip` instead
92
+ * (`t 0.1000 0.2000 0.3000 m · rpy 0.00 90.00 0.00 °`). The root carries `data-readonly`.
93
+ */
94
+ export function PoseInput({
95
+ value,
96
+ onValueChange,
97
+ rotationView,
98
+ translationUnit = "m",
99
+ translationPrecision,
100
+ rotationPrecision = 2,
101
+ readOnly = false,
102
+ disabled = false,
103
+ "aria-label": ariaLabel = "Pose",
104
+ className,
105
+ }: PoseInputProps) {
106
+ const density = useDensity();
107
+ // The angles last typed, and the quaternion they became.
108
+ const [typed, setTyped] = useState<{ rotation: Quaternion; angles: Vec3 } | null>(null);
109
+
110
+ const scale = translationUnit === "mm" ? 1000 : 1;
111
+ const tPrecision = translationPrecision ?? (translationUnit === "mm" ? 1 : 4);
112
+ const translation = value.translation.map((component) => component * scale);
113
+ const radians =
114
+ typed !== null && sameQuaternion(typed.rotation, value.rotation) ? typed.angles : rotationView.toEuler(value.rotation);
115
+ const degrees = radians.map((angle) => angle * DEGREES);
116
+ const angleLabels = rotationView.labels ?? DEFAULT_ANGLE_LABELS;
117
+
118
+ if (readOnly) {
119
+ const join = (values: readonly number[], precision: number) =>
120
+ values.map((component) => formatNumber(component, precision)).join(" ");
121
+ return (
122
+ <div role="group" aria-label={ariaLabel} data-readonly="" className={cn("min-w-0", className)}>
123
+ <ReadoutStrip
124
+ items={[
125
+ { label: "t", value: `${join(translation, tPrecision)} ${translationUnit}` },
126
+ { label: "rpy", value: `${join(degrees, rotationPrecision)} °` },
127
+ ]}
128
+ />
129
+ </div>
130
+ );
131
+ }
132
+
133
+ const onTranslation = (next: number[]) => {
134
+ const [x = 0, y = 0, z = 0] = next.map((component) => component / scale);
135
+ onValueChange?.({ rotation: value.rotation, translation: [x, y, z] });
136
+ };
137
+
138
+ const onRotation = (next: number[]) => {
139
+ const [a = 0, b = 0, c = 0] = next.map((angle) => angle / DEGREES);
140
+ const angles: Vec3 = [a, b, c];
141
+ const rotation = rotationView.fromEuler(angles);
142
+ setTyped({ rotation, angles });
143
+ onValueChange?.({ rotation, translation: value.translation });
144
+ };
145
+
146
+ const rowLabel = cn("text-fg-muted", byDensity(density, "text-xs", "text-[11px]"));
147
+
148
+ return (
149
+ <div
150
+ role="group"
151
+ aria-label={ariaLabel}
152
+ className={cn("grid min-w-0 grid-cols-[auto_minmax(0,1fr)] items-center gap-x-2", byDensity(density, "gap-y-2", "gap-y-1"), className)}
153
+ >
154
+ <span aria-hidden className={rowLabel}>
155
+ Translation
156
+ </span>
157
+ <VectorInput
158
+ aria-label="Translation"
159
+ value={translation}
160
+ onValueChange={onTranslation}
161
+ unit={translationUnit}
162
+ precision={tPrecision}
163
+ step={translationUnit === "mm" ? 1 : 0.001}
164
+ disabled={disabled}
165
+ />
166
+ <span aria-hidden className={rowLabel}>
167
+ Rotation
168
+ </span>
169
+ <VectorInput
170
+ aria-label="Rotation"
171
+ value={degrees}
172
+ onValueChange={onRotation}
173
+ labels={angleLabels}
174
+ unit="°"
175
+ precision={rotationPrecision}
176
+ step={1}
177
+ disabled={disabled}
178
+ />
179
+ </div>
180
+ );
181
+ }
@@ -16,6 +16,7 @@ import { Check, ChevronDown } from "lucide-react";
16
16
  import { useState } from "react";
17
17
 
18
18
  import { useFieldDescription } from "./Field";
19
+ import { useControlHeight } from "./Input";
19
20
  import { cn, focusRingInset } from "./cn";
20
21
 
21
22
  const UNSET_SENTINEL = "__unset__";
@@ -72,6 +73,8 @@ export function Select({
72
73
  }) {
73
74
  const [open, setOpen] = useState(false);
74
75
  const described = useFieldDescription(ownDescribedBy);
76
+ // The trigger is a control like any input: 32 px comfortable, 28 px compact.
77
+ const height = useControlHeight();
75
78
 
76
79
  return (
77
80
  <RadixSelect.Root
@@ -91,7 +94,8 @@ export function Select({
91
94
  // order. Focus returns to it on close all the same.
92
95
  tabIndex={open ? -1 : undefined}
93
96
  className={cn(
94
- "flex h-8 w-full items-center justify-between gap-2 rounded-control border border-line-strong bg-raised px-2.5 text-sm text-fg",
97
+ "flex w-full items-center justify-between gap-2 rounded-control border border-line-strong bg-raised px-2.5 text-sm text-fg",
98
+ height,
95
99
  "transition-colors hover:border-fg-subtle",
96
100
  "disabled:cursor-not-allowed disabled:opacity-50",
97
101
  "data-[placeholder]:text-fg-subtle",
@@ -0,0 +1,183 @@
1
+ /*
2
+ * A small vector — a position, a set of angles, a scale — edited as one row.
3
+ *
4
+ * Three separate `Field`s for x, y and z spend three labels and three rows on what a reader
5
+ * thinks of as one quantity. This is one row: a quiet axis letter before each number, the
6
+ * unit once at the end, and one name for the whole group.
7
+ *
8
+ * Each field keeps the text being typed while it has focus and shows the formatted value
9
+ * otherwise (see `numberText.ts`), so `precision` never fights the cursor. Every valid
10
+ * keystroke is reported, so whatever the vector drives follows the typing.
11
+ */
12
+
13
+ import { useId, useState } from "react";
14
+ import type { KeyboardEvent } from "react";
15
+
16
+ import { NumberInput } from "./Input";
17
+ import { ReadoutStrip } from "./Panel";
18
+ import { cn } from "./cn";
19
+ import { formatNumber, parseNumber } from "./numberText";
20
+
21
+ const DEFAULT_LABELS = ["x", "y", "z", "w"];
22
+
23
+ /** Props of `VectorInput`. */
24
+ export interface VectorInputProps {
25
+ /** The components. Its length is the number of fields. */
26
+ value: readonly number[];
27
+ /** Called with the whole vector (a new array) whenever one component changes to a valid number. */
28
+ onValueChange?: ((value: number[]) => void) | undefined;
29
+ /** Each component's label, shown before its field and naming it. Defaults to x, y, z, w. */
30
+ labels?: readonly string[] | undefined;
31
+ /** The unit of every component, shown once after the row (`m`, `mm`, `°`). */
32
+ unit?: string | undefined;
33
+ /** The arrow-key step. Defaults to `any` (the browser then steps by 1). */
34
+ step?: number | undefined;
35
+ /** Decimals shown when a field is not being edited. Defaults to 3. */
36
+ precision?: number | undefined;
37
+ /** The smallest accepted component. */
38
+ min?: number | undefined;
39
+ /** The largest accepted component. */
40
+ max?: number | undefined;
41
+ /** Show the values as a compact mono readout instead of fields. */
42
+ readOnly?: boolean | undefined;
43
+ /** Blocks every field. */
44
+ disabled?: boolean | undefined;
45
+ /** Names the group (`role="group"`). */
46
+ "aria-label": string;
47
+ /** Merged with the row's own classes through `cn`. */
48
+ className?: string | undefined;
49
+ }
50
+
51
+ /**
52
+ * A row of number fields editing one small vector, with the axis labels before the fields
53
+ * and the unit once after them.
54
+ *
55
+ * Controlled. A `role="group"` named by `aria-label`, each field named by its label and
56
+ * described by the unit. While a field has focus it shows what is typed; on blur or Enter it
57
+ * shows the value at `precision`; Escape restores the value it had on focus. With `readOnly`
58
+ * it renders a `ReadoutStrip` (`x 0.100 m · y …`) instead. The row carries `data-readonly`
59
+ * and `data-disabled`.
60
+ */
61
+ export function VectorInput({
62
+ value,
63
+ onValueChange,
64
+ labels = DEFAULT_LABELS,
65
+ unit,
66
+ step,
67
+ precision = 3,
68
+ min,
69
+ max,
70
+ readOnly = false,
71
+ disabled = false,
72
+ "aria-label": ariaLabel,
73
+ className,
74
+ }: VectorInputProps) {
75
+ const unitId = useId();
76
+ const labelOf = (index: number) => labels[index] ?? String(index);
77
+
78
+ if (readOnly) {
79
+ return (
80
+ <div role="group" aria-label={ariaLabel} data-readonly="" className={cn("min-w-0", className)}>
81
+ <ReadoutStrip
82
+ items={value.map((component, index) => ({
83
+ label: labelOf(index),
84
+ value: unit ? `${formatNumber(component, precision)} ${unit}` : formatNumber(component, precision),
85
+ }))}
86
+ />
87
+ </div>
88
+ );
89
+ }
90
+
91
+ const change = (index: number, component: number) => {
92
+ if (component === value[index]) return;
93
+ onValueChange?.(value.map((current, i) => (i === index ? component : current)));
94
+ };
95
+
96
+ return (
97
+ <div
98
+ role="group"
99
+ aria-label={ariaLabel}
100
+ data-disabled={disabled ? "" : undefined}
101
+ className={cn("flex min-w-0 items-center gap-1.5", className)}
102
+ >
103
+ {value.map((component, index) => (
104
+ // The components are positional: index is their identity.
105
+ // eslint-disable-next-line @eslint-react/no-array-index-key -- see above
106
+ <label key={index} className="flex min-w-0 flex-1 items-center gap-1">
107
+ <span className="shrink-0 font-mono text-[11px] text-fg-subtle">{labelOf(index)}</span>
108
+ <ComponentField
109
+ value={component}
110
+ precision={precision}
111
+ step={step}
112
+ min={min}
113
+ max={max}
114
+ disabled={disabled}
115
+ describedBy={unit ? unitId : undefined}
116
+ onCommit={(next) => change(index, next)}
117
+ />
118
+ </label>
119
+ ))}
120
+ {unit && (
121
+ <span id={unitId} className="shrink-0 font-mono text-xs text-fg-subtle">
122
+ {unit}
123
+ </span>
124
+ )}
125
+ </div>
126
+ );
127
+ }
128
+
129
+ /** One component: formatted at rest, the typed text while focused. */
130
+ function ComponentField({
131
+ value,
132
+ precision,
133
+ step,
134
+ min,
135
+ max,
136
+ disabled,
137
+ describedBy,
138
+ onCommit,
139
+ }: {
140
+ value: number;
141
+ precision: number;
142
+ step: number | undefined;
143
+ min: number | undefined;
144
+ max: number | undefined;
145
+ disabled: boolean;
146
+ describedBy: string | undefined;
147
+ onCommit: (value: number) => void;
148
+ }) {
149
+ // Non-null while the field is being edited: the text as typed, and the value on focus.
150
+ const [draft, setDraft] = useState<{ text: string; initial: number } | null>(null);
151
+ const formatted = formatNumber(value, precision);
152
+
153
+ const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
154
+ if (event.key === "Enter") {
155
+ setDraft((current) => current && { ...current, text: formatted });
156
+ } else if (event.key === "Escape" && draft) {
157
+ event.preventDefault();
158
+ onCommit(draft.initial);
159
+ setDraft({ ...draft, text: formatNumber(draft.initial, precision) });
160
+ }
161
+ };
162
+
163
+ return (
164
+ <NumberInput
165
+ value={draft?.text ?? formatted}
166
+ step={step ?? "any"}
167
+ min={min}
168
+ max={max}
169
+ disabled={disabled}
170
+ aria-describedby={describedBy}
171
+ onFocus={() => setDraft({ text: formatted, initial: value })}
172
+ onBlur={() => setDraft(null)}
173
+ onKeyDown={onKeyDown}
174
+ onChange={(event) => {
175
+ const text = event.currentTarget.value;
176
+ setDraft((current) => ({ text, initial: current?.initial ?? value }));
177
+ const parsed = parseNumber(text);
178
+ if (parsed !== null) onCommit(parsed);
179
+ }}
180
+ className="min-w-0 px-1.5"
181
+ />
182
+ );
183
+ }
@@ -29,6 +29,7 @@ export {
29
29
  controlClasses,
30
30
  inputClasses,
31
31
  useControlHeight,
32
+ type NumberInputProps,
32
33
  } from "./Input";
33
34
  export {
34
35
  PageHeader,
@@ -38,6 +39,14 @@ export {
38
39
  Section,
39
40
  type ReadoutItem,
40
41
  } from "./Panel";
42
+ export {
43
+ PoseInput,
44
+ type PoseInputProps,
45
+ type PoseValue,
46
+ type Quaternion,
47
+ type RotationView,
48
+ type Vec3,
49
+ } from "./PoseInput";
41
50
  export { SegmentedControl } from "./SegmentedControl";
42
51
  export { Select, type SelectOption } from "./Select";
43
52
  export { Slider } from "./Slider";
@@ -45,3 +54,4 @@ export { Table, type Column } from "./Table";
45
54
  export { Checkbox, Switch } from "./Toggle";
46
55
  export { ToggleChip } from "./ToggleChip";
47
56
  export { InfoHint, Tooltip, TooltipProvider } from "./Tooltip";
57
+ export { VectorInput, type VectorInputProps } from "./VectorInput";
@@ -0,0 +1,36 @@
1
+ /*
2
+ * Numbers as a field shows them and as a person types them. Internal to this package (used by
3
+ * `VectorInput` and `PoseInput`); not exported.
4
+ *
5
+ * A field bound straight to a number re-formats under the cursor: typing `0.` into a field
6
+ * showing `0.000` becomes `0` before the next digit arrives. So the multi-number fields keep
7
+ * the typed text while they have focus and show the formatted value otherwise; these are the
8
+ * two conversions between the two.
9
+ */
10
+
11
+ /**
12
+ * A number at a fixed number of decimals, without a negative zero (`-0.000` reads as a sign
13
+ * error in a coordinate readout).
14
+ *
15
+ * @param value - The number. Non-finite values print as `NaN`, `Infinity`, `-Infinity`.
16
+ * @param precision - Decimals, 0–20.
17
+ * @returns The text.
18
+ */
19
+ export function formatNumber(value: number, precision: number): string {
20
+ if (!Number.isFinite(value)) return String(value);
21
+ const text = value.toFixed(precision);
22
+ return /^-0(?:\.0*)?$/.test(text) ? text.slice(1) : text;
23
+ }
24
+
25
+ /**
26
+ * The number a field's text means, if it means one.
27
+ *
28
+ * @param text - What is in the field.
29
+ * @returns The number, or `null` for empty, partial (`-`, `1e`) or non-numeric text.
30
+ */
31
+ export function parseNumber(text: string): number | null {
32
+ const trimmed = text.trim();
33
+ if (trimmed === "") return null;
34
+ const value = Number(trimmed);
35
+ return Number.isFinite(value) ? value : null;
36
+ }