@olenbetong/appframe-ds 1.5.0 → 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.
@@ -1,14 +1,22 @@
1
1
  import "./LookupGrid.css";
2
2
 
3
+ import { ArrowDownIcon, ArrowUpIcon } from "@navikt/aksel-icons";
3
4
  import type { LookupColumn } from "@olenbetong/appframe-react";
4
5
 
5
6
  import clsx from "clsx";
6
- import { useEffect, useMemo } from "react";
7
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
7
8
  import { List, type RowComponentProps, useListRef } from "react-window";
8
9
  import { getLocalizedString } from "../i18n.js";
9
10
 
10
11
  const ROW_HEIGHT = 40;
11
12
  const HEADER_HEIGHT = 40;
13
+ /** Narrowest a column can be made, and what a flexible column counts for in the minimum width */
14
+ const MIN_COLUMN_WIDTH = 80;
15
+
16
+ export type LookupGridSort = {
17
+ field: string;
18
+ direction: "asc" | "desc";
19
+ };
12
20
 
13
21
  export interface LookupGridProps<T extends Record<string, unknown>> {
14
22
  columns: LookupColumn<T>[];
@@ -19,18 +27,49 @@ export interface LookupGridProps<T extends Record<string, unknown>> {
19
27
  getItemId: (item: T | undefined) => string | undefined;
20
28
  isItemSelected?: (item: T) => boolean;
21
29
  onSelectItem: (item: T) => void;
30
+ /**
31
+ * The column the rows are sorted by, shown with an arrow in its header
32
+ */
33
+ sort?: LookupGridSort;
34
+ /**
35
+ * Called with the field of a header the user clicked. When left out the headers are plain text.
36
+ */
37
+ onSort?: (field: string) => void;
22
38
  }
23
39
 
24
- function getColumnWidth<T extends Record<string, unknown>>(column: LookupColumn<T>) {
40
+ /** The track for one column in `grid-template-columns`; a width the user dragged wins over the configured one */
41
+ function getColumnTrack<T extends Record<string, unknown>>(column: LookupColumn<T>, resizedWidth: number | undefined) {
42
+ if (resizedWidth !== undefined) {
43
+ return `${resizedWidth}px`;
44
+ }
25
45
  if (typeof column.width === "number") {
26
46
  return `${column.width}px`;
27
47
  }
28
48
 
29
- return column.width ?? "minmax(80px, 1fr)";
49
+ return column.width ?? `minmax(${MIN_COLUMN_WIDTH}px, 1fr)`;
50
+ }
51
+
52
+ /** What a column contributes to the narrowest width the grid can be laid out in */
53
+ function getColumnMinWidth<T extends Record<string, unknown>>(
54
+ column: LookupColumn<T>,
55
+ resizedWidth: number | undefined,
56
+ ) {
57
+ if (resizedWidth !== undefined) {
58
+ return resizedWidth;
59
+ }
60
+ if (typeof column.width === "number") {
61
+ return column.width;
62
+ }
63
+ if (typeof column.width === "string" && /^\d+(\.\d+)?px$/.test(column.width)) {
64
+ return Number.parseFloat(column.width);
65
+ }
66
+
67
+ return MIN_COLUMN_WIDTH;
30
68
  }
31
69
 
32
- type LookupGridRowProps<T extends Record<string, unknown>> = Omit<LookupGridProps<T>, "height"> & {
70
+ type LookupGridRowProps<T extends Record<string, unknown>> = Omit<LookupGridProps<T>, "height" | "sort" | "onSort"> & {
33
71
  gridTemplateColumns: string;
72
+ minWidth: number;
34
73
  };
35
74
 
36
75
  function LookupGridRow<T extends Record<string, unknown>>({
@@ -41,6 +80,7 @@ function LookupGridRow<T extends Record<string, unknown>>({
41
80
  currentIndex,
42
81
  currentColumn,
43
82
  gridTemplateColumns,
83
+ minWidth,
44
84
  getItemId,
45
85
  isItemSelected,
46
86
  onSelectItem,
@@ -54,7 +94,7 @@ function LookupGridRow<T extends Record<string, unknown>>({
54
94
  role="row"
55
95
  aria-selected={active}
56
96
  className={clsx("ObLookupGrid-row", active && "active", isItemSelected?.(item) && "selected")}
57
- style={{ ...style, gridTemplateColumns }}
97
+ style={{ ...style, gridTemplateColumns, minWidth }}
58
98
  onClick={() => onSelectItem(item)}
59
99
  id={itemId}
60
100
  >
@@ -65,13 +105,77 @@ function LookupGridRow<T extends Record<string, unknown>>({
65
105
  key={column.field}
66
106
  title={String(item[column.field] ?? "")}
67
107
  >
68
- {column.renderCell ? column.renderCell(item[column.field], item) : String(item[column.field] ?? "")}
108
+ {/* The cell is a flex container, so the ellipsis has to be on an element inside it */}
109
+ <span className="ObLookupGrid-cellText">
110
+ {column.renderCell ? column.renderCell(item[column.field], item) : String(item[column.field] ?? "")}
111
+ </span>
69
112
  </div>
70
113
  ))}
71
114
  </div>
72
115
  );
73
116
  }
74
117
 
118
+ type ColumnResizerProps = {
119
+ onResize: (delta: number) => void;
120
+ /** Called with the handle, whose parent is the header cell being resized */
121
+ onResizeStart: (handle: HTMLElement) => void;
122
+ onResizeEnd: () => void;
123
+ onReset: () => void;
124
+ };
125
+
126
+ /**
127
+ * The drag handle at the end of a header cell. Pointer capture keeps the drag alive when the
128
+ * pointer leaves the handle; a double click puts the column back to its configured width.
129
+ */
130
+ function ColumnResizer({ onResize, onResizeStart, onResizeEnd, onReset }: ColumnResizerProps) {
131
+ let startX = useRef(0);
132
+
133
+ return (
134
+ // oxlint-disable-next-line jsx-a11y/no-static-element-interactions -- a drag handle; the grid is keyboard navigable by cell
135
+ <div
136
+ role="separator"
137
+ aria-orientation="vertical"
138
+ aria-label={getLocalizedString("Resize column")}
139
+ className="ObLookupGrid-resizer"
140
+ onClick={(event) => event.stopPropagation()}
141
+ onDoubleClick={(event) => {
142
+ event.stopPropagation();
143
+ onReset();
144
+ }}
145
+ onPointerDown={(event) => {
146
+ if (event.button !== 0) return;
147
+ event.preventDefault();
148
+ event.stopPropagation();
149
+ event.currentTarget.setPointerCapture(event.pointerId);
150
+ startX.current = event.clientX;
151
+ onResizeStart(event.currentTarget);
152
+ }}
153
+ onPointerMove={(event) => {
154
+ if (!event.currentTarget.hasPointerCapture(event.pointerId)) return;
155
+ onResize(event.clientX - startX.current);
156
+ }}
157
+ onPointerUp={(event) => {
158
+ if (!event.currentTarget.hasPointerCapture(event.pointerId)) return;
159
+ event.currentTarget.releasePointerCapture(event.pointerId);
160
+ onResizeEnd();
161
+ }}
162
+ onPointerCancel={onResizeEnd}
163
+ />
164
+ );
165
+ }
166
+
167
+ /**
168
+ * The grid variant of the lookup popup: a header row and a virtualised list of rows, laid out
169
+ * with the same `grid-template-columns`.
170
+ *
171
+ * Only the list scrolls. It scrolls both ways when the columns are wider than the popup, and
172
+ * the header follows it sideways with a transform, so the header never needs a scrollbar of
173
+ * its own. The list reserves its vertical scrollbar gutter, and the header row is given the
174
+ * list's inner width, so flexible (`1fr`) columns line up between the two.
175
+ *
176
+ * Columns can be resized by dragging the handle at the end of a header cell. The widths live
177
+ * in the grid, so they last for as long as the popup is open.
178
+ */
75
179
  export function LookupGrid<T extends Record<string, unknown>>({
76
180
  columns,
77
181
  data,
@@ -81,9 +185,23 @@ export function LookupGrid<T extends Record<string, unknown>>({
81
185
  getItemId,
82
186
  isItemSelected,
83
187
  onSelectItem,
188
+ sort,
189
+ onSort,
84
190
  }: LookupGridProps<T>) {
85
191
  let listRef = useListRef(null);
86
- let gridTemplateColumns = useMemo(() => columns.map(getColumnWidth).join(" "), [columns]);
192
+ let headerRowRef = useRef<HTMLDivElement>(null);
193
+ let [resizedWidths, setResizedWidths] = useState<Partial<Record<string, number>>>({});
194
+ let [resizing, setResizing] = useState<{ field: string; startWidth: number } | null>(null);
195
+ let [listInnerWidth, setListInnerWidth] = useState<number>();
196
+
197
+ let gridTemplateColumns = useMemo(
198
+ () => columns.map((column) => getColumnTrack(column, resizedWidths[column.field])).join(" "),
199
+ [columns, resizedWidths],
200
+ );
201
+ let minWidth = useMemo(
202
+ () => columns.reduce((sum, column) => sum + getColumnMinWidth(column, resizedWidths[column.field]), 0),
203
+ [columns, resizedWidths],
204
+ );
87
205
 
88
206
  useEffect(() => {
89
207
  if (currentIndex >= 0 && currentIndex < data.length) {
@@ -91,22 +209,103 @@ export function LookupGrid<T extends Record<string, unknown>>({
91
209
  }
92
210
  }, [currentIndex, data.length, listRef]);
93
211
 
212
+ // The header row is as wide as the list's inner (client) width, so 1fr columns match the rows
213
+ useEffect(() => {
214
+ let element = listRef.current?.element;
215
+ if (!element) return;
216
+
217
+ let measure = () => setListInnerWidth(element.clientWidth);
218
+ measure();
219
+
220
+ let observer = new ResizeObserver(measure);
221
+ observer.observe(element);
222
+
223
+ return () => observer.disconnect();
224
+ }, [listRef, height]);
225
+
226
+ let handleScroll = useCallback((event: React.UIEvent<HTMLDivElement>) => {
227
+ if (headerRowRef.current) {
228
+ headerRowRef.current.style.transform = `translateX(${-event.currentTarget.scrollLeft}px)`;
229
+ }
230
+ }, []);
231
+
232
+ function startResize(field: string, cell: HTMLElement) {
233
+ setResizing({ field, startWidth: cell.getBoundingClientRect().width });
234
+ }
235
+
236
+ function resizeBy(delta: number) {
237
+ if (!resizing) return;
238
+ let { field, startWidth } = resizing;
239
+ let width = Math.max(MIN_COLUMN_WIDTH, Math.round(startWidth + delta));
240
+ setResizedWidths((widths) => (widths[field] === width ? widths : { ...widths, [field]: width }));
241
+ }
242
+
243
+ function resetWidth(field: string) {
244
+ setResizedWidths(({ [field]: _removed, ...rest }) => rest);
245
+ }
246
+
94
247
  return (
95
- <div role="grid" aria-label={getLocalizedString("Search results")} className="ObLookupGrid-root">
96
- <div role="row" className="ObLookupGrid-header" style={{ gridTemplateColumns }}>
97
- {columns.map((column) => (
98
- <div role="columnheader" className="ObLookupGrid-headerCell" key={column.field}>
99
- {column.headerName ?? column.field}
100
- </div>
101
- ))}
248
+ <div
249
+ role="grid"
250
+ aria-label={getLocalizedString("Search results")}
251
+ className="ObLookupGrid-root"
252
+ data-resizing={resizing ? "" : undefined}
253
+ >
254
+ <div className="ObLookupGrid-header">
255
+ <div
256
+ role="row"
257
+ ref={headerRowRef}
258
+ className="ObLookupGrid-headerRow"
259
+ style={{ gridTemplateColumns, minWidth, width: listInnerWidth }}
260
+ >
261
+ {columns.map((column) => {
262
+ let sortable = !!onSort && column.sortable !== false;
263
+ let sorted = sort?.field === column.field ? sort.direction : undefined;
264
+ let label = column.headerName ?? column.field;
265
+ let SortIcon = sorted === "desc" ? ArrowDownIcon : ArrowUpIcon;
266
+
267
+ return (
268
+ <div
269
+ role="columnheader"
270
+ className="ObLookupGrid-headerCell"
271
+ key={column.field}
272
+ aria-sort={sorted === "asc" ? "ascending" : sorted === "desc" ? "descending" : undefined}
273
+ >
274
+ {sortable ? (
275
+ <button
276
+ type="button"
277
+ className={clsx("ObLookupGrid-sortButton", sorted && "sorted")}
278
+ // Keeps the focus in the search field, so typing carries on after a click
279
+ onMouseDown={(event) => event.preventDefault()}
280
+ onClick={() => onSort?.(column.field)}
281
+ tabIndex={-1}
282
+ >
283
+ <span className="ObLookupGrid-headerText">{label}</span>
284
+ <SortIcon className="ObLookupGrid-sortIcon" aria-hidden />
285
+ </button>
286
+ ) : (
287
+ <span className="ObLookupGrid-headerText">{label}</span>
288
+ )}
289
+ <ColumnResizer
290
+ onResizeStart={(handle) => startResize(column.field, handle.parentElement as HTMLElement)}
291
+ onResize={resizeBy}
292
+ onResizeEnd={() => setResizing(null)}
293
+ onReset={() => resetWidth(column.field)}
294
+ />
295
+ </div>
296
+ );
297
+ })}
298
+ </div>
102
299
  </div>
103
300
  <List<LookupGridRowProps<T>>
104
301
  role="rowgroup"
105
302
  listRef={listRef}
303
+ className="ObLookupGrid-list"
106
304
  style={{ height: Math.max(0, height - HEADER_HEIGHT) }}
107
305
  rowCount={data.length}
108
306
  rowHeight={ROW_HEIGHT}
109
307
  overscanCount={5}
308
+ onScroll={handleScroll}
110
309
  rowComponent={LookupGridRow}
111
310
  rowProps={{
112
311
  columns,
@@ -114,6 +313,7 @@ export function LookupGrid<T extends Record<string, unknown>>({
114
313
  currentIndex,
115
314
  currentColumn,
116
315
  gridTemplateColumns,
316
+ minWidth,
117
317
  getItemId,
118
318
  isItemSelected,
119
319
  onSelectItem,
@@ -27,12 +27,9 @@
27
27
  * Font size is deliberately never set: `ds-input` inherits its font size when a
28
28
  * `data-size` attribute is present, so referencing `--ds-font-size-*` here — which
29
29
  * `data-size` rescales — would render the text smaller than a `Textfield` or
30
- * `Select` of the same size. Only the padding varies per size.
30
+ * `Select` of the same size. Only the padding varies per size, and only for the
31
+ * sizes Designsystemet components come in (sm, md, lg; xs and xl are typography-only).
31
32
  */
32
- .ObAutocomplete-root[data-size="xs"] {
33
- --obAutocomplete-padding: 0.125rem;
34
- }
35
-
36
33
  .ObAutocomplete-root[data-size="sm"] {
37
34
  --obAutocomplete-padding: 0.25rem;
38
35
  }
@@ -0,0 +1,42 @@
1
+ import { useField } from "@olenbetong/appframe-react";
2
+
3
+ import { NumberInput, type NumberInputProps } from "../input/NumberInput.js";
4
+
5
+ export type BoundNumberInputProps = Omit<NumberInputProps, "value" | "onChange" | "onKeyDown"> & {
6
+ /**
7
+ * Name of the number field in the data object from context
8
+ */
9
+ field: string;
10
+ /**
11
+ * Called with the new value before it is written to the data object
12
+ */
13
+ onChange?: (value: number | null) => void;
14
+ };
15
+
16
+ /**
17
+ * A `NumberInput` bound to a number field of the data object from `DataObjectProvider`
18
+ * via `useField`. Escape resets the field, and a conversion error from the data object is
19
+ * shown below the input unless an `error` is passed.
20
+ *
21
+ * @example
22
+ * ```jsx
23
+ * <BoundNumberInput field="TotHrs" label="Total hours" step={0.25} min={0} max={24} />
24
+ * ```
25
+ */
26
+ export function BoundNumberInput({ field, onChange: onChangeProp, error: errorProp, ...props }: BoundNumberInputProps) {
27
+ let { error, value, onChange, onKeyDown } = useField<any, any>(field);
28
+
29
+ return (
30
+ <NumberInput
31
+ name={field}
32
+ {...props}
33
+ error={errorProp ?? error ?? undefined}
34
+ value={typeof value === "number" ? value : null}
35
+ onChange={(next) => {
36
+ onChangeProp?.(next);
37
+ onChange({ target: { value: next } });
38
+ }}
39
+ onKeyDown={(event) => onKeyDown(event)}
40
+ />
41
+ );
42
+ }
@@ -2,6 +2,7 @@ export * from "./BoundCheckbox.js";
2
2
  export * from "./BoundDatePicker.js";
3
3
  export * from "./BoundDateTimePicker.js";
4
4
  export * from "./BoundInput.js";
5
+ export * from "./BoundNumberInput.js";
5
6
  export * from "./BoundNumericTextField.js";
6
7
  export * from "./BoundSelect.js";
7
8
  export * from "./BoundSwitch.js";
@@ -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
+ });