@zag-js/number-input 2.0.0-next.2 → 2.0.0-next.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/index.d.mts +6 -9
  2. package/dist/index.d.ts +6 -9
  3. package/dist/index.js +12 -38
  4. package/dist/index.mjs +2 -7
  5. package/dist/number-input.anatomy.d.mts +2 -6
  6. package/dist/number-input.anatomy.d.ts +2 -6
  7. package/dist/number-input.anatomy.js +8 -43
  8. package/dist/number-input.anatomy.mjs +4 -17
  9. package/dist/number-input.connect.d.mts +3 -8
  10. package/dist/number-input.connect.d.ts +3 -8
  11. package/dist/number-input.connect.js +483 -377
  12. package/dist/number-input.connect.mjs +478 -353
  13. package/dist/number-input.dom.d.mts +33 -33
  14. package/dist/number-input.dom.d.ts +33 -33
  15. package/dist/number-input.dom.js +99 -142
  16. package/dist/number-input.dom.mjs +78 -103
  17. package/dist/number-input.machine.d.mts +2 -8
  18. package/dist/number-input.machine.d.ts +2 -8
  19. package/dist/number-input.machine.js +600 -528
  20. package/dist/number-input.machine.mjs +596 -512
  21. package/dist/number-input.props.d.mts +3 -9
  22. package/dist/number-input.props.d.ts +3 -9
  23. package/dist/number-input.props.js +43 -69
  24. package/dist/number-input.props.mjs +39 -43
  25. package/dist/number-input.translations.d.mts +3 -8
  26. package/dist/number-input.translations.d.ts +3 -8
  27. package/dist/number-input.translations.js +9 -31
  28. package/dist/number-input.translations.mjs +5 -6
  29. package/dist/number-input.types.d.mts +418 -408
  30. package/dist/number-input.types.d.ts +418 -408
  31. package/dist/number-input.types.js +4 -18
  32. package/dist/number-input.types.mjs +1 -0
  33. package/dist/number-input.utils.d.mts +16 -12
  34. package/dist/number-input.utils.d.ts +16 -12
  35. package/dist/number-input.utils.js +51 -57
  36. package/dist/number-input.utils.mjs +39 -27
  37. package/package.json +8 -8
  38. package/dist/cursor.d.mts +0 -12
  39. package/dist/cursor.d.ts +0 -12
  40. package/dist/cursor.js +0 -111
  41. package/dist/cursor.mjs +0 -84
@@ -1,514 +1,598 @@
1
- // src/number-input.machine.ts
1
+ import { dispatchHiddenInputValue, getHiddenInputEl, getInputEl, getMousemoveValue, getScrubberEl, getTriggerEl, preventTextSelection } from "./number-input.dom.mjs";
2
+ import { createFormatter, createParser, formatNumber, formatValue, getDefaultStep, parseValue, snapToStep } from "./number-input.utils.mjs";
3
+ import { AnimationFrame, addDomEvent, isFirefox, isIPhone, isIos, isSafari, observeAttributes, recordCursor, requestPointerLock, restoreCursor, setElementValue, trackFormControl } from "@zag-js/dom-query";
4
+ import { callAll, clampValue, decrementValue, incrementValue, isValueWithinRange } from "@zag-js/utils";
2
5
  import { memo, setup } from "@zag-js/core";
3
- import {
4
- addDomEvent,
5
- isFirefox,
6
- isSafari,
7
- observeAttributes,
8
- raf,
9
- requestPointerLock,
10
- setElementValue,
11
- trackFormControl
12
- } from "@zag-js/dom-query";
13
- import {
14
- callAll,
15
- clampValue,
16
- decrementValue,
17
- incrementValue,
18
- isValueAtMax,
19
- isValueAtMin,
20
- isValueWithinRange,
21
- snapValueToStep,
22
- mergeWithDefault
23
- } from "@zag-js/utils";
24
- import { recordCursor, restoreCursor } from "./cursor.mjs";
25
- import * as dom from "./number-input.dom.mjs";
26
- import { defaultTranslations } from "./number-input.translations.mjs";
27
- import { createFormatter, createParser, formatValue, getDefaultStep, parseValue } from "./number-input.utils.mjs";
28
- var { choose, guards, createMachine } = setup();
29
- var { not, and } = guards;
30
- var machine = createMachine({
31
- props({ props }) {
32
- const step = getDefaultStep(props.step, props.formatOptions);
33
- return {
34
- dir: "ltr",
35
- locale: "en-US",
36
- focusInputOnChange: true,
37
- clampValueOnBlur: !props.allowOverflow,
38
- allowOverflow: false,
39
- inputMode: "decimal",
40
- pattern: "-?[0-9]*(.[0-9]+)?",
41
- defaultValue: "",
42
- step,
43
- min: Number.MIN_SAFE_INTEGER,
44
- max: Number.MAX_SAFE_INTEGER,
45
- spinOnPress: true,
46
- scrubberPixelSensitivity: 2,
47
- scrubberDirection: "horizontal",
48
- snapOnStep: false,
49
- ...props,
50
- largeStep: props.largeStep ?? 10 * step,
51
- smallStep: props.smallStep ?? step / 10
52
- };
53
- },
54
- initialState() {
55
- return "idle";
56
- },
57
- context({ prop, bindable, getComputed, getEvent }) {
58
- return {
59
- value: bindable(() => ({
60
- defaultValue: prop("defaultValue"),
61
- value: prop("value"),
62
- onChange(value) {
63
- const computed = getComputed();
64
- const valueAsNumber = parseValue(value, { computed, prop });
65
- prop("onValueChange")?.({ value, valueAsNumber, reason: getEvent().src });
66
- }
67
- })),
68
- hint: bindable(() => ({ defaultValue: null })),
69
- scrubberCursorPoint: bindable(() => ({
70
- defaultValue: null,
71
- hash(value) {
72
- return value ? `x:${value.x}, y:${value.y}` : "";
73
- }
74
- })),
75
- fieldsetDisabled: bindable(() => ({ defaultValue: false })),
76
- cumulativeDelta: bindable(() => ({ defaultValue: 0 })),
77
- isPointerLockSupported: bindable(() => ({ defaultValue: false })),
78
- visualScale: bindable(() => ({ defaultValue: 1 }))
79
- };
80
- },
81
- computed: {
82
- isRtl: ({ prop }) => prop("dir") === "rtl",
83
- valueAsNumber: ({ context, computed, prop }) => parseValue(context.get("value"), { computed, prop }),
84
- formattedValue: ({ computed, prop }) => formatValue(computed("valueAsNumber"), { computed, prop }),
85
- isAtMin: ({ computed, prop }) => isValueAtMin(computed("valueAsNumber"), prop("min")),
86
- isAtMax: ({ computed, prop }) => isValueAtMax(computed("valueAsNumber"), prop("max")),
87
- isOutOfRange: ({ computed, prop }) => !isValueWithinRange(computed("valueAsNumber"), prop("min"), prop("max")),
88
- isValueEmpty: ({ context }) => context.get("value") === "",
89
- isDisabled: ({ prop, context }) => !!prop("disabled") || context.get("fieldsetDisabled"),
90
- canIncrement: ({ prop, computed }) => prop("allowOverflow") || !computed("isAtMax"),
91
- canDecrement: ({ prop, computed }) => prop("allowOverflow") || !computed("isAtMin"),
92
- // Only useful when the display differs from `aria-valuenow`, as with currency or percent.
93
- valueText: ({ prop, context, computed }) => {
94
- const translations = mergeWithDefault(defaultTranslations, prop("translations"));
95
- const custom = translations.valueText?.(context.get("value"));
96
- if (custom) return custom;
97
- if (computed("isValueEmpty")) return void 0;
98
- const formatted = computed("formattedValue");
99
- return formatted === String(computed("valueAsNumber")) ? void 0 : formatted;
100
- },
101
- formatter: memo(
102
- ({ prop }) => [prop("locale"), prop("formatOptions")],
103
- ([locale, formatOptions]) => createFormatter(locale, formatOptions)
104
- ),
105
- parser: memo(
106
- ({ prop }) => [prop("locale"), prop("formatOptions")],
107
- ([locale, formatOptions]) => createParser(locale, formatOptions)
108
- )
109
- },
110
- watch({ track, action, context, computed, prop }) {
111
- track([() => context.get("value"), () => prop("locale"), () => JSON.stringify(prop("formatOptions"))], () => {
112
- action(["syncInputElement"]);
113
- });
114
- track([() => computed("isOutOfRange")], () => {
115
- if (!computed("isOutOfRange")) return;
116
- action(["invokeOnInvalid"]);
117
- });
118
- track([() => context.hash("scrubberCursorPoint")], () => {
119
- action(["setVirtualCursorPosition"]);
120
- });
121
- },
122
- effects: ["trackFormControl", "detectPointerLock"],
123
- on: {
124
- "INPUT.FOCUS": {
125
- actions: ["invokeOnFocus"]
126
- },
127
- "VALUE.SET": {
128
- actions: ["setRawValue", "invokeOnValueCommit"]
129
- },
130
- "VALUE.CLEAR": {
131
- actions: ["clearValue", "invokeOnValueCommit"]
132
- },
133
- "VALUE.INCREMENT": {
134
- actions: ["increment", "invokeOnValueCommit"]
135
- },
136
- "VALUE.DECREMENT": {
137
- actions: ["decrement", "invokeOnValueCommit"]
138
- }
139
- },
140
- states: {
141
- idle: {
142
- on: {
143
- "TRIGGER.PRESS_DOWN": [
144
- { guard: "isTouchPointer", target: "pressed", actions: ["setHint"] },
145
- {
146
- target: "pressed",
147
- actions: ["focusInput", "setHint"]
148
- }
149
- ],
150
- "SCRUBBER.PRESS_DOWN": {
151
- target: "scrubbing",
152
- actions: ["focusInput", "setHint", "setCursorPoint"]
153
- },
154
- "INPUT.FOCUS": {
155
- target: "focused",
156
- actions: ["focusInput", "invokeOnFocus"]
157
- }
158
- }
159
- },
160
- focused: {
161
- tags: ["focus"],
162
- effects: ["attachWheelListener"],
163
- on: {
164
- "TRIGGER.PRESS_DOWN": [
165
- { guard: "isTouchPointer", target: "pressed", actions: ["setHint"] },
166
- { target: "pressed", actions: ["focusInput", "setHint"] }
167
- ],
168
- "SCRUBBER.PRESS_DOWN": {
169
- target: "scrubbing",
170
- actions: ["focusInput", "setHint", "setCursorPoint"]
171
- },
172
- "INPUT.ARROW_UP": {
173
- actions: ["increment", "invokeOnValueCommit"]
174
- },
175
- "INPUT.ARROW_DOWN": {
176
- actions: ["decrement", "invokeOnValueCommit"]
177
- },
178
- "INPUT.HOME": {
179
- actions: ["decrementToMin", "invokeOnValueCommit"]
180
- },
181
- "INPUT.END": {
182
- actions: ["incrementToMax", "invokeOnValueCommit"]
183
- },
184
- "INPUT.CHANGE": {
185
- actions: ["setValue", "setHint"]
186
- },
187
- "INPUT.BLUR": [
188
- {
189
- guard: and("clampValueOnBlur", not("isValueEmpty"), not("isInRange")),
190
- target: "idle",
191
- actions: ["setClampedValue", "clearHint", "invokeOnBlur", "invokeOnValueCommit"]
192
- },
193
- {
194
- guard: not("isInRange"),
195
- target: "idle",
196
- actions: ["setFormattedValue", "clearHint", "invokeOnBlur", "invokeOnValueCommit"]
197
- },
198
- {
199
- target: "idle",
200
- actions: ["setFormattedValue", "clearHint", "invokeOnBlur", "invokeOnValueCommit"]
201
- }
202
- ],
203
- // No target, so the input stays focused. It must not report a blur.
204
- "INPUT.ENTER": {
205
- actions: ["setFormattedValue", "clearHint", "invokeOnValueCommit"]
206
- }
207
- }
208
- },
209
- pressed: {
210
- tags: ["focus"],
211
- initial: "waiting",
212
- effects: ["trackButtonDisabled", "preventContextMenu"],
213
- on: {
214
- "TRIGGER.PRESS_UP": [
215
- { guard: "isTouchPointer", target: "focused", actions: ["clearHint", "invokeOnValueCommit"] },
216
- { target: "focused", actions: ["focusInput", "clearHint", "invokeOnValueCommit"] }
217
- ]
218
- },
219
- states: {
220
- waiting: {
221
- effects: ["waitForChangeDelay"],
222
- entry: choose([
223
- { guard: "isIncrementHint", actions: ["increment"] },
224
- { guard: "isDecrementHint", actions: ["decrement"] }
225
- ]),
226
- on: {
227
- CHANGE_DELAY: {
228
- target: "repeating",
229
- guard: and("isInRange", "spinOnPress")
230
- }
231
- }
232
- },
233
- repeating: {
234
- effects: ["spinValue"],
235
- on: {
236
- SPIN: [
237
- {
238
- guard: "isIncrementHint",
239
- actions: ["increment"]
240
- },
241
- {
242
- guard: "isDecrementHint",
243
- actions: ["decrement"]
244
- }
245
- ]
246
- }
247
- }
248
- }
249
- },
250
- scrubbing: {
251
- tags: ["focus"],
252
- effects: ["activatePointerLock", "trackMousemove", "preventTextSelection", "trackVisualViewport"],
253
- entry: ["clearCumulativeDelta"],
254
- on: {
255
- "SCRUBBER.STEP": [
256
- {
257
- guard: "isIncrementHint",
258
- actions: ["increment"]
259
- },
260
- {
261
- guard: "isDecrementHint",
262
- actions: ["decrement"]
263
- }
264
- ],
265
- "SCRUBBER.POINTER_UP": {
266
- target: "focused",
267
- actions: ["focusInput", "clearCursorPoint", "clearCumulativeDelta", "invokeOnValueCommit"]
268
- },
269
- "SCRUBBER.POINTER_MOVE": {
270
- actions: ["accumulateDelta", "setCursorPoint"]
271
- }
272
- }
273
- }
274
- },
275
- implementations: {
276
- guards: {
277
- clampValueOnBlur: ({ prop }) => prop("clampValueOnBlur"),
278
- spinOnPress: ({ prop }) => !!prop("spinOnPress"),
279
- isInRange: ({ computed }) => !computed("isOutOfRange"),
280
- isValueEmpty: ({ computed }) => computed("isValueEmpty"),
281
- isDecrementHint: ({ context, event }) => (event.hint ?? context.get("hint")) === "decrement",
282
- isIncrementHint: ({ context, event }) => (event.hint ?? context.get("hint")) === "increment",
283
- isTouchPointer: ({ event }) => event.pointerType === "touch"
284
- },
285
- effects: {
286
- waitForChangeDelay({ send }) {
287
- const id = setTimeout(() => {
288
- send({ type: "CHANGE_DELAY" });
289
- }, 300);
290
- return () => clearTimeout(id);
291
- },
292
- preventContextMenu({ scope }) {
293
- return addDomEvent(scope.getWin(), "contextmenu", (event) => event.preventDefault());
294
- },
295
- spinValue({ send, context }) {
296
- const id = setInterval(() => {
297
- const src = context.get("hint") === "increment" ? "increment-press" : "decrement-press";
298
- send({ type: "SPIN", src });
299
- }, 50);
300
- return () => clearInterval(id);
301
- },
302
- detectPointerLock({ context }) {
303
- context.set("isPointerLockSupported", !isSafari());
304
- },
305
- trackFormControl({ context, scope }) {
306
- const inputEl = dom.getInputEl(scope);
307
- return trackFormControl(inputEl, {
308
- onFieldsetDisabledChange(disabled) {
309
- context.set("fieldsetDisabled", disabled);
310
- },
311
- onFormReset() {
312
- context.set("value", context.initial("value"));
313
- }
314
- });
315
- },
316
- preventTextSelection({ scope, prop }) {
317
- return dom.preventTextSelection(scope, prop("scrubberDirection"));
318
- },
319
- trackButtonDisabled({ context, scope, send }) {
320
- const hint = context.get("hint");
321
- const btn = dom.getPressedTriggerEl(scope, hint);
322
- return observeAttributes(btn, {
323
- attributes: ["disabled"],
324
- callback() {
325
- const src = hint === "increment" ? "increment-press" : "decrement-press";
326
- send({ type: "TRIGGER.PRESS_UP", src });
327
- }
328
- });
329
- },
330
- attachWheelListener({ scope, send, prop }) {
331
- const inputEl = dom.getInputEl(scope);
332
- if (!inputEl || !scope.isActiveElement(inputEl) || !prop("allowMouseWheel")) return;
333
- function onWheel(event) {
334
- event.preventDefault();
335
- const dir = Math.sign(event.deltaY) * -1;
336
- if (dir === 1) {
337
- send({ type: "VALUE.INCREMENT", src: "wheel" });
338
- } else if (dir === -1) {
339
- send({ type: "VALUE.DECREMENT", src: "wheel" });
340
- }
341
- }
342
- return addDomEvent(inputEl, "wheel", onWheel, { passive: false });
343
- },
344
- trackVisualViewport({ scope, context }) {
345
- const vV = scope.getWin().visualViewport;
346
- if (!vV) return;
347
- function onResize() {
348
- context.set("visualScale", vV.scale);
349
- }
350
- onResize();
351
- return addDomEvent(vV, "resize", onResize);
352
- },
353
- activatePointerLock({ scope }) {
354
- if (isSafari()) return;
355
- const cleanup = requestPointerLock(scope.getDoc());
356
- return () => {
357
- if (isFirefox()) {
358
- setTimeout(() => cleanup?.(), 20);
359
- } else {
360
- cleanup?.();
361
- }
362
- };
363
- },
364
- trackMousemove({ scope, send, context, computed, prop }) {
365
- const doc = scope.getDoc();
366
- function onMousemove(event) {
367
- const point = context.get("scrubberCursorPoint");
368
- const isRtl = computed("isRtl");
369
- const direction = prop("scrubberDirection");
370
- const teleportDistance = prop("scrubberTeleportDistance");
371
- const value = dom.getMousemoveValue(scope, { point, isRtl, event, direction, teleportDistance });
372
- send({
373
- type: "SCRUBBER.POINTER_MOVE",
374
- hint: value.hint,
375
- point: value.point,
376
- delta: value.delta
377
- });
378
- }
379
- function onMouseup() {
380
- send({ type: "SCRUBBER.POINTER_UP", src: "scrub" });
381
- }
382
- return callAll(addDomEvent(doc, "mousemove", onMousemove, false), addDomEvent(doc, "mouseup", onMouseup, false));
383
- }
384
- },
385
- actions: {
386
- focusInput({ scope, prop }) {
387
- if (!prop("focusInputOnChange")) return;
388
- const inputEl = dom.getInputEl(scope);
389
- if (scope.isActiveElement(inputEl)) return;
390
- raf(() => inputEl?.focus({ preventScroll: true }));
391
- },
392
- increment({ context, event, prop, computed }) {
393
- let nextValue = incrementValue(computed("valueAsNumber"), event.step ?? prop("step"));
394
- if (!prop("allowOverflow")) nextValue = clampValue(nextValue, prop("min"), prop("max"));
395
- if (prop("snapOnStep"))
396
- nextValue = snapValueToStep(nextValue, prop("min"), prop("max"), event.step ?? prop("step"));
397
- context.set("value", formatValue(nextValue, { computed, prop }));
398
- },
399
- decrement({ context, event, prop, computed }) {
400
- let nextValue = decrementValue(computed("valueAsNumber"), event.step ?? prop("step"));
401
- if (!prop("allowOverflow")) nextValue = clampValue(nextValue, prop("min"), prop("max"));
402
- if (prop("snapOnStep"))
403
- nextValue = snapValueToStep(nextValue, prop("min"), prop("max"), event.step ?? prop("step"));
404
- context.set("value", formatValue(nextValue, { computed, prop }));
405
- },
406
- setClampedValue({ context, prop, computed }) {
407
- const nextValue = clampValue(computed("valueAsNumber"), prop("min"), prop("max"));
408
- context.set("value", formatValue(nextValue, { computed, prop }));
409
- },
410
- setRawValue({ context, event, prop, computed }) {
411
- let nextValue = typeof event.value === "number" ? event.value : parseValue(event.value, { computed, prop });
412
- if (!prop("allowOverflow")) nextValue = clampValue(nextValue, prop("min"), prop("max"));
413
- context.set("value", formatValue(nextValue, { computed, prop }));
414
- },
415
- setValue({ context, event }) {
416
- const value = event.target?.value ?? event.value;
417
- context.set("value", value);
418
- },
419
- clearValue({ context }) {
420
- context.set("value", "");
421
- },
422
- incrementToMax({ context, prop, computed }) {
423
- const value = formatValue(prop("max"), { computed, prop });
424
- context.set("value", value);
425
- },
426
- decrementToMin({ context, prop, computed }) {
427
- const value = formatValue(prop("min"), { computed, prop });
428
- context.set("value", value);
429
- },
430
- setHint({ context, event }) {
431
- context.set("hint", event.hint);
432
- },
433
- clearHint({ context }) {
434
- context.set("hint", null);
435
- },
436
- invokeOnFocus({ computed, prop }) {
437
- prop("onFocusChange")?.({
438
- focused: true,
439
- value: computed("formattedValue"),
440
- valueAsNumber: computed("valueAsNumber")
441
- });
442
- },
443
- invokeOnBlur({ computed, prop }) {
444
- prop("onFocusChange")?.({
445
- focused: false,
446
- value: computed("formattedValue"),
447
- valueAsNumber: computed("valueAsNumber")
448
- });
449
- },
450
- invokeOnInvalid({ computed, prop }) {
451
- const reason = computed("valueAsNumber") > prop("max") ? "rangeOverflow" : "rangeUnderflow";
452
- prop("onValueInvalid")?.({
453
- reason,
454
- value: computed("formattedValue"),
455
- valueAsNumber: computed("valueAsNumber")
456
- });
457
- },
458
- invokeOnValueCommit({ computed, prop, event }) {
459
- prop("onValueCommit")?.({
460
- value: computed("formattedValue"),
461
- valueAsNumber: computed("valueAsNumber"),
462
- reason: event.src
463
- });
464
- },
465
- syncInputElement({ context, event, computed, scope }) {
466
- const value = event.type.endsWith("CHANGE") ? context.get("value") : computed("formattedValue");
467
- const inputEl = dom.getInputEl(scope);
468
- const sel = event.selection ?? recordCursor(inputEl, scope);
469
- raf(() => {
470
- setElementValue(inputEl, value);
471
- restoreCursor(inputEl, sel, scope);
472
- });
473
- },
474
- setFormattedValue({ context, computed, action }) {
475
- context.set("value", computed("formattedValue"));
476
- action(["syncInputElement"]);
477
- },
478
- setCursorPoint({ context, event }) {
479
- context.set("scrubberCursorPoint", event.point);
480
- },
481
- clearCursorPoint({ context }) {
482
- context.set("scrubberCursorPoint", null);
483
- },
484
- setVirtualCursorPosition({ context, scope }) {
485
- const scrubberEl = dom.getScrubberEl(scope);
486
- const point = context.get("scrubberCursorPoint");
487
- if (!scrubberEl || !point) return;
488
- scrubberEl.style.setProperty("--scrubber-x", `${point.x}px`);
489
- scrubberEl.style.setProperty("--scrubber-y", `${point.y}px`);
490
- },
491
- accumulateDelta({ context, event, prop, send }) {
492
- const delta = event.delta ?? 0;
493
- const newDelta = context.get("cumulativeDelta") + delta;
494
- const sensitivity = prop("scrubberPixelSensitivity");
495
- if (Math.abs(newDelta) >= sensitivity) {
496
- const step = prop("step");
497
- const hint = event.hint;
498
- if (hint === "increment" || hint === "decrement") {
499
- send({ type: "SCRUBBER.STEP", step, hint, src: "scrub" });
500
- }
501
- context.set("cumulativeDelta", newDelta % sensitivity);
502
- } else {
503
- context.set("cumulativeDelta", newDelta);
504
- }
505
- },
506
- clearCumulativeDelta({ context }) {
507
- context.set("cumulativeDelta", 0);
508
- }
509
- }
510
- }
6
+ // src/number-input.machine.ts
7
+ const { choose, guards, createMachine } = setup();
8
+ const { not, and } = guards;
9
+ const machine = createMachine({
10
+ props({ props }) {
11
+ const step = getDefaultStep(props.step, props.formatOptions);
12
+ return {
13
+ dir: "ltr",
14
+ locale: "en-US",
15
+ focusInputOnChange: true,
16
+ allowOutOfRange: false,
17
+ pattern: "-?[0-9]*(.[0-9]+)?",
18
+ defaultValue: null,
19
+ step,
20
+ spinOnPress: true,
21
+ scrubberPixelSensitivity: 2,
22
+ scrubberDirection: "horizontal",
23
+ snapOnStep: false,
24
+ ...props,
25
+ largeStep: props.largeStep ?? 10 * step,
26
+ smallStep: props.smallStep ?? step / 10
27
+ };
28
+ },
29
+ initialState() {
30
+ return "idle";
31
+ },
32
+ refs({ prop }) {
33
+ return {
34
+ syncFrame: AnimationFrame.create(),
35
+ pressDirection: 1,
36
+ focusFrame: AnimationFrame.create(),
37
+ committedValue: prop("value") ?? prop("defaultValue") ?? null
38
+ };
39
+ },
40
+ exit: ["cancelFrames"],
41
+ context({ prop, bindable, getComputed, getEvent }) {
42
+ return {
43
+ value: bindable(() => ({
44
+ defaultValue: prop("defaultValue"),
45
+ value: prop("value"),
46
+ onChange(value) {
47
+ const formattedValue = formatValue(value, {
48
+ computed: getComputed(),
49
+ prop
50
+ });
51
+ prop("onValueChange")?.({
52
+ value,
53
+ formattedValue,
54
+ reason: getEvent().src
55
+ });
56
+ }
57
+ })),
58
+ inputValue: bindable(() => ({ defaultValue: formatNumber(prop("value") ?? prop("defaultValue"), createFormatter(prop("locale"), prop("formatOptions")), prop("formatOptions")) })),
59
+ scrubberCursorPoint: bindable(() => ({
60
+ defaultValue: null,
61
+ hash(value) {
62
+ return value ? `x:${value.x}, y:${value.y}` : "";
63
+ }
64
+ })),
65
+ fieldsetDisabled: bindable(() => ({ defaultValue: false })),
66
+ cumulativeDelta: bindable(() => ({ defaultValue: 0 })),
67
+ platform: bindable(() => ({ defaultValue: {
68
+ iPhone: false,
69
+ ios: false,
70
+ supportsPointerLock: false
71
+ } })),
72
+ visualScale: bindable(() => ({ defaultValue: 1 }))
73
+ };
74
+ },
75
+ computed: {
76
+ isRtl: ({ prop }) => prop("dir") === "rtl",
77
+ min: ({ prop }) => prop("min") ?? -1e400,
78
+ max: ({ prop }) => prop("max") ?? 1e400,
79
+ formattedValue: ({ context, computed, prop }) => formatValue(context.get("value"), {
80
+ computed,
81
+ prop
82
+ }),
83
+ isAtMin: ({ context, computed }) => {
84
+ const value = context.get("value");
85
+ return value != null && value <= computed("min");
86
+ },
87
+ isAtMax: ({ context, computed }) => {
88
+ const value = context.get("value");
89
+ return value != null && value >= computed("max");
90
+ },
91
+ isOutOfRange: ({ context, prop }) => {
92
+ const value = context.get("value");
93
+ return value != null && !isValueWithinRange(value, prop("min"), prop("max"));
94
+ },
95
+ isValueEmpty: ({ context }) => context.get("value") == null,
96
+ isDisabled: ({ prop, context }) => !!prop("disabled") || context.get("fieldsetDisabled"),
97
+ canIncrement: ({ computed }) => !computed("isAtMax"),
98
+ canDecrement: ({ computed }) => !computed("isAtMin"),
99
+ formatter: memo(({ prop }) => [prop("locale"), prop("formatOptions")], ([locale, formatOptions]) => createFormatter(locale, formatOptions)),
100
+ parser: memo(({ prop }) => [prop("locale"), prop("formatOptions")], ([locale, formatOptions]) => createParser(locale, formatOptions))
101
+ },
102
+ watch({ track, action, context, computed, prop }) {
103
+ track([
104
+ () => context.get("value"),
105
+ () => prop("locale"),
106
+ () => JSON.stringify(prop("formatOptions"))
107
+ ], () => {
108
+ action(["syncInputValue", "syncHiddenInput"]);
109
+ });
110
+ track([() => context.get("inputValue")], () => {
111
+ action(["syncInputValue", "syncInputElement"]);
112
+ });
113
+ track([() => computed("isOutOfRange")], () => {
114
+ if (!computed("isOutOfRange")) return;
115
+ action(["invokeOnInvalid"]);
116
+ });
117
+ track([() => context.hash("scrubberCursorPoint")], () => {
118
+ action(["setVirtualCursorPosition"]);
119
+ });
120
+ },
121
+ effects: ["trackFormControl", "detectPlatform"],
122
+ on: {
123
+ "INPUT.FOCUS": { actions: ["invokeOnFocus"] },
124
+ "VALUE.SET": { actions: ["setRawValue", "invokeOnValueCommit"] },
125
+ "VALUE.CLEAR": { actions: ["clearValue", "invokeOnValueCommit"] },
126
+ "VALUE.INCREMENT": { actions: ["increment", "invokeOnValueCommit"] },
127
+ "VALUE.DECREMENT": { actions: ["decrement", "invokeOnValueCommit"] }
128
+ },
129
+ states: {
130
+ idle: { on: {
131
+ "TRIGGER.PRESS_DOWN": [{
132
+ guard: "isTouchPointer",
133
+ target: "pressed",
134
+ actions: ["setPressDirection"]
135
+ }, {
136
+ target: "pressed",
137
+ actions: ["focusInput", "setPressDirection"]
138
+ }],
139
+ "SCRUBBER.PRESS_DOWN": {
140
+ target: "scrubbing",
141
+ actions: ["focusInput", "setCursorPoint"]
142
+ },
143
+ "INPUT.FOCUS": {
144
+ target: "focused",
145
+ actions: ["focusInput", "invokeOnFocus"]
146
+ }
147
+ } },
148
+ focused: {
149
+ tags: ["focus"],
150
+ effects: ["attachWheelListener"],
151
+ on: {
152
+ "TRIGGER.PRESS_DOWN": [{
153
+ guard: "isTouchPointer",
154
+ target: "pressed",
155
+ actions: ["setPressDirection"]
156
+ }, {
157
+ target: "pressed",
158
+ actions: ["focusInput", "setPressDirection"]
159
+ }],
160
+ "SCRUBBER.PRESS_DOWN": {
161
+ target: "scrubbing",
162
+ actions: ["focusInput", "setCursorPoint"]
163
+ },
164
+ "INPUT.ARROW_UP": { actions: ["increment", "invokeOnValueCommit"] },
165
+ "INPUT.ARROW_DOWN": { actions: ["decrement", "invokeOnValueCommit"] },
166
+ "INPUT.HOME": { actions: ["decrementToMin", "invokeOnValueCommit"] },
167
+ "INPUT.END": { actions: ["incrementToMax", "invokeOnValueCommit"] },
168
+ "INPUT.CHANGE": { actions: ["setInputValue"] },
169
+ "INPUT.BLUR": [{
170
+ guard: and(not("allowOutOfRange"), not("isInRange")),
171
+ target: "idle",
172
+ actions: [
173
+ "setClampedValue",
174
+ "invokeOnBlur",
175
+ "invokeOnValueCommit"
176
+ ]
177
+ }, {
178
+ target: "idle",
179
+ actions: [
180
+ "setFormattedValue",
181
+ "invokeOnBlur",
182
+ "invokeOnValueCommit"
183
+ ]
184
+ }],
185
+ "INPUT.ENTER": [{
186
+ guard: and(not("allowOutOfRange"), not("isInRange")),
187
+ actions: ["setClampedValue", "invokeOnValueCommit"]
188
+ }, { actions: ["setFormattedValue", "invokeOnValueCommit"] }]
189
+ }
190
+ },
191
+ pressed: {
192
+ tags: ["focus"],
193
+ initial: "waiting",
194
+ effects: ["trackButtonDisabled", "preventContextMenu"],
195
+ on: { "TRIGGER.PRESS_UP": [{
196
+ guard: "isTouchPointer",
197
+ target: "focused",
198
+ actions: ["invokeOnValueCommit"]
199
+ }, {
200
+ target: "focused",
201
+ actions: ["focusInput", "invokeOnValueCommit"]
202
+ }] },
203
+ states: {
204
+ waiting: {
205
+ effects: ["waitForChangeDelay"],
206
+ entry: choose([{
207
+ guard: not("isTouchPointer"),
208
+ actions: ["step"]
209
+ }]),
210
+ on: {
211
+ "TRIGGER.PRESS_UP": [
212
+ {
213
+ guard: and("isTouchPointer", "isTouchTap"),
214
+ target: "focused",
215
+ actions: ["step", "invokeOnValueCommit"]
216
+ },
217
+ {
218
+ guard: "isTouchPointer",
219
+ target: "focused"
220
+ },
221
+ {
222
+ target: "focused",
223
+ actions: ["focusInput", "invokeOnValueCommit"]
224
+ }
225
+ ],
226
+ CHANGE_DELAY: {
227
+ target: "repeating",
228
+ guard: and("isInRange", "spinOnPress")
229
+ }
230
+ }
231
+ },
232
+ repeating: {
233
+ effects: ["spinValue"],
234
+ on: { SPIN: { actions: ["step"] } }
235
+ }
236
+ }
237
+ },
238
+ scrubbing: {
239
+ tags: ["focus"],
240
+ effects: [
241
+ "activatePointerLock",
242
+ "trackMousemove",
243
+ "preventTextSelection",
244
+ "trackVisualViewport"
245
+ ],
246
+ entry: ["clearCumulativeDelta"],
247
+ on: {
248
+ "SCRUBBER.STEP": { actions: ["step"] },
249
+ "SCRUBBER.POINTER_UP": {
250
+ target: "focused",
251
+ actions: [
252
+ "focusInput",
253
+ "clearCursorPoint",
254
+ "clearCumulativeDelta",
255
+ "invokeOnValueCommit"
256
+ ]
257
+ },
258
+ "SCRUBBER.POINTER_MOVE": { actions: ["setCursorPoint", "accumulateDelta"] }
259
+ }
260
+ }
261
+ },
262
+ implementations: {
263
+ guards: {
264
+ allowOutOfRange: ({ prop }) => !!prop("allowOutOfRange"),
265
+ spinOnPress: ({ prop }) => !!prop("spinOnPress"),
266
+ isInRange: ({ computed }) => !computed("isOutOfRange"),
267
+ isTouchPointer: ({ event }) => event.pointerType === "touch",
268
+ isTouchTap: ({ event }) => !event.cancelled
269
+ },
270
+ effects: {
271
+ waitForChangeDelay({ send }) {
272
+ const id = setTimeout(() => {
273
+ send({ type: "CHANGE_DELAY" });
274
+ }, 400);
275
+ return () => clearTimeout(id);
276
+ },
277
+ preventContextMenu({ scope }) {
278
+ return addDomEvent(scope.getWin(), "contextmenu", (event) => event.preventDefault());
279
+ },
280
+ spinValue({ send, refs }) {
281
+ const id = setInterval(() => {
282
+ send({
283
+ type: "SPIN",
284
+ src: getPressSource(refs.get("pressDirection"))
285
+ });
286
+ }, 60);
287
+ return () => clearInterval(id);
288
+ },
289
+ detectPlatform({ context }) {
290
+ context.set("platform", {
291
+ iPhone: isIPhone(),
292
+ ios: isIos(),
293
+ supportsPointerLock: !isSafari()
294
+ });
295
+ },
296
+ trackFormControl({ context, scope }) {
297
+ const inputEl = getHiddenInputEl(scope) ?? getInputEl(scope);
298
+ return trackFormControl(inputEl, {
299
+ onFieldsetDisabledChange(disabled) {
300
+ context.set("fieldsetDisabled", disabled);
301
+ },
302
+ onFormReset() {
303
+ context.set("value", context.initial("value") ?? null);
304
+ }
305
+ });
306
+ },
307
+ preventTextSelection({ scope, prop }) {
308
+ return preventTextSelection(scope, prop("scrubberDirection"));
309
+ },
310
+ trackButtonDisabled({ refs, scope, send }) {
311
+ const direction = refs.get("pressDirection");
312
+ const btn = getTriggerEl(scope, direction);
313
+ return observeAttributes(btn, {
314
+ attributes: ["disabled"],
315
+ callback() {
316
+ send({
317
+ type: "TRIGGER.PRESS_UP",
318
+ src: getPressSource(direction)
319
+ });
320
+ }
321
+ });
322
+ },
323
+ attachWheelListener({ scope, send, prop }) {
324
+ const inputEl = getInputEl(scope);
325
+ if (!inputEl || !scope.isActiveElement(inputEl) || !prop("allowMouseWheel")) return;
326
+ function onWheel(event) {
327
+ if (prop("readOnly")) return;
328
+ if (event.ctrlKey) return;
329
+ const isHorizontal = Math.abs(event.deltaX) > Math.abs(event.deltaY);
330
+ const delta = event.shiftKey && isHorizontal ? event.deltaX : event.deltaY;
331
+ if (delta === 0 || isHorizontal && !event.shiftKey) return;
332
+ event.preventDefault();
333
+ const step = event.altKey ? prop("smallStep") : event.shiftKey ? prop("largeStep") : prop("step");
334
+ send({
335
+ type: delta < 0 ? "VALUE.INCREMENT" : "VALUE.DECREMENT",
336
+ step,
337
+ src: "wheel"
338
+ });
339
+ }
340
+ return addDomEvent(inputEl, "wheel", onWheel, { passive: false });
341
+ },
342
+ trackVisualViewport({ scope, context }) {
343
+ const vV = scope.getWin().visualViewport;
344
+ if (!vV) return;
345
+ function onResize() {
346
+ context.set("visualScale", vV.scale);
347
+ }
348
+ onResize();
349
+ return addDomEvent(vV, "resize", onResize);
350
+ },
351
+ activatePointerLock({ scope }) {
352
+ if (isSafari()) return;
353
+ const cleanup = requestPointerLock(scope.getDoc());
354
+ return () => {
355
+ if (isFirefox()) setTimeout(() => cleanup?.(), 20);
356
+ else cleanup?.();
357
+ };
358
+ },
359
+ trackMousemove({ scope, send, context, computed, prop }) {
360
+ const doc = scope.getDoc();
361
+ function onMousemove(event) {
362
+ const point = context.get("scrubberCursorPoint");
363
+ const isRtl = computed("isRtl");
364
+ const axis = prop("scrubberDirection");
365
+ const teleportDistance = prop("scrubberTeleportDistance");
366
+ const value = getMousemoveValue(scope, {
367
+ point,
368
+ isRtl,
369
+ event,
370
+ axis,
371
+ teleportDistance
372
+ });
373
+ send({
374
+ type: "SCRUBBER.POINTER_MOVE",
375
+ direction: value.direction,
376
+ point: value.point,
377
+ delta: value.delta
378
+ });
379
+ }
380
+ function onMouseup() {
381
+ send({
382
+ type: "SCRUBBER.POINTER_UP",
383
+ src: "scrub"
384
+ });
385
+ }
386
+ return callAll(addDomEvent(doc, "mousemove", onMousemove, false), addDomEvent(doc, "mouseup", onMouseup, false));
387
+ }
388
+ },
389
+ actions: {
390
+ focusInput({ scope, prop, refs }) {
391
+ if (!prop("focusInputOnChange")) return;
392
+ const inputEl = getInputEl(scope);
393
+ if (scope.isActiveElement(inputEl)) return;
394
+ refs.get("focusFrame").request(() => inputEl?.focus({ preventScroll: true }));
395
+ },
396
+ cancelFrames({ refs }) {
397
+ refs.get("syncFrame").cancel();
398
+ refs.get("focusFrame").cancel();
399
+ },
400
+ increment({ event, prop, computed, context }) {
401
+ const value = context.get("value");
402
+ const step = event.step ?? prop("step");
403
+ const next = value == null ? 0 : incrementValue(value, step);
404
+ setNumber({
405
+ context,
406
+ prop,
407
+ computed
408
+ }, getStepValue(next, step, 1, {
409
+ prop,
410
+ computed
411
+ }));
412
+ },
413
+ decrement({ event, prop, computed, context }) {
414
+ const value = context.get("value");
415
+ const step = event.step ?? prop("step");
416
+ const next = value == null ? 0 : decrementValue(value, step);
417
+ setNumber({
418
+ context,
419
+ prop,
420
+ computed
421
+ }, getStepValue(next, step, -1, {
422
+ prop,
423
+ computed
424
+ }));
425
+ },
426
+ setClampedValue({ context, prop, computed }) {
427
+ const value = context.get("value");
428
+ setNumber({
429
+ context,
430
+ prop,
431
+ computed
432
+ }, value == null ? null : clampValue(value, computed("min"), computed("max")));
433
+ },
434
+ setRawValue({ context, event, prop, computed }) {
435
+ let value = event.value;
436
+ if (!prop("allowOutOfRange")) value = clampValue(value, computed("min"), computed("max"));
437
+ setNumber({
438
+ context,
439
+ prop,
440
+ computed
441
+ }, value);
442
+ },
443
+ setInputValue({ context, event, computed, prop }) {
444
+ const text = event.value;
445
+ context.set("inputValue", text);
446
+ if (text.trim() === "") {
447
+ context.set("value", null);
448
+ return;
449
+ }
450
+ const value = parseValue(text, {
451
+ computed,
452
+ prop
453
+ });
454
+ if (!Number.isNaN(value)) context.set("value", normalizeZero(value));
455
+ },
456
+ clearValue({ context }) {
457
+ context.set("value", null);
458
+ context.set("inputValue", "");
459
+ },
460
+ incrementToMax({ context, prop, computed }) {
461
+ setNumber({
462
+ context,
463
+ prop,
464
+ computed
465
+ }, computed("max"));
466
+ },
467
+ decrementToMin({ context, prop, computed }) {
468
+ setNumber({
469
+ context,
470
+ prop,
471
+ computed
472
+ }, computed("min"));
473
+ },
474
+ setPressDirection({ refs, event }) {
475
+ refs.set("pressDirection", event.direction);
476
+ },
477
+ step({ event, refs, action }) {
478
+ action([(event.direction ?? refs.get("pressDirection")) > 0 ? "increment" : "decrement"]);
479
+ },
480
+ invokeOnFocus({ context, computed, prop }) {
481
+ prop("onFocusChange")?.({
482
+ focused: true,
483
+ value: context.get("value"),
484
+ formattedValue: computed("formattedValue")
485
+ });
486
+ },
487
+ invokeOnBlur({ context, computed, prop }) {
488
+ prop("onFocusChange")?.({
489
+ focused: false,
490
+ value: context.get("value"),
491
+ formattedValue: computed("formattedValue")
492
+ });
493
+ },
494
+ invokeOnInvalid({ context, computed, prop }) {
495
+ const value = context.get("value");
496
+ if (value == null) return;
497
+ prop("onValueInvalid")?.({
498
+ reason: value > computed("max") ? "rangeOverflow" : "rangeUnderflow",
499
+ value,
500
+ formattedValue: computed("formattedValue")
501
+ });
502
+ },
503
+ invokeOnValueCommit({ context, computed, prop, event, refs }) {
504
+ const reason = event.src;
505
+ queueMicrotask(() => {
506
+ const value = context.get("value");
507
+ if (value === refs.get("committedValue")) return;
508
+ refs.set("committedValue", value);
509
+ prop("onValueCommit")?.({
510
+ value,
511
+ formattedValue: computed("formattedValue"),
512
+ reason
513
+ });
514
+ });
515
+ },
516
+ syncInputValue({ context, computed, prop, state }) {
517
+ const text = context.get("inputValue");
518
+ const formatted = computed("formattedValue");
519
+ if (text === formatted) return;
520
+ if (state.hasTag("focus") && representsValue(text, context.get("value"), {
521
+ computed,
522
+ prop
523
+ })) return;
524
+ context.set("inputValue", formatted);
525
+ },
526
+ syncInputElement({ context, event, scope, refs }) {
527
+ const value = context.get("inputValue");
528
+ const inputEl = getInputEl(scope);
529
+ const sel = event.selection ?? recordCursor(inputEl);
530
+ refs.get("syncFrame").request(() => {
531
+ const unchanged = inputEl?.value === value;
532
+ setElementValue(inputEl, value);
533
+ if (!unchanged) restoreCursor(inputEl, sel);
534
+ });
535
+ },
536
+ syncHiddenInput({ scope, context }) {
537
+ const value = context.get("value");
538
+ dispatchHiddenInputValue(scope, value == null ? "" : String(value));
539
+ },
540
+ setFormattedValue({ context, computed }) {
541
+ context.set("inputValue", computed("formattedValue"));
542
+ },
543
+ setCursorPoint({ context, event }) {
544
+ context.set("scrubberCursorPoint", event.point);
545
+ },
546
+ clearCursorPoint({ context }) {
547
+ context.set("scrubberCursorPoint", null);
548
+ },
549
+ setVirtualCursorPosition({ context, scope }) {
550
+ const scrubberEl = getScrubberEl(scope);
551
+ const point = context.get("scrubberCursorPoint");
552
+ if (!scrubberEl || !point) return;
553
+ scrubberEl.style.setProperty("--scrubber-x", `${point.x}px`);
554
+ scrubberEl.style.setProperty("--scrubber-y", `${point.y}px`);
555
+ },
556
+ accumulateDelta({ context, event, prop, send }) {
557
+ const delta = event.delta ?? 0;
558
+ const newDelta = context.get("cumulativeDelta") + delta;
559
+ const pixels = prop("scrubberPixelSensitivity");
560
+ const sensitivity = pixels > 0 ? pixels : 1;
561
+ if (Math.abs(newDelta) >= sensitivity) {
562
+ const step = prop("step");
563
+ if (event.direction) send({
564
+ type: "SCRUBBER.STEP",
565
+ step,
566
+ direction: event.direction,
567
+ src: "scrub"
568
+ });
569
+ context.set("cumulativeDelta", newDelta % sensitivity);
570
+ } else context.set("cumulativeDelta", newDelta);
571
+ },
572
+ clearCumulativeDelta({ context }) {
573
+ context.set("cumulativeDelta", 0);
574
+ }
575
+ }
576
+ }
511
577
  });
512
- export {
513
- machine
514
- };
578
+ const getPressSource = (direction) => direction > 0 ? "increment-trigger" : "decrement-trigger";
579
+ /** Sets the number and shows it formatted */
580
+ function setNumber({ context, prop, computed }, value) {
581
+ value = value == null ? null : normalizeZero(value);
582
+ context.set("value", value);
583
+ context.set("inputValue", formatValue(value, {
584
+ computed,
585
+ prop
586
+ }));
587
+ }
588
+ function getStepValue(value, step, direction, { prop, computed }) {
589
+ if (prop("snapOnStep")) value = snapToStep(value, prop("min") ?? 0, step, direction);
590
+ return clampValue(value, computed("min"), computed("max"));
591
+ }
592
+ function representsValue(text, value, params) {
593
+ if (text.trim() === "") return value == null;
594
+ const parsed = parseValue(text, params);
595
+ return Number.isNaN(parsed) || parsed === value;
596
+ }
597
+ const normalizeZero = (value) => value === 0 ? 0 : value;
598
+ export { machine };