@olenbetong/appframe-ds 1.4.1 → 1.6.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.
@@ -0,0 +1,64 @@
1
+ import { type GridApi, gridFocusCellSelector } from "@mui/x-data-grid-premium";
2
+
3
+ import type React from "react";
4
+ import { useEffect } from "react";
5
+
6
+ /** How long after a row or cell changes mode a focus loss is still blamed on it. */
7
+ const EDIT_STOP_WINDOW_MS = 1000;
8
+
9
+ /**
10
+ * Keeps the keyboard focus in the grid when a row or cell enters or leaves edit mode.
11
+ *
12
+ * Two things drop the focus to `<body>`, after which the arrow keys scroll the page instead of
13
+ * moving between cells: when editing stops (Escape, Enter), the grid moves the focus from the
14
+ * editor back to the cell and Chrome then takes it from that cell with no script involved; and the
15
+ * edit, save and cancel buttons are removed while they have the focus. This puts the focus back on
16
+ * the cell the grid's own focus state points at - but only right after a mode change, and only
17
+ * when the focus was lost from that cell, so a click outside the grid (which clears that state)
18
+ * keeps the focus where it went.
19
+ */
20
+ export function useAfKeepFocusAfterEdit(apiRef: React.RefObject<GridApi | null>) {
21
+ useEffect(() => {
22
+ let api = apiRef.current;
23
+ let root = api?.rootElementRef?.current;
24
+ if (!api || !root) return;
25
+
26
+ let lastModeChange = 0;
27
+ let markModeChange = () => {
28
+ lastModeChange = Date.now();
29
+ };
30
+
31
+ let handleFocusOut = (event: FocusEvent) => {
32
+ if (event.relatedTarget || Date.now() - lastModeChange > EDIT_STOP_WINDOW_MS) return;
33
+ let lostFrom = (event.target as HTMLElement).closest?.<HTMLElement>(".MuiDataGrid-row");
34
+ if (!lostFrom) return;
35
+
36
+ setTimeout(() => {
37
+ let doc = root.ownerDocument;
38
+ if (doc.activeElement !== doc.body) return;
39
+
40
+ // The focus state may have moved on to another cell of the same row (the save and
41
+ // cancel buttons move it to the actions cell), so restore whatever it points at.
42
+ let focused = gridFocusCellSelector(apiRef);
43
+ if (!focused || String(focused.id) !== lostFrom.dataset.id) return;
44
+
45
+ let cell = apiRef.current?.getCellElement(focused.id, focused.field);
46
+ if (!cell) return;
47
+
48
+ let target = cell.querySelector<HTMLElement>('[tabindex="0"]') ?? cell;
49
+ target.focus({ preventScroll: true });
50
+ }, 0);
51
+ };
52
+
53
+ let unsubscribers = [
54
+ api.subscribeEvent("rowModesModelChange", markModeChange),
55
+ api.subscribeEvent("cellModesModelChange", markModeChange),
56
+ ];
57
+ root.addEventListener("focusout", handleFocusOut);
58
+
59
+ return () => {
60
+ for (let unsubscribe of unsubscribers) unsubscribe();
61
+ root.removeEventListener("focusout", handleFocusOut);
62
+ };
63
+ }, [apiRef]);
64
+ }
@@ -20,11 +20,7 @@
20
20
  border-radius: var(--ds-border-radius-md, 0.375rem);
21
21
  }
22
22
 
23
- .ObInputAdornments-root[data-size="xs"] {
24
- --obInputAdornments-padding: 0.125rem;
25
- --obInputAdornments-fontSize: var(--ds-font-size-1, 0.75rem);
26
- }
27
-
23
+ /* Designsystemet components come in sm, md and lg; xs and xl are typography-only sizes */
28
24
  .ObInputAdornments-root[data-size="sm"] {
29
25
  --obInputAdornments-padding: 0.25rem;
30
26
  --obInputAdornments-fontSize: var(--ds-font-size-2, 0.875rem);
@@ -0,0 +1,9 @@
1
+ .ObNumberInput-root .ObInputAdornments-field {
2
+ /* Numbers read best right aligned, and the steppers sit at the end anyway */
3
+ text-align: end;
4
+ font-variant-numeric: tabular-nums;
5
+ }
6
+
7
+ .ObNumberInput-root .ObNumberInput-stepper {
8
+ flex-shrink: 0;
9
+ }
@@ -0,0 +1,212 @@
1
+ import { fireEvent, render, screen } from "@testing-library/react";
2
+ import userEvent from "@testing-library/user-event";
3
+ import { useState } from "react";
4
+ import { describe, expect, it, vi } from "vitest";
5
+
6
+ import { NumberInput, type NumberInputProps } from "./NumberInput.js";
7
+
8
+ function Controlled({
9
+ initial = null,
10
+ onChange,
11
+ ...props
12
+ }: Partial<Omit<NumberInputProps, "value" | "onChange">> & {
13
+ initial?: number | null;
14
+ onChange?: (value: number | null) => void;
15
+ }) {
16
+ let [value, setValue] = useState<number | null>(initial);
17
+
18
+ return (
19
+ <NumberInput
20
+ label="Hours"
21
+ {...props}
22
+ value={value}
23
+ onChange={(next) => {
24
+ setValue(next);
25
+ onChange?.(next);
26
+ }}
27
+ />
28
+ );
29
+ }
30
+
31
+ describe("NumberInput", () => {
32
+ it("shows the value formatted with the fraction digits, in nb-NO without a session", () => {
33
+ render(<Controlled initial={8} />);
34
+
35
+ expect(screen.getByLabelText("Hours")).toHaveValue("8,00");
36
+ });
37
+
38
+ it("formats in the culture given", () => {
39
+ render(<Controlled initial={1234.5} culture="en-GB" />);
40
+
41
+ expect(screen.getByLabelText("Hours")).toHaveValue("1,234.50");
42
+ });
43
+
44
+ it("reads a period as the decimal separator for a Norwegian user too", async () => {
45
+ let onChange = vi.fn();
46
+ let user = userEvent.setup();
47
+ render(<Controlled initial={null} culture="nb-NO" onChange={onChange} />);
48
+
49
+ let input = screen.getByLabelText("Hours");
50
+ await user.type(input, "1.5");
51
+ expect(onChange).toHaveBeenLastCalledWith(1.5);
52
+
53
+ await user.tab();
54
+ expect(input).toHaveValue("1,50");
55
+ });
56
+
57
+ it("shows an empty input for null", () => {
58
+ render(<Controlled initial={null} />);
59
+
60
+ expect(screen.getByLabelText("Hours")).toHaveValue("");
61
+ });
62
+
63
+ it("parses typed text with either decimal separator", async () => {
64
+ let onChange = vi.fn();
65
+ let user = userEvent.setup();
66
+ render(<Controlled initial={null} onChange={onChange} />);
67
+
68
+ let input = screen.getByLabelText("Hours");
69
+ await user.type(input, "1,5");
70
+ expect(onChange).toHaveBeenLastCalledWith(1.5);
71
+ expect(input).toHaveValue("1,5");
72
+
73
+ await user.clear(input);
74
+ await user.type(input, "2.25");
75
+ expect(onChange).toHaveBeenLastCalledWith(2.25);
76
+ });
77
+
78
+ it("reports null when cleared and nothing while the text is incomplete", async () => {
79
+ let onChange = vi.fn();
80
+ let user = userEvent.setup();
81
+ render(<Controlled initial={3} onChange={onChange} />);
82
+
83
+ let input = screen.getByLabelText("Hours");
84
+ await user.clear(input);
85
+ expect(onChange).toHaveBeenLastCalledWith(null);
86
+
87
+ onChange.mockClear();
88
+ await user.type(input, "-");
89
+ expect(onChange).not.toHaveBeenCalled();
90
+ });
91
+
92
+ it("formats the value again on blur", async () => {
93
+ let user = userEvent.setup();
94
+ render(<Controlled initial={null} />);
95
+
96
+ let input = screen.getByLabelText("Hours");
97
+ await user.type(input, "1,5");
98
+ await user.tab();
99
+
100
+ expect(input).toHaveValue("1,50");
101
+ });
102
+
103
+ it("steps with the buttons, rounding to the fraction digits", async () => {
104
+ let onChange = vi.fn();
105
+ let user = userEvent.setup();
106
+ render(<Controlled initial={0.1} step={0.2} onChange={onChange} />);
107
+
108
+ await user.click(screen.getByRole("button", { name: "Increase value" }));
109
+ expect(onChange).toHaveBeenLastCalledWith(0.3);
110
+
111
+ await user.click(screen.getByRole("button", { name: "Decrease value" }));
112
+ await user.click(screen.getByRole("button", { name: "Decrease value" }));
113
+ expect(onChange).toHaveBeenLastCalledWith(-0.1);
114
+ });
115
+
116
+ it("steps from zero when empty", async () => {
117
+ let onChange = vi.fn();
118
+ let user = userEvent.setup();
119
+ render(<Controlled initial={null} step={0.25} onChange={onChange} />);
120
+
121
+ await user.click(screen.getByRole("button", { name: "Increase value" }));
122
+ expect(onChange).toHaveBeenLastCalledWith(0.25);
123
+ });
124
+
125
+ it("steps with the arrow keys and keeps the text selected", async () => {
126
+ let onChange = vi.fn();
127
+ let user = userEvent.setup();
128
+ render(<Controlled initial={1} onChange={onChange} />);
129
+
130
+ let input = screen.getByLabelText("Hours") as HTMLInputElement;
131
+ await user.click(input);
132
+ await user.keyboard("{ArrowUp}{ArrowUp}{ArrowDown}");
133
+
134
+ expect(onChange).toHaveBeenLastCalledWith(2);
135
+ expect(input).toHaveValue("2,00");
136
+ });
137
+
138
+ it("clamps typed and stepped values to min and max", async () => {
139
+ let onChange = vi.fn();
140
+ let user = userEvent.setup();
141
+ render(<Controlled initial={23} min={0} max={24} onChange={onChange} />);
142
+
143
+ let input = screen.getByLabelText("Hours");
144
+ await user.click(screen.getByRole("button", { name: "Increase value" }));
145
+ expect(onChange).toHaveBeenLastCalledWith(24);
146
+ expect(screen.getByRole("button", { name: "Increase value" })).toBeDisabled();
147
+
148
+ await user.clear(input);
149
+ await user.type(input, "30");
150
+ expect(onChange).toHaveBeenLastCalledWith(24);
151
+ expect(input).toHaveValue("24,00");
152
+
153
+ await user.clear(input);
154
+ await user.type(input, "-5");
155
+ expect(onChange).toHaveBeenLastCalledWith(0);
156
+ });
157
+
158
+ it("hides the steppers when read only, disabled or asked to", () => {
159
+ let { rerender } = render(<Controlled initial={1} readOnly />);
160
+ expect(screen.queryByRole("button")).toBeNull();
161
+
162
+ rerender(<Controlled initial={1} disabled />);
163
+ expect(screen.queryByRole("button")).toBeNull();
164
+
165
+ rerender(<Controlled initial={1} hideSteppers />);
166
+ expect(screen.queryByRole("button")).toBeNull();
167
+
168
+ rerender(<Controlled initial={1} />);
169
+ expect(screen.getAllByRole("button")).toHaveLength(2);
170
+ });
171
+
172
+ it("does not step a read only input from the keyboard", () => {
173
+ let onChange = vi.fn();
174
+ render(<Controlled initial={1} readOnly onChange={onChange} />);
175
+
176
+ fireEvent.keyDown(screen.getByLabelText("Hours"), { key: "ArrowUp" });
177
+ expect(onChange).not.toHaveBeenCalled();
178
+ });
179
+
180
+ it("shows the description and the error, and marks the input invalid", () => {
181
+ render(<Controlled initial={1} description="Including overtime" error="Too many hours" />);
182
+
183
+ expect(screen.getByText("Including overtime")).toBeInTheDocument();
184
+ expect(screen.getByText("Too many hours")).toBeInTheDocument();
185
+ expect(screen.getByLabelText("Hours")).toHaveAttribute("aria-invalid", "true");
186
+ });
187
+
188
+ it("shows a value changed from the outside while focused", async () => {
189
+ function Resettable() {
190
+ let [value, setValue] = useState<number | null>(5);
191
+ return (
192
+ <>
193
+ <NumberInput label="Hours" value={value} onChange={setValue} />
194
+ <button type="button" onClick={() => setValue(0)}>
195
+ Reset
196
+ </button>
197
+ </>
198
+ );
199
+ }
200
+
201
+ let user = userEvent.setup();
202
+ render(<Resettable />);
203
+
204
+ let input = screen.getByLabelText("Hours");
205
+ await user.click(input);
206
+ await user.keyboard("7");
207
+ expect(input).toHaveValue("7");
208
+
209
+ fireEvent.click(screen.getByRole("button", { name: "Reset" }));
210
+ expect(input).toHaveValue("0,00");
211
+ });
212
+ });
@@ -0,0 +1,268 @@
1
+ import "./NumberInput.css";
2
+
3
+ import { Button, Field, Label, ValidationMessage } from "@digdir/designsystemet-react";
4
+ import { MinusIcon, PlusIcon } from "@navikt/aksel-icons";
5
+ import clsx from "clsx";
6
+ import { type ReactNode, type Ref, useCallback, useEffect, useId, useRef, useState } from "react";
7
+
8
+ import { InputAdornments, type InputAdornmentsProps } from "./InputAdornments.js";
9
+ import { clamp, formatNumber, parseNumber, roundTo } from "./numberFormat.js";
10
+ import { getLocalizedString } from "../i18n.js";
11
+
12
+ export type NumberInputProps = Omit<
13
+ InputAdornmentsProps,
14
+ "value" | "defaultValue" | "onChange" | "type" | "children" | "min" | "max" | "step" | "inputMode" | "ref"
15
+ > & {
16
+ /**
17
+ * The number being edited. `null` renders an empty input.
18
+ */
19
+ value: number | null | undefined;
20
+ /**
21
+ * Called with the parsed number whenever the text in the input is a valid number, and with
22
+ * `null` when the input is cleared. Not called while the text is incomplete (a lone `-`).
23
+ */
24
+ onChange: (value: number | null) => void;
25
+ /**
26
+ * Fraction digits shown and rounded to when stepping. Defaults to 2.
27
+ */
28
+ decimalDigits?: number;
29
+ /**
30
+ * BCP 47 culture the value is formatted in (`nb-NO` shows `8,00`, `en-GB` shows `8.00`).
31
+ * Defaults to the Appframe session's culture, and to `nb-NO` when there is no session.
32
+ * Typed text is parsed the same way whatever the culture: both `,` and `.` are decimal separators.
33
+ */
34
+ culture?: string;
35
+ /**
36
+ * Amount added or subtracted by the stepper buttons and the arrow keys. Defaults to 1.
37
+ */
38
+ step?: number;
39
+ /**
40
+ * Smallest allowed value. Typed and stepped values are clamped to it.
41
+ */
42
+ min?: number;
43
+ /**
44
+ * Largest allowed value. Typed and stepped values are clamped to it.
45
+ */
46
+ max?: number;
47
+ label?: ReactNode;
48
+ description?: ReactNode;
49
+ /**
50
+ * Error message shown below the input. Also marks the input invalid.
51
+ */
52
+ error?: ReactNode;
53
+ /**
54
+ * Hide the increment and decrement buttons. The arrow keys still step. The buttons are also
55
+ * hidden when the input is disabled or read only.
56
+ */
57
+ hideSteppers?: boolean;
58
+ /**
59
+ * Ref to the input element.
60
+ */
61
+ ref?: Ref<HTMLInputElement>;
62
+ };
63
+
64
+ /**
65
+ * A text input for editing a number, with stepper buttons and arrow key support. The number is
66
+ * shown formatted in the user's culture (`8,00`) and edited as text, so both `,` and `.` are
67
+ * accepted as the decimal separator. The whole value is selected when the input gets focus, so
68
+ * typing replaces it.
69
+ *
70
+ * `className` and `style` go on the `Field` wrapper, like Designsystemet's `Textfield`; the rest
71
+ * of the props go to the input.
72
+ *
73
+ * @example
74
+ * ```jsx
75
+ * <NumberInput label="Hours" value={hours} onChange={setHours} step={0.25} min={0} max={24} />
76
+ * ```
77
+ */
78
+ export function NumberInput({
79
+ value,
80
+ onChange,
81
+ decimalDigits = 2,
82
+ culture,
83
+ step = 1,
84
+ min,
85
+ max,
86
+ label,
87
+ description,
88
+ error,
89
+ hideSteppers = false,
90
+ className,
91
+ style,
92
+ disabled,
93
+ readOnly,
94
+ onFocus,
95
+ onBlur,
96
+ onKeyDown,
97
+ ref,
98
+ "data-size": size,
99
+ "data-color": color,
100
+ id: idProp,
101
+ ...props
102
+ }: NumberInputProps) {
103
+ let generatedId = useId();
104
+ let id = idProp ?? generatedId;
105
+ let inputRef = useRef<HTMLInputElement | null>(null);
106
+ let [hasFocus, setHasFocus] = useState(false);
107
+ let [text, setText] = useState("");
108
+ /** The last value this input reported, so an outside change can be told from our own. */
109
+ let lastEmitted = useRef<number | null>(value ?? null);
110
+
111
+ let setRefs = useCallback(
112
+ (element: HTMLInputElement | null) => {
113
+ inputRef.current = element;
114
+ if (typeof ref === "function") {
115
+ ref(element);
116
+ } else if (ref) {
117
+ ref.current = element;
118
+ }
119
+ },
120
+ [ref],
121
+ );
122
+
123
+ function emit(next: number | null) {
124
+ lastEmitted.current = next;
125
+ onChange(next);
126
+ }
127
+
128
+ function editText(nextValue: number | null) {
129
+ setText(formatNumber(nextValue, { decimalDigits, culture }) ?? "");
130
+ }
131
+
132
+ function handleTextChange(raw: string) {
133
+ setText(raw);
134
+
135
+ let parsed = parseNumber(raw);
136
+ if (parsed === null) {
137
+ emit(null);
138
+ return;
139
+ }
140
+ if (Number.isNaN(parsed)) {
141
+ return;
142
+ }
143
+
144
+ let clamped = clamp(parsed, min, max);
145
+ if (clamped !== parsed) {
146
+ editText(clamped);
147
+ }
148
+ emit(clamped);
149
+ }
150
+
151
+ function addStep(delta: number) {
152
+ let current = hasFocus ? parseNumber(text) : (value ?? null);
153
+ if (current === null || Number.isNaN(current)) {
154
+ current = 0;
155
+ }
156
+
157
+ let next = roundTo(clamp(current + delta, min, max), decimalDigits);
158
+ editText(next);
159
+ emit(next);
160
+
161
+ let input = inputRef.current;
162
+ if (input && document.activeElement === input) {
163
+ setTimeout(() => input.select(), 0);
164
+ }
165
+ }
166
+
167
+ function handleFocus(event: React.FocusEvent<HTMLInputElement>) {
168
+ lastEmitted.current = value ?? null;
169
+ editText(value ?? null);
170
+ setHasFocus(true);
171
+ onFocus?.(event);
172
+ }
173
+
174
+ function handleBlur(event: React.FocusEvent<HTMLInputElement>) {
175
+ setHasFocus(false);
176
+ onBlur?.(event);
177
+ }
178
+
179
+ function handleKeyDown(event: React.KeyboardEvent<HTMLInputElement>) {
180
+ if (!readOnly && !disabled) {
181
+ if (event.key === "ArrowUp") {
182
+ event.preventDefault();
183
+ addStep(step);
184
+ } else if (event.key === "ArrowDown") {
185
+ event.preventDefault();
186
+ addStep(-step);
187
+ }
188
+ }
189
+ onKeyDown?.(event);
190
+ }
191
+
192
+ // Select the whole value when the input gets focus, so typing replaces it
193
+ useEffect(() => {
194
+ if (hasFocus) {
195
+ inputRef.current?.select();
196
+ }
197
+ }, [hasFocus]);
198
+
199
+ // The value changed from the outside while editing (cancel edit, a reset): show the new value
200
+ useEffect(() => {
201
+ if (hasFocus && (value ?? null) !== lastEmitted.current) {
202
+ lastEmitted.current = value ?? null;
203
+ setText(formatNumber(value, { decimalDigits, culture }) ?? "");
204
+ }
205
+ }, [value, hasFocus, decimalDigits, culture]);
206
+
207
+ let showSteppers = !hideSteppers && !disabled && !readOnly;
208
+ let current = value ?? null;
209
+ let atMin = current !== null && min !== undefined && current <= min;
210
+ let atMax = current !== null && max !== undefined && current >= max;
211
+
212
+ return (
213
+ <Field className={clsx("ObNumberInput-root", className)} style={style} data-size={size} data-color={color}>
214
+ {!!label && <Label htmlFor={id}>{label}</Label>}
215
+ {!!description && <Field.Description>{description}</Field.Description>}
216
+ <InputAdornments
217
+ {...props}
218
+ data-size={size}
219
+ data-color={color}
220
+ id={id}
221
+ ref={setRefs}
222
+ type="text"
223
+ inputMode="decimal"
224
+ autoComplete="off"
225
+ disabled={disabled}
226
+ readOnly={readOnly}
227
+ aria-invalid={error ? true : undefined}
228
+ value={hasFocus ? text : (formatNumber(value, { decimalDigits, culture, grouping: true }) ?? "")}
229
+ onChange={(event) => handleTextChange(event.target.value)}
230
+ onFocus={handleFocus}
231
+ onBlur={handleBlur}
232
+ onKeyDown={handleKeyDown}
233
+ >
234
+ {showSteppers && (
235
+ <>
236
+ <Button
237
+ icon
238
+ type="button"
239
+ variant="tertiary"
240
+ data-size="sm"
241
+ className="ObNumberInput-stepper"
242
+ tabIndex={-1}
243
+ disabled={atMin}
244
+ aria-label={getLocalizedString("Decrease value")}
245
+ onClick={() => addStep(-step)}
246
+ >
247
+ <MinusIcon aria-hidden />
248
+ </Button>
249
+ <Button
250
+ icon
251
+ type="button"
252
+ variant="tertiary"
253
+ data-size="sm"
254
+ className="ObNumberInput-stepper"
255
+ tabIndex={-1}
256
+ disabled={atMax}
257
+ aria-label={getLocalizedString("Increase value")}
258
+ onClick={() => addStep(step)}
259
+ >
260
+ <PlusIcon aria-hidden />
261
+ </Button>
262
+ </>
263
+ )}
264
+ </InputAdornments>
265
+ {!!error && <ValidationMessage>{error}</ValidationMessage>}
266
+ </Field>
267
+ );
268
+ }
@@ -1 +1,3 @@
1
1
  export * from "./InputAdornments.js";
2
+ export * from "./NumberInput.js";
3
+ export { formatNumber, getDefaultCulture, parseNumber, type FormatNumberOptions } from "./numberFormat.js";
@@ -0,0 +1,79 @@
1
+ import { describe, expect, it } from "vitest";
2
+
3
+ import { clamp, formatNumber, getDefaultCulture, parseNumber, roundTo } from "./numberFormat.js";
4
+
5
+ describe("formatNumber", () => {
6
+ it("returns null for nothing", () => {
7
+ expect(formatNumber(null)).toBeNull();
8
+ expect(formatNumber(undefined)).toBeNull();
9
+ expect(formatNumber(Number.NaN)).toBeNull();
10
+ });
11
+
12
+ it("falls back to nb-NO when there is no Appframe session", () => {
13
+ expect(getDefaultCulture()).toBe("nb-NO");
14
+ expect(formatNumber(8)).toBe("8,00");
15
+ });
16
+
17
+ it("follows the culture given", () => {
18
+ expect(formatNumber(8, { culture: "en-GB" })).toBe("8.00");
19
+ expect(formatNumber(8, { culture: "de-DE" })).toBe("8,00");
20
+ });
21
+
22
+ it("pads and rounds to the fraction digits", () => {
23
+ expect(formatNumber(1.005, { decimalDigits: 0 })).toBe("1");
24
+ expect(formatNumber(1.5, { decimalDigits: 3 })).toBe("1,500");
25
+ });
26
+
27
+ it("leaves out thousands separators unless asked for them", () => {
28
+ expect(formatNumber(1234.5)).toBe("1234,50");
29
+ expect(formatNumber(1234.5, { culture: "en-GB" })).toBe("1234.50");
30
+ expect(formatNumber(1234.5, { culture: "en-GB", grouping: true })).toBe("1,234.50");
31
+ // nb-NO groups with a (narrow no-break) space
32
+ expect(formatNumber(1234.5, { grouping: true })).toMatch(/^1\s234,50$/);
33
+ });
34
+
35
+ it("round trips through parseNumber in any culture", () => {
36
+ expect(parseNumber(formatNumber(1234.5))).toBe(1234.5);
37
+ expect(parseNumber(formatNumber(1234.5, { culture: "en-GB" }))).toBe(1234.5);
38
+ });
39
+ });
40
+
41
+ describe("parseNumber", () => {
42
+ it("returns null for empty text", () => {
43
+ expect(parseNumber("")).toBeNull();
44
+ expect(parseNumber(" ")).toBeNull();
45
+ expect(parseNumber(null)).toBeNull();
46
+ expect(parseNumber(undefined)).toBeNull();
47
+ });
48
+
49
+ it("reads both comma and period as the decimal separator", () => {
50
+ expect(parseNumber("1,5")).toBe(1.5);
51
+ expect(parseNumber("1.5")).toBe(1.5);
52
+ expect(parseNumber("1,")).toBe(1);
53
+ expect(parseNumber(".5")).toBe(0.5);
54
+ });
55
+
56
+ it("accepts the typographic minus and ignores whitespace", () => {
57
+ expect(parseNumber("−2")).toBe(-2);
58
+ expect(parseNumber(" 1 234 ")).toBe(1234);
59
+ });
60
+
61
+ it("returns NaN for text that is not a number yet", () => {
62
+ expect(parseNumber("-")).toBeNaN();
63
+ expect(parseNumber("abc")).toBeNaN();
64
+ });
65
+ });
66
+
67
+ describe("roundTo and clamp", () => {
68
+ it("rounds away floating point noise", () => {
69
+ expect(roundTo(0.1 + 0.2, 2)).toBe(0.3);
70
+ expect(roundTo(2.675, 0)).toBe(3);
71
+ });
72
+
73
+ it("clamps only against the bounds given", () => {
74
+ expect(clamp(5)).toBe(5);
75
+ expect(clamp(5, 0, 3)).toBe(3);
76
+ expect(clamp(-1, 0)).toBe(0);
77
+ expect(clamp(2, undefined, 1)).toBe(1);
78
+ });
79
+ });