@barqjs/aria 0.0.0-stage → 0.2.0-next.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/LICENSE +21 -0
- package/README.md +293 -2
- package/package.json +347 -4
- package/src/breadcrumbs.tsx +296 -0
- package/src/button.tsx +342 -0
- package/src/calendar.tsx +1389 -0
- package/src/checkbox.tsx +570 -0
- package/src/collections.ts +976 -0
- package/src/color.ts +562 -0
- package/src/colorpicker.tsx +1478 -0
- package/src/combobox.tsx +2481 -0
- package/src/command.tsx +1184 -0
- package/src/date.ts +652 -0
- package/src/datefield.tsx +951 -0
- package/src/datepicker.tsx +556 -0
- package/src/dialog.tsx +890 -0
- package/src/disclosure.tsx +659 -0
- package/src/dom.ts +706 -0
- package/src/drawer.ts +674 -0
- package/src/focus.ts +1370 -0
- package/src/form.tsx +94 -0
- package/src/gridlist.tsx +563 -0
- package/src/i18n.ts +823 -0
- package/src/index.ts +1270 -0
- package/src/interactions/description.ts +73 -0
- package/src/interactions/flags.ts +35 -0
- package/src/interactions/focus-events.ts +218 -0
- package/src/interactions/focusable.ts +86 -0
- package/src/interactions/hover.ts +213 -0
- package/src/interactions/interact-outside.ts +123 -0
- package/src/interactions/keyboard.ts +105 -0
- package/src/interactions/listeners.ts +78 -0
- package/src/interactions/long-press.ts +160 -0
- package/src/interactions/modality.ts +416 -0
- package/src/interactions/move.ts +257 -0
- package/src/interactions/open-link.ts +193 -0
- package/src/interactions/press.ts +898 -0
- package/src/interactions/prevent-focus.ts +102 -0
- package/src/interactions/scroll-wheel.ts +43 -0
- package/src/interactions/text-selection.ts +77 -0
- package/src/interactions.ts +81 -0
- package/src/label.ts +128 -0
- package/src/link.tsx +381 -0
- package/src/listbox.tsx +721 -0
- package/src/live.ts +204 -0
- package/src/menu.tsx +2290 -0
- package/src/menubar.tsx +575 -0
- package/src/navigation.ts +735 -0
- package/src/numberfield.tsx +838 -0
- package/src/otp.ts +430 -0
- package/src/overlays.ts +1247 -0
- package/src/platform.ts +74 -0
- package/src/presence.ts +164 -0
- package/src/questionnaire.tsx +1712 -0
- package/src/radio.tsx +567 -0
- package/src/register-dom.ts +12 -0
- package/src/scroller.ts +1165 -0
- package/src/select.tsx +1665 -0
- package/src/selection.ts +1415 -0
- package/src/slider.tsx +1042 -0
- package/src/splitter.ts +1152 -0
- package/src/static-collection.ts +211 -0
- package/src/switch.tsx +186 -0
- package/src/table.tsx +0 -0
- package/src/tabs.tsx +1018 -0
- package/src/tag.tsx +452 -0
- package/src/textfield.tsx +417 -0
- package/src/toast.ts +658 -0
- package/src/toggle-input.tsx +48 -0
- package/src/toggle.ts +321 -0
- package/src/togglegroup.ts +365 -0
- package/src/toolbar.tsx +179 -0
- package/src/tooltip.tsx +657 -0
- package/src/utils.ts +758 -0
- package/src/validation.ts +447 -0
- package/src/virtualizer.tsx +674 -0
|
@@ -0,0 +1,838 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A number field: a text input that holds a number, with stepper buttons.
|
|
3
|
+
*
|
|
4
|
+
* `<input type="number">` is not this. It accepts `1e5` and `--` and rejects
|
|
5
|
+
* nothing, it cannot show a currency symbol or a thousands separator, its
|
|
6
|
+
* spinner is unstyleable and unreachable by touch, and its `valueAsNumber` is
|
|
7
|
+
* NaN whenever the user is mid-edit. So this is a `type="text"` input with the
|
|
8
|
+
* numeric parts put back:
|
|
9
|
+
*
|
|
10
|
+
* - **It is formatted while you are not editing and plain while you are.** The
|
|
11
|
+
* value shows as "$1,234.50" and commits back to that on blur, but a
|
|
12
|
+
* keystroke that could still become a number is accepted as typed.
|
|
13
|
+
* - **Parsing is locale-aware.** "1.234,5" is one thousand two hundred and
|
|
14
|
+
* thirty four and a half in German, and `parseFloat` would read 1.234.
|
|
15
|
+
* - **It announces.** The input carries no `role`, because a spin button role
|
|
16
|
+
* makes VoiceOver refuse to focus it; instead the value is announced
|
|
17
|
+
* assertively when it changes, which is what a real spin button would do.
|
|
18
|
+
*
|
|
19
|
+
* The stepper buttons are out of the Tab order and take no focus: they belong
|
|
20
|
+
* to the input, and a keyboard user reaches the same thing with the arrows.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import {
|
|
24
|
+
type Accessor,
|
|
25
|
+
type Child,
|
|
26
|
+
createMemo,
|
|
27
|
+
createContext,
|
|
28
|
+
createEffect,
|
|
29
|
+
getContext,
|
|
30
|
+
getOwner,
|
|
31
|
+
type Incoming,
|
|
32
|
+
install,
|
|
33
|
+
createSignal,
|
|
34
|
+
} from "@barqjs/core";
|
|
35
|
+
import { isServer } from "@barqjs/web";
|
|
36
|
+
import { ref as makeRef, mergeRefs, type RefTarget } from "@barqjs/primitives/refs";
|
|
37
|
+
import { button } from "./button.tsx";
|
|
38
|
+
import { focusRing } from "./focus.ts";
|
|
39
|
+
import { numberFormatter, numberParser } from "./i18n.ts";
|
|
40
|
+
import { focusWithin } from "./interactions/focus-events.ts";
|
|
41
|
+
import { hover } from "./interactions/hover.ts";
|
|
42
|
+
import type { ElementRef, PressEvent } from "./interactions/press.ts";
|
|
43
|
+
import { scrollWheel } from "./interactions/scroll-wheel.ts";
|
|
44
|
+
import { announce, clearAnnouncer } from "./live.ts";
|
|
45
|
+
import { textField, type TextFieldOptions } from "./textfield.tsx";
|
|
46
|
+
import {
|
|
47
|
+
type FormValidationState,
|
|
48
|
+
type ValidateFunction,
|
|
49
|
+
type ValidationBehavior,
|
|
50
|
+
} from "./validation.ts";
|
|
51
|
+
import { formReset } from "./toggle.ts";
|
|
52
|
+
import {
|
|
53
|
+
access,
|
|
54
|
+
callback,
|
|
55
|
+
clamp,
|
|
56
|
+
controllable,
|
|
57
|
+
type DOMProps,
|
|
58
|
+
filterDOMProps,
|
|
59
|
+
fromProps,
|
|
60
|
+
id,
|
|
61
|
+
type MaybeAccessor,
|
|
62
|
+
mergeProps,
|
|
63
|
+
snapValueToStep,
|
|
64
|
+
type StyleProps,
|
|
65
|
+
styleProps,
|
|
66
|
+
} from "./utils.ts";
|
|
67
|
+
|
|
68
|
+
// ---------------------------------------------------------------------------
|
|
69
|
+
// State
|
|
70
|
+
// ---------------------------------------------------------------------------
|
|
71
|
+
|
|
72
|
+
export interface NumberFieldStateOptions {
|
|
73
|
+
value?: MaybeAccessor<number | null | undefined>;
|
|
74
|
+
defaultValue?: MaybeAccessor<number | null | undefined>;
|
|
75
|
+
minValue?: MaybeAccessor<number | undefined>;
|
|
76
|
+
maxValue?: MaybeAccessor<number | undefined>;
|
|
77
|
+
step?: MaybeAccessor<number | undefined>;
|
|
78
|
+
formatOptions?: MaybeAccessor<Intl.NumberFormatOptions | undefined>;
|
|
79
|
+
isDisabled?: MaybeAccessor<boolean | undefined>;
|
|
80
|
+
isReadOnly?: MaybeAccessor<boolean | undefined>;
|
|
81
|
+
/**
|
|
82
|
+
* Whether committing snaps to the step, or only validates.
|
|
83
|
+
*
|
|
84
|
+
* @default "snap"
|
|
85
|
+
*/
|
|
86
|
+
commitBehavior?: MaybeAccessor<"snap" | "validate" | undefined>;
|
|
87
|
+
onChange?: (value: number) => void;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export interface NumberFieldState {
|
|
91
|
+
/** What the input shows: as typed while editing, formatted otherwise. */
|
|
92
|
+
inputValue: Accessor<string>;
|
|
93
|
+
/** What it currently parses to, or NaN. */
|
|
94
|
+
numberValue: Accessor<number>;
|
|
95
|
+
defaultNumberValue: Accessor<number>;
|
|
96
|
+
minValue: Accessor<number | undefined>;
|
|
97
|
+
maxValue: Accessor<number | undefined>;
|
|
98
|
+
canIncrement: Accessor<boolean>;
|
|
99
|
+
canDecrement: Accessor<boolean>;
|
|
100
|
+
/** Whether the text could still become a number as the user keeps typing. */
|
|
101
|
+
validate(value: string): boolean;
|
|
102
|
+
setInputValue(value: string): void;
|
|
103
|
+
setNumberValue(value: number): void;
|
|
104
|
+
/** Parse, clamp, snap and format. What blur and Enter do. */
|
|
105
|
+
commit(value?: string): void;
|
|
106
|
+
increment(): void;
|
|
107
|
+
decrement(): void;
|
|
108
|
+
incrementToMax(): void;
|
|
109
|
+
decrementToMin(): void;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Add or subtract without the binary floating point drift. */
|
|
113
|
+
function step(operation: "+" | "-", value: number, amount: number): number {
|
|
114
|
+
const decimals = (entry: number): number => {
|
|
115
|
+
const text = String(entry);
|
|
116
|
+
const point = text.indexOf(".");
|
|
117
|
+
return point === -1 ? 0 : text.length - point - 1;
|
|
118
|
+
};
|
|
119
|
+
const places = Math.max(decimals(value), decimals(amount));
|
|
120
|
+
const scale = 10 ** places;
|
|
121
|
+
const scaled =
|
|
122
|
+
operation === "+" ? value * scale + amount * scale : value * scale - amount * scale;
|
|
123
|
+
return scaled / scale;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function numberFieldState(options: NumberFieldStateOptions): NumberFieldState {
|
|
127
|
+
const format = numberFormatter(access(options.formatOptions));
|
|
128
|
+
const parser = numberParser(access(options.formatOptions));
|
|
129
|
+
|
|
130
|
+
const min = (): number | undefined => access(options.minValue);
|
|
131
|
+
const max = (): number | undefined => access(options.maxValue);
|
|
132
|
+
const snaps = (): boolean => (access(options.commitBehavior) ?? "snap") === "snap";
|
|
133
|
+
|
|
134
|
+
const stepSize = (): number => {
|
|
135
|
+
const given = access(options.step);
|
|
136
|
+
if (given !== undefined && !Number.isNaN(given)) return given;
|
|
137
|
+
// A percent field's natural step is one percentage point, which is 0.01 of
|
|
138
|
+
// the value it holds.
|
|
139
|
+
return format().resolvedOptions().style === "percent" ? 0.01 : 1;
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
const snap = (value: number): number => {
|
|
143
|
+
const given = access(options.step);
|
|
144
|
+
if (given === undefined || Number.isNaN(given)) return clamp(value, min(), max());
|
|
145
|
+
return snapValueToStep(value, min(), max(), given);
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
const [numberValue, setNumberValueRaw] = controllable<number>(
|
|
149
|
+
() => {
|
|
150
|
+
const given = access(options.value);
|
|
151
|
+
if (given === undefined) return undefined;
|
|
152
|
+
if (given === null || Number.isNaN(given)) return Number.NaN;
|
|
153
|
+
return snaps() ? snap(given) : given;
|
|
154
|
+
},
|
|
155
|
+
() => {
|
|
156
|
+
const given = access(options.defaultValue);
|
|
157
|
+
if (given === null || given === undefined || Number.isNaN(given)) return Number.NaN;
|
|
158
|
+
return snaps() ? snap(given) : given;
|
|
159
|
+
},
|
|
160
|
+
options.onChange,
|
|
161
|
+
);
|
|
162
|
+
|
|
163
|
+
const initial = numberValue();
|
|
164
|
+
const asText = (value: number): string => (Number.isNaN(value) ? "" : format().format(value));
|
|
165
|
+
|
|
166
|
+
const [inputValue, writeInputValue] = createSignal(asText(numberValue()));
|
|
167
|
+
|
|
168
|
+
// What the LAST write produced, so a keystroke reads its own change back
|
|
169
|
+
// rather than the value a controlled owner has not caught up with yet.
|
|
170
|
+
let live = numberValue();
|
|
171
|
+
|
|
172
|
+
if (!isServer) {
|
|
173
|
+
// The number changing from OUTSIDE reformats the field. A change the field
|
|
174
|
+
// made itself is already in it, as typed.
|
|
175
|
+
createEffect(numberValue, (value) => {
|
|
176
|
+
if (value === live) return;
|
|
177
|
+
live = value;
|
|
178
|
+
writeInputValue(asText(value));
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const parsed = createMemo(() => parser().parse(inputValue()));
|
|
183
|
+
|
|
184
|
+
const setNumberValue = (value: number): void => {
|
|
185
|
+
live = value;
|
|
186
|
+
setNumberValueRaw(value);
|
|
187
|
+
writeInputValue(asText(value));
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
const commit = (override?: string): void => {
|
|
191
|
+
const text = override ?? inputValue();
|
|
192
|
+
|
|
193
|
+
if (text.length === 0) {
|
|
194
|
+
live = Number.NaN;
|
|
195
|
+
setNumberValueRaw(Number.NaN);
|
|
196
|
+
writeInputValue(access(options.value) === undefined ? "" : asText(numberValue()));
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const value = override === undefined ? parsed() : parser().parse(override);
|
|
201
|
+
if (Number.isNaN(value)) {
|
|
202
|
+
// Not a number after all: the field goes back to what it holds rather
|
|
203
|
+
// than keeping text that means nothing.
|
|
204
|
+
writeInputValue(asText(numberValue()));
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// Formatted and read back, so the value IS what the field will show: a
|
|
209
|
+
// field displaying two decimal places holds two decimal places.
|
|
210
|
+
const clamped = parser().parse(asText(snaps() ? snap(value) : value));
|
|
211
|
+
live = clamped;
|
|
212
|
+
setNumberValueRaw(clamped);
|
|
213
|
+
writeInputValue(asText(access(options.value) === undefined ? clamped : numberValue()));
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* The next step boundary in a direction.
|
|
218
|
+
*
|
|
219
|
+
* From a value already off the boundary, the first move is ONTO it — the
|
|
220
|
+
* user asked for the next valid value, not for the next one plus a step.
|
|
221
|
+
*/
|
|
222
|
+
const nextStep = (operation: "+" | "-", empty: number | undefined): number => {
|
|
223
|
+
const current = parsed();
|
|
224
|
+
const size = stepSize();
|
|
225
|
+
|
|
226
|
+
if (Number.isNaN(current)) {
|
|
227
|
+
return snapValueToStep(
|
|
228
|
+
empty === undefined || Number.isNaN(empty) ? 0 : empty,
|
|
229
|
+
min(),
|
|
230
|
+
max(),
|
|
231
|
+
size,
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const snapped = snapValueToStep(current, min(), max(), size);
|
|
236
|
+
if ((operation === "+" && snapped > current) || (operation === "-" && snapped < current)) {
|
|
237
|
+
return snapped;
|
|
238
|
+
}
|
|
239
|
+
return snapValueToStep(step(operation, current, size), min(), max(), size);
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
const canStep = (operation: "+" | "-"): boolean => {
|
|
243
|
+
if (access(options.isDisabled) === true || access(options.isReadOnly) === true) return false;
|
|
244
|
+
const current = parsed();
|
|
245
|
+
const limit = operation === "+" ? max() : min();
|
|
246
|
+
if (Number.isNaN(current) || limit === undefined || Number.isNaN(limit)) return true;
|
|
247
|
+
const size = stepSize();
|
|
248
|
+
if (operation === "+") {
|
|
249
|
+
return (
|
|
250
|
+
snapValueToStep(current, min(), max(), size) > current || step("+", current, size) <= limit
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
return (
|
|
254
|
+
snapValueToStep(current, min(), max(), size) < current || step("-", current, size) >= limit
|
|
255
|
+
);
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
return {
|
|
259
|
+
inputValue,
|
|
260
|
+
numberValue,
|
|
261
|
+
defaultNumberValue: () => {
|
|
262
|
+
const given = access(options.defaultValue);
|
|
263
|
+
if (given === null || given === undefined || Number.isNaN(given)) return initial;
|
|
264
|
+
return snaps() ? snap(given) : given;
|
|
265
|
+
},
|
|
266
|
+
minValue: min,
|
|
267
|
+
maxValue: max,
|
|
268
|
+
canIncrement: () => canStep("+"),
|
|
269
|
+
canDecrement: () => canStep("-"),
|
|
270
|
+
validate: (value) => parser().isValidPartialNumber(value, min(), max()),
|
|
271
|
+
setInputValue: (value) => writeInputValue(value),
|
|
272
|
+
setNumberValue,
|
|
273
|
+
commit,
|
|
274
|
+
increment: () => setNumberValue(nextStep("+", min())),
|
|
275
|
+
decrement: () => setNumberValue(nextStep("-", max())),
|
|
276
|
+
incrementToMax: () => {
|
|
277
|
+
const limit = max();
|
|
278
|
+
if (limit !== undefined) setNumberValue(snapValueToStep(limit, min(), max(), stepSize()));
|
|
279
|
+
},
|
|
280
|
+
decrementToMin: () => {
|
|
281
|
+
const limit = min();
|
|
282
|
+
if (limit !== undefined) setNumberValue(limit);
|
|
283
|
+
},
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// ---------------------------------------------------------------------------
|
|
288
|
+
// Spin button
|
|
289
|
+
// ---------------------------------------------------------------------------
|
|
290
|
+
|
|
291
|
+
export interface SpinButtonOptions {
|
|
292
|
+
isDisabled?: MaybeAccessor<boolean | undefined>;
|
|
293
|
+
isReadOnly?: MaybeAccessor<boolean | undefined>;
|
|
294
|
+
value?: MaybeAccessor<number | undefined>;
|
|
295
|
+
minValue?: MaybeAccessor<number | undefined>;
|
|
296
|
+
maxValue?: MaybeAccessor<number | undefined>;
|
|
297
|
+
/** What the value MEANS, for assistive technology. */
|
|
298
|
+
textValue?: MaybeAccessor<string | undefined>;
|
|
299
|
+
onIncrement?: () => void;
|
|
300
|
+
onDecrement?: () => void;
|
|
301
|
+
onIncrementToMax?: () => void;
|
|
302
|
+
onDecrementToMin?: () => void;
|
|
303
|
+
onIncrementPage?: () => void;
|
|
304
|
+
onDecrementPage?: () => void;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
export interface SpinButtonResult {
|
|
308
|
+
spinButtonProps: DOMProps;
|
|
309
|
+
/** Options for {@link button}, not props for an element. */
|
|
310
|
+
incrementButtonProps: DOMProps;
|
|
311
|
+
decrementButtonProps: DOMProps;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** How long a held stepper button waits before it starts repeating. */
|
|
315
|
+
const REPEAT_DELAY = 400;
|
|
316
|
+
const REPEAT_INTERVAL = 60;
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* The keys and the press-and-hold that step a value.
|
|
320
|
+
*
|
|
321
|
+
* Holding a stepper button repeats, as the platform's own does; the repeat is
|
|
322
|
+
* cancelled by a `pointercancel`, so a touch that turns into a scroll does not
|
|
323
|
+
* leave the value running away.
|
|
324
|
+
*/
|
|
325
|
+
export function spinButton(options: SpinButtonOptions): SpinButtonResult {
|
|
326
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
327
|
+
let announced = false;
|
|
328
|
+
|
|
329
|
+
const stop = (): void => {
|
|
330
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
331
|
+
timer = undefined;
|
|
332
|
+
};
|
|
333
|
+
|
|
334
|
+
const repeat = (act: () => void, guard: () => boolean, delay: number): void => {
|
|
335
|
+
stop();
|
|
336
|
+
timer = setTimeout(() => {
|
|
337
|
+
if (!guard()) return;
|
|
338
|
+
act();
|
|
339
|
+
repeat(act, guard, REPEAT_INTERVAL);
|
|
340
|
+
}, delay);
|
|
341
|
+
};
|
|
342
|
+
|
|
343
|
+
const belowMax = (): boolean => {
|
|
344
|
+
const limit = access(options.maxValue);
|
|
345
|
+
const value = access(options.value);
|
|
346
|
+
return limit === undefined || value === undefined || Number.isNaN(value) || value < limit;
|
|
347
|
+
};
|
|
348
|
+
|
|
349
|
+
const aboveMin = (): boolean => {
|
|
350
|
+
const limit = access(options.minValue);
|
|
351
|
+
const value = access(options.value);
|
|
352
|
+
return limit === undefined || value === undefined || Number.isNaN(value) || value > limit;
|
|
353
|
+
};
|
|
354
|
+
|
|
355
|
+
const enabled = (): boolean =>
|
|
356
|
+
access(options.isDisabled) !== true && access(options.isReadOnly) !== true;
|
|
357
|
+
|
|
358
|
+
const onKeyDown = (event: KeyboardEvent): void => {
|
|
359
|
+
if (!enabled()) return;
|
|
360
|
+
switch (event.key) {
|
|
361
|
+
case "PageUp":
|
|
362
|
+
event.preventDefault();
|
|
363
|
+
(options.onIncrementPage ?? options.onIncrement)?.();
|
|
364
|
+
return;
|
|
365
|
+
case "PageDown":
|
|
366
|
+
event.preventDefault();
|
|
367
|
+
(options.onDecrementPage ?? options.onDecrement)?.();
|
|
368
|
+
return;
|
|
369
|
+
case "ArrowUp":
|
|
370
|
+
event.preventDefault();
|
|
371
|
+
options.onIncrement?.();
|
|
372
|
+
return;
|
|
373
|
+
case "ArrowDown":
|
|
374
|
+
event.preventDefault();
|
|
375
|
+
options.onDecrement?.();
|
|
376
|
+
return;
|
|
377
|
+
case "Home":
|
|
378
|
+
if (options.onDecrementToMin === undefined) return;
|
|
379
|
+
event.preventDefault();
|
|
380
|
+
options.onDecrementToMin();
|
|
381
|
+
return;
|
|
382
|
+
case "End":
|
|
383
|
+
if (options.onIncrementToMax === undefined) return;
|
|
384
|
+
event.preventDefault();
|
|
385
|
+
options.onIncrementToMax();
|
|
386
|
+
return;
|
|
387
|
+
default:
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
};
|
|
391
|
+
|
|
392
|
+
if (!isServer) {
|
|
393
|
+
// Announced assertively, because the input carries no spin button role to
|
|
394
|
+
// announce it for us. `clearAnnouncer` first, so holding a stepper does
|
|
395
|
+
// not queue up thirty values to read out in turn.
|
|
396
|
+
createEffect(
|
|
397
|
+
() => [access(options.textValue), access(options.value)] as const,
|
|
398
|
+
([textValue, value]) => {
|
|
399
|
+
const text = textValue ?? String(value ?? "");
|
|
400
|
+
// A hyphen-minus between a currency symbol and a number is read as a
|
|
401
|
+
// hyphen and swallowed; the real minus sign is announced.
|
|
402
|
+
const spoken = text === "" ? "Empty" : text.replace("-", "−");
|
|
403
|
+
if (!announced) {
|
|
404
|
+
announced = true;
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
clearAnnouncer("assertive");
|
|
408
|
+
announce(spoken, "assertive");
|
|
409
|
+
},
|
|
410
|
+
);
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* One step now, then a repeat while it is held.
|
|
415
|
+
*
|
|
416
|
+
* Touch is the exception: nothing happens until the finger lifts, because a
|
|
417
|
+
* touch that turns into a scroll must not have changed the value on the way
|
|
418
|
+
* past.
|
|
419
|
+
*/
|
|
420
|
+
const stepper = (
|
|
421
|
+
act: () => void,
|
|
422
|
+
guard: () => boolean,
|
|
423
|
+
): {
|
|
424
|
+
onPressStart: (event: { pointerType: string }) => void;
|
|
425
|
+
onPressEnd: (event: { pointerType: string }) => void;
|
|
426
|
+
} => {
|
|
427
|
+
let held = false;
|
|
428
|
+
let spun = false;
|
|
429
|
+
return {
|
|
430
|
+
onPressStart: (event) => {
|
|
431
|
+
stop();
|
|
432
|
+
spun = false;
|
|
433
|
+
held = event.pointerType === "touch";
|
|
434
|
+
if (!enabled()) return;
|
|
435
|
+
if (!held) act();
|
|
436
|
+
repeat(
|
|
437
|
+
() => {
|
|
438
|
+
spun = true;
|
|
439
|
+
act();
|
|
440
|
+
},
|
|
441
|
+
guard,
|
|
442
|
+
REPEAT_DELAY,
|
|
443
|
+
);
|
|
444
|
+
},
|
|
445
|
+
onPressEnd: () => {
|
|
446
|
+
stop();
|
|
447
|
+
if (held && !spun && enabled()) act();
|
|
448
|
+
held = false;
|
|
449
|
+
},
|
|
450
|
+
};
|
|
451
|
+
};
|
|
452
|
+
|
|
453
|
+
return {
|
|
454
|
+
spinButtonProps: { onKeyDown },
|
|
455
|
+
incrementButtonProps: stepper(() => options.onIncrement?.(), belowMax),
|
|
456
|
+
decrementButtonProps: stepper(() => options.onDecrement?.(), aboveMin),
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
// ---------------------------------------------------------------------------
|
|
461
|
+
// Hooks
|
|
462
|
+
// ---------------------------------------------------------------------------
|
|
463
|
+
|
|
464
|
+
export interface NumberFieldOptions extends Omit<
|
|
465
|
+
TextFieldOptions,
|
|
466
|
+
"value" | "defaultValue" | "onChange" | "type" | "validate"
|
|
467
|
+
> {
|
|
468
|
+
/**
|
|
469
|
+
* What the page thinks of the NUMBER, checked as it changes.
|
|
470
|
+
*
|
|
471
|
+
* The number rather than the typed text: a validator handed "1.2e" while
|
|
472
|
+
* someone is still typing has nothing useful to say.
|
|
473
|
+
*/
|
|
474
|
+
validate?: ValidateFunction<number>;
|
|
475
|
+
inputRef: ElementRef<HTMLInputElement>;
|
|
476
|
+
formatOptions?: MaybeAccessor<Intl.NumberFormatOptions | undefined>;
|
|
477
|
+
minValue?: MaybeAccessor<number | undefined>;
|
|
478
|
+
maxValue?: MaybeAccessor<number | undefined>;
|
|
479
|
+
/** Stop the scroll wheel changing the value. @default false */
|
|
480
|
+
isWheelDisabled?: MaybeAccessor<boolean | undefined>;
|
|
481
|
+
incrementAriaLabel?: MaybeAccessor<string | undefined>;
|
|
482
|
+
decrementAriaLabel?: MaybeAccessor<string | undefined>;
|
|
483
|
+
/** The field's visible label, for naming the stepper buttons. */
|
|
484
|
+
label?: MaybeAccessor<string | undefined>;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
export interface NumberFieldResult {
|
|
488
|
+
labelProps: DOMProps;
|
|
489
|
+
/** What is wrong with the value, and whether the user is being told. */
|
|
490
|
+
validation: FormValidationState;
|
|
491
|
+
errors: Accessor<string[]>;
|
|
492
|
+
isInvalid: Accessor<boolean>;
|
|
493
|
+
/** For the element wrapping the input and its steppers. */
|
|
494
|
+
groupProps: DOMProps;
|
|
495
|
+
inputProps: DOMProps;
|
|
496
|
+
/** Options for {@link button}, not props for an element. */
|
|
497
|
+
incrementButtonProps: DOMProps;
|
|
498
|
+
decrementButtonProps: DOMProps;
|
|
499
|
+
descriptionProps: DOMProps;
|
|
500
|
+
errorMessageProps: DOMProps;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
export function numberField(
|
|
504
|
+
options: NumberFieldOptions,
|
|
505
|
+
state: NumberFieldState,
|
|
506
|
+
): NumberFieldResult {
|
|
507
|
+
const inputId = id();
|
|
508
|
+
const format = numberFormatter(access(options.formatOptions));
|
|
509
|
+
|
|
510
|
+
const isDisabled = (): boolean => access(options.isDisabled) === true;
|
|
511
|
+
const isReadOnly = (): boolean => access(options.isReadOnly) === true;
|
|
512
|
+
|
|
513
|
+
// Never `currencySign: "accounting"`: the value would be spoken as
|
|
514
|
+
// parentheses rather than as a negative number.
|
|
515
|
+
const spoken = numberFormatter({ ...access(options.formatOptions), currencySign: undefined });
|
|
516
|
+
const textValue = (): string =>
|
|
517
|
+
Number.isNaN(state.numberValue()) ? "" : spoken().format(state.numberValue());
|
|
518
|
+
|
|
519
|
+
const { spinButtonProps, incrementButtonProps, decrementButtonProps } = spinButton({
|
|
520
|
+
isDisabled: options.isDisabled,
|
|
521
|
+
isReadOnly: options.isReadOnly,
|
|
522
|
+
value: state.numberValue,
|
|
523
|
+
minValue: options.minValue,
|
|
524
|
+
maxValue: options.maxValue,
|
|
525
|
+
textValue,
|
|
526
|
+
onIncrement: () => state.increment(),
|
|
527
|
+
onDecrement: () => state.decrement(),
|
|
528
|
+
onIncrementToMax: () => state.incrementToMax(),
|
|
529
|
+
onDecrementToMin: () => state.decrementToMin(),
|
|
530
|
+
});
|
|
531
|
+
|
|
532
|
+
const { focusWithinProps, isFocusWithin } = focusWithin({ isDisabled: options.isDisabled });
|
|
533
|
+
|
|
534
|
+
scrollWheel({
|
|
535
|
+
ref: options.inputRef,
|
|
536
|
+
isDisabled: () =>
|
|
537
|
+
access(options.isWheelDisabled) === true || isDisabled() || isReadOnly() || !isFocusWithin(),
|
|
538
|
+
onScroll: (delta) => {
|
|
539
|
+
// A trackpad scrolls in both directions at once. Mostly sideways is the
|
|
540
|
+
// user scrolling the page, not adjusting this field.
|
|
541
|
+
if (Math.abs(delta.deltaY) <= Math.abs(delta.deltaX)) return;
|
|
542
|
+
if (delta.deltaY > 0) state.increment();
|
|
543
|
+
else state.decrement();
|
|
544
|
+
},
|
|
545
|
+
});
|
|
546
|
+
|
|
547
|
+
/**
|
|
548
|
+
* Which software keyboard a touch device offers.
|
|
549
|
+
*
|
|
550
|
+
* `numeric` has no minus and no decimal point on iOS, so a field that can
|
|
551
|
+
* hold either has to ask for something wider — and the answers differ
|
|
552
|
+
* between iOS and Android.
|
|
553
|
+
*/
|
|
554
|
+
const inputMode = (): string => {
|
|
555
|
+
const resolved = format().resolvedOptions();
|
|
556
|
+
const hasDecimals = (resolved.maximumFractionDigits ?? 0) > 0;
|
|
557
|
+
const hasNegative = state.minValue() === undefined || (state.minValue() as number) < 0;
|
|
558
|
+
if (hasNegative) return "text";
|
|
559
|
+
if (hasDecimals) return "decimal";
|
|
560
|
+
return "numeric";
|
|
561
|
+
};
|
|
562
|
+
|
|
563
|
+
const {
|
|
564
|
+
labelProps,
|
|
565
|
+
inputProps: fieldProps,
|
|
566
|
+
descriptionProps,
|
|
567
|
+
errorMessageProps,
|
|
568
|
+
validation,
|
|
569
|
+
errors,
|
|
570
|
+
isInvalid,
|
|
571
|
+
} = textField(
|
|
572
|
+
{
|
|
573
|
+
...options,
|
|
574
|
+
id: inputId,
|
|
575
|
+
type: "text",
|
|
576
|
+
// The caller validates the NUMBER; `textField` validates a string, so
|
|
577
|
+
// the typed text is ignored and the parsed value is handed over instead.
|
|
578
|
+
validate:
|
|
579
|
+
options.validate === undefined
|
|
580
|
+
? undefined
|
|
581
|
+
: () => (options.validate as ValidateFunction<number>)(state.numberValue()),
|
|
582
|
+
value: state.inputValue,
|
|
583
|
+
// Rejected keystrokes never reach the state, so a field that cannot hold
|
|
584
|
+
// a letter never shows one.
|
|
585
|
+
onChange: (value) => {
|
|
586
|
+
if (state.validate(value)) state.setInputValue(value);
|
|
587
|
+
},
|
|
588
|
+
autoComplete: "off",
|
|
589
|
+
},
|
|
590
|
+
options.inputRef,
|
|
591
|
+
);
|
|
592
|
+
|
|
593
|
+
formReset(options.inputRef, state.defaultNumberValue, (value) => state.setNumberValue(value));
|
|
594
|
+
|
|
595
|
+
const onBlur = (): void => {
|
|
596
|
+
state.commit();
|
|
597
|
+
validation.commitValidation();
|
|
598
|
+
};
|
|
599
|
+
|
|
600
|
+
const onKeyDown = (event: KeyboardEvent): void => {
|
|
601
|
+
if (event.key !== "Enter") return;
|
|
602
|
+
// Not prevented: a number field inside a form still submits it, with the
|
|
603
|
+
// committed value rather than the typed one.
|
|
604
|
+
state.commit();
|
|
605
|
+
};
|
|
606
|
+
|
|
607
|
+
const onPaste = (event: ClipboardEvent): void => {
|
|
608
|
+
const input = event.target as HTMLInputElement;
|
|
609
|
+
// Only a paste over the WHOLE field: anything else would need the new
|
|
610
|
+
// string worked out from where the selection was, and a partial paste is
|
|
611
|
+
// handled by the ordinary input path.
|
|
612
|
+
if ((input.selectionEnd ?? -1) - (input.selectionStart ?? 0) !== input.value.length) return;
|
|
613
|
+
event.preventDefault();
|
|
614
|
+
state.commit(event.clipboardData?.getData("text/plain")?.trim() ?? "");
|
|
615
|
+
};
|
|
616
|
+
|
|
617
|
+
/** Focus the INPUT, not the button: a stepper is not a place to stand. */
|
|
618
|
+
const onButtonPressStart = (event: PressEvent): void => {
|
|
619
|
+
const input = access(options.inputRef) as HTMLInputElement | null;
|
|
620
|
+
if (input === null) return;
|
|
621
|
+
if (input.ownerDocument.activeElement === input) return;
|
|
622
|
+
// Touch and screen readers keep focus on the button, so the software
|
|
623
|
+
// keyboard does not appear and the reader's cursor does not jump.
|
|
624
|
+
if (event.pointerType === "mouse") input.focus();
|
|
625
|
+
};
|
|
626
|
+
|
|
627
|
+
const fieldLabel = (): string => access(options.label) ?? access(options["aria-label"]) ?? "";
|
|
628
|
+
|
|
629
|
+
return {
|
|
630
|
+
labelProps,
|
|
631
|
+
descriptionProps,
|
|
632
|
+
errorMessageProps,
|
|
633
|
+
validation,
|
|
634
|
+
errors,
|
|
635
|
+
isInvalid,
|
|
636
|
+
groupProps: mergeProps(focusWithinProps, {
|
|
637
|
+
role: "group",
|
|
638
|
+
"aria-disabled": () => isDisabled() || undefined,
|
|
639
|
+
}),
|
|
640
|
+
inputProps: mergeProps(spinButtonProps, fieldProps, {
|
|
641
|
+
onKeyDown,
|
|
642
|
+
onBlur,
|
|
643
|
+
onPaste,
|
|
644
|
+
// No `role`: a `spinbutton` role makes VoiceOver refuse to put its
|
|
645
|
+
// cursor in the field at all, and the value is announced by hand
|
|
646
|
+
// instead.
|
|
647
|
+
inputmode: inputMode,
|
|
648
|
+
autocorrect: "off",
|
|
649
|
+
spellcheck: "false",
|
|
650
|
+
}),
|
|
651
|
+
incrementButtonProps: mergeProps(incrementButtonProps, {
|
|
652
|
+
"aria-label": () => access(options.incrementAriaLabel) ?? `Increase ${fieldLabel()}`.trim(),
|
|
653
|
+
"aria-controls": inputId,
|
|
654
|
+
excludeFromTabOrder: true,
|
|
655
|
+
preventFocusOnPress: true,
|
|
656
|
+
isDisabled: () => !state.canIncrement(),
|
|
657
|
+
onPressStart: onButtonPressStart,
|
|
658
|
+
}),
|
|
659
|
+
decrementButtonProps: mergeProps(decrementButtonProps, {
|
|
660
|
+
"aria-label": () => access(options.decrementAriaLabel) ?? `Decrease ${fieldLabel()}`.trim(),
|
|
661
|
+
"aria-controls": inputId,
|
|
662
|
+
excludeFromTabOrder: true,
|
|
663
|
+
preventFocusOnPress: true,
|
|
664
|
+
isDisabled: () => !state.canDecrement(),
|
|
665
|
+
onPressStart: onButtonPressStart,
|
|
666
|
+
}),
|
|
667
|
+
};
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// ---------------------------------------------------------------------------
|
|
671
|
+
// Components
|
|
672
|
+
// ---------------------------------------------------------------------------
|
|
673
|
+
|
|
674
|
+
interface NumberFieldContextValue {
|
|
675
|
+
state: NumberFieldState;
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
const NumberFieldContext = createContext<NumberFieldContextValue | null>(null);
|
|
679
|
+
|
|
680
|
+
export function useNumberField(): NumberFieldContextValue {
|
|
681
|
+
const value = getContext(NumberFieldContext);
|
|
682
|
+
if (value === null || value === undefined) {
|
|
683
|
+
throw new Error("This must be rendered inside a NumberField.");
|
|
684
|
+
}
|
|
685
|
+
return value;
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
export interface NumberFieldComponentProps extends StyleProps {
|
|
689
|
+
label?: string;
|
|
690
|
+
description?: Child;
|
|
691
|
+
errorMessage?: Child;
|
|
692
|
+
value?: number | null;
|
|
693
|
+
defaultValue?: number | null;
|
|
694
|
+
minValue?: number;
|
|
695
|
+
maxValue?: number;
|
|
696
|
+
step?: number;
|
|
697
|
+
formatOptions?: Intl.NumberFormatOptions;
|
|
698
|
+
placeholder?: string;
|
|
699
|
+
isDisabled?: boolean;
|
|
700
|
+
isReadOnly?: boolean;
|
|
701
|
+
isRequired?: boolean;
|
|
702
|
+
isInvalid?: boolean;
|
|
703
|
+
/** What the page thinks of the number, checked as it changes. */
|
|
704
|
+
validate?: ValidateFunction<number>;
|
|
705
|
+
/** @default "aria" */
|
|
706
|
+
validationBehavior?: ValidationBehavior;
|
|
707
|
+
isWheelDisabled?: boolean;
|
|
708
|
+
name?: string;
|
|
709
|
+
form?: string;
|
|
710
|
+
autoFocus?: boolean;
|
|
711
|
+
incrementAriaLabel?: string;
|
|
712
|
+
decrementAriaLabel?: string;
|
|
713
|
+
"aria-label"?: string;
|
|
714
|
+
"aria-labelledby"?: string;
|
|
715
|
+
ref?: RefTarget<HTMLInputElement>;
|
|
716
|
+
onChange?: (value: number) => void;
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
/**
|
|
720
|
+
* ```tsx
|
|
721
|
+
* <NumberField label="Quantity" defaultValue={1} minValue={0} onChange={(n) => qty.set(n)} />
|
|
722
|
+
* <NumberField label="Price" formatOptions={{ style: "currency", currency: "GBP" }} />
|
|
723
|
+
* ```
|
|
724
|
+
*/
|
|
725
|
+
export function NumberField(props: Incoming<NumberFieldComponentProps>) {
|
|
726
|
+
const inputRef = makeRef<HTMLInputElement>();
|
|
727
|
+
const incrementRef = makeRef<HTMLButtonElement>();
|
|
728
|
+
const decrementRef = makeRef<HTMLButtonElement>();
|
|
729
|
+
|
|
730
|
+
const state = numberFieldState({
|
|
731
|
+
value: () => props.value?.(),
|
|
732
|
+
defaultValue: () => props.defaultValue?.(),
|
|
733
|
+
minValue: () => props.minValue?.(),
|
|
734
|
+
maxValue: () => props.maxValue?.(),
|
|
735
|
+
step: () => props.step?.(),
|
|
736
|
+
formatOptions: () => props.formatOptions?.(),
|
|
737
|
+
isDisabled: () => props.isDisabled?.(),
|
|
738
|
+
isReadOnly: () => props.isReadOnly?.(),
|
|
739
|
+
onChange: (value) => props.onChange?.()?.(value),
|
|
740
|
+
});
|
|
741
|
+
|
|
742
|
+
const {
|
|
743
|
+
labelProps,
|
|
744
|
+
groupProps,
|
|
745
|
+
inputProps,
|
|
746
|
+
incrementButtonProps,
|
|
747
|
+
decrementButtonProps,
|
|
748
|
+
descriptionProps,
|
|
749
|
+
errorMessageProps,
|
|
750
|
+
errors,
|
|
751
|
+
isInvalid,
|
|
752
|
+
} = numberField(
|
|
753
|
+
{
|
|
754
|
+
inputRef,
|
|
755
|
+
label: () => props.label?.(),
|
|
756
|
+
name: () => props.name?.(),
|
|
757
|
+
form: () => props.form?.(),
|
|
758
|
+
validate: callback<[number], string | string[] | true | null | undefined>(props.validate),
|
|
759
|
+
validationBehavior: () => props.validationBehavior?.(),
|
|
760
|
+
minValue: () => props.minValue?.(),
|
|
761
|
+
maxValue: () => props.maxValue?.(),
|
|
762
|
+
formatOptions: () => props.formatOptions?.(),
|
|
763
|
+
placeholder: () => props.placeholder?.(),
|
|
764
|
+
isDisabled: () => props.isDisabled?.(),
|
|
765
|
+
isReadOnly: () => props.isReadOnly?.(),
|
|
766
|
+
isRequired: () => props.isRequired?.(),
|
|
767
|
+
isInvalid: () => props.isInvalid?.(),
|
|
768
|
+
isWheelDisabled: () => props.isWheelDisabled?.(),
|
|
769
|
+
autoFocus: () => props.autoFocus?.(),
|
|
770
|
+
incrementAriaLabel: () => props.incrementAriaLabel?.(),
|
|
771
|
+
decrementAriaLabel: () => props.decrementAriaLabel?.(),
|
|
772
|
+
"aria-label": () => props["aria-label"]?.(),
|
|
773
|
+
"aria-labelledby": () => props["aria-labelledby"]?.(),
|
|
774
|
+
},
|
|
775
|
+
state,
|
|
776
|
+
);
|
|
777
|
+
|
|
778
|
+
const increment = button(incrementButtonProps, incrementRef);
|
|
779
|
+
const decrement = button(decrementButtonProps, decrementRef);
|
|
780
|
+
const { focusProps, isFocusVisible } = focusRing();
|
|
781
|
+
const { hoverProps, isHovered } = hover({ isDisabled: () => props.isDisabled?.() });
|
|
782
|
+
|
|
783
|
+
const owner = getOwner();
|
|
784
|
+
if (owner !== null) install(owner, NumberFieldContext, () => ({ state }));
|
|
785
|
+
|
|
786
|
+
const elementProps = mergeProps(
|
|
787
|
+
groupProps,
|
|
788
|
+
hoverProps,
|
|
789
|
+
filterDOMProps(fromProps(props), { global: true }),
|
|
790
|
+
styleProps(props),
|
|
791
|
+
{
|
|
792
|
+
"data-hovered": isHovered,
|
|
793
|
+
"data-disabled": () => props.isDisabled?.() === true,
|
|
794
|
+
"data-invalid": isInvalid,
|
|
795
|
+
"data-testid": () => props["data-testid"]?.(),
|
|
796
|
+
},
|
|
797
|
+
);
|
|
798
|
+
|
|
799
|
+
const inputElementProps = mergeProps(inputProps, focusProps, {
|
|
800
|
+
name: () => props.name?.(),
|
|
801
|
+
form: () => props.form?.(),
|
|
802
|
+
"data-focus-visible": isFocusVisible,
|
|
803
|
+
});
|
|
804
|
+
|
|
805
|
+
return (
|
|
806
|
+
<>
|
|
807
|
+
<label {...labelProps}>{props.label}</label>
|
|
808
|
+
<div {...elementProps}>
|
|
809
|
+
<button
|
|
810
|
+
{...decrement.buttonProps}
|
|
811
|
+
type="button"
|
|
812
|
+
data-pressed={decrement.isPressed}
|
|
813
|
+
ref={decrementRef.set}
|
|
814
|
+
>
|
|
815
|
+
<span aria-hidden="true">−</span>
|
|
816
|
+
</button>
|
|
817
|
+
<input {...inputElementProps} ref={mergeRefs(inputRef.set, props.ref?.())} />
|
|
818
|
+
<button
|
|
819
|
+
{...increment.buttonProps}
|
|
820
|
+
type="button"
|
|
821
|
+
data-pressed={increment.isPressed}
|
|
822
|
+
ref={incrementRef.set}
|
|
823
|
+
>
|
|
824
|
+
<span aria-hidden="true">+</span>
|
|
825
|
+
</button>
|
|
826
|
+
</div>
|
|
827
|
+
<span {...descriptionProps}>{props.description}</span>
|
|
828
|
+
<span {...errorMessageProps}>
|
|
829
|
+
{() => {
|
|
830
|
+
const given = props.errorMessage?.();
|
|
831
|
+
if (given !== undefined && given !== null && given !== "") return given;
|
|
832
|
+
const found = errors();
|
|
833
|
+
return found.length === 0 ? null : found.join(" ");
|
|
834
|
+
}}
|
|
835
|
+
</span>
|
|
836
|
+
</>
|
|
837
|
+
);
|
|
838
|
+
}
|