@zag-js/number-input 0.0.0-20220802150625

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/dist/index.mjs ADDED
@@ -0,0 +1,970 @@
1
+ // ../../utilities/dom/dist/index.mjs
2
+ var dataAttr = (guard) => {
3
+ return guard ? "" : void 0;
4
+ };
5
+ var ariaAttr = (guard) => {
6
+ return guard ? "true" : void 0;
7
+ };
8
+ var MAX_Z_INDEX = 2147483647;
9
+ var runIfFn = (v, ...a) => {
10
+ const res = typeof v === "function" ? v(...a) : v;
11
+ return res ?? void 0;
12
+ };
13
+ var callAll = (...fns) => (...a) => {
14
+ fns.forEach(function(fn) {
15
+ fn == null ? void 0 : fn(...a);
16
+ });
17
+ };
18
+ var isArray = (v) => Array.isArray(v);
19
+ var isObject = (v) => !(v == null || typeof v !== "object" || isArray(v));
20
+ var hasProp = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);
21
+ var isDom = () => typeof window !== "undefined";
22
+ function getPlatform() {
23
+ const agent = navigator.userAgentData;
24
+ return (agent == null ? void 0 : agent.platform) ?? navigator.platform;
25
+ }
26
+ var pt = (v) => isDom() && v.test(getPlatform());
27
+ var vn = (v) => isDom() && v.test(navigator.vendor);
28
+ var isTouchDevice = () => isDom() && !!navigator.maxTouchPoints;
29
+ var isMac = () => pt(/^Mac/) && !isTouchDevice;
30
+ var isSafari = () => isApple() && vn(/apple/i);
31
+ var isApple = () => pt(/mac|iphone|ipad|ipod/i);
32
+ var isIos = () => isApple() && !isMac();
33
+ function isDocument(el) {
34
+ return el.nodeType === Node.DOCUMENT_NODE;
35
+ }
36
+ function isWindow(value) {
37
+ return (value == null ? void 0 : value.toString()) === "[object Window]";
38
+ }
39
+ function getDocument(el) {
40
+ if (isWindow(el))
41
+ return el.document;
42
+ if (isDocument(el))
43
+ return el;
44
+ return (el == null ? void 0 : el.ownerDocument) ?? document;
45
+ }
46
+ function defineDomHelpers(helpers) {
47
+ const dom2 = {
48
+ getRootNode: (ctx) => {
49
+ var _a;
50
+ return ((_a = ctx.getRootNode) == null ? void 0 : _a.call(ctx)) ?? document;
51
+ },
52
+ getDoc: (ctx) => getDocument(dom2.getRootNode(ctx)),
53
+ getWin: (ctx) => dom2.getDoc(ctx).defaultView ?? window,
54
+ getActiveElement: (ctx) => dom2.getDoc(ctx).activeElement,
55
+ getById: (ctx, id) => dom2.getRootNode(ctx).getElementById(id)
56
+ };
57
+ return {
58
+ ...dom2,
59
+ ...helpers
60
+ };
61
+ }
62
+ function getNativeEvent(e) {
63
+ return e.nativeEvent ?? e;
64
+ }
65
+ var supportsPointerEvent = () => isDom() && window.onpointerdown === null;
66
+ var isTouchEvent = (v) => isObject(v) && hasProp(v, "touches");
67
+ var isLeftClick = (v) => v.button === 0;
68
+ var isModifiedEvent = (v) => v.ctrlKey || v.altKey || v.metaKey;
69
+ function observeAttributes(node, attributes, fn) {
70
+ if (!node)
71
+ return;
72
+ const attrs = Array.isArray(attributes) ? attributes : [attributes];
73
+ const win = node.ownerDocument.defaultView || window;
74
+ const obs = new win.MutationObserver((changes) => {
75
+ for (const change of changes) {
76
+ if (change.type === "attributes" && change.attributeName && attrs.includes(change.attributeName)) {
77
+ fn(change);
78
+ }
79
+ }
80
+ });
81
+ obs.observe(node, { attributes: true, attributeFilter: attrs });
82
+ return () => obs.disconnect();
83
+ }
84
+ var fallback = {
85
+ pageX: 0,
86
+ pageY: 0,
87
+ clientX: 0,
88
+ clientY: 0
89
+ };
90
+ function getEventPoint(event, type = "page") {
91
+ const point = isTouchEvent(event) ? event.touches[0] ?? event.changedTouches[0] ?? fallback : event;
92
+ return { x: point[`${type}X`], y: point[`${type}Y`] };
93
+ }
94
+ var PAGE_KEYS = /* @__PURE__ */ new Set(["PageUp", "PageDown"]);
95
+ var ARROW_KEYS = /* @__PURE__ */ new Set(["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"]);
96
+ function getEventStep(event) {
97
+ if (event.ctrlKey || event.metaKey) {
98
+ return 0.1;
99
+ } else {
100
+ const isPageKey = PAGE_KEYS.has(event.key);
101
+ const isSkipKey = isPageKey || event.shiftKey && ARROW_KEYS.has(event.key);
102
+ return isSkipKey ? 10 : 1;
103
+ }
104
+ }
105
+ var isRef = (v) => hasProp(v, "current");
106
+ function addDomEvent(target, eventName, handler, options) {
107
+ const node = isRef(target) ? target.current : runIfFn(target);
108
+ node == null ? void 0 : node.addEventListener(eventName, handler, options);
109
+ return () => {
110
+ node == null ? void 0 : node.removeEventListener(eventName, handler, options);
111
+ };
112
+ }
113
+ function raf(fn) {
114
+ const id = globalThis.requestAnimationFrame(fn);
115
+ return function cleanup() {
116
+ globalThis.cancelAnimationFrame(id);
117
+ };
118
+ }
119
+ function addPointerlockChangeListener(doc, fn) {
120
+ return addDomEvent(doc, "pointerlockchange", fn, false);
121
+ }
122
+ function addPointerlockErrorListener(doc, fn) {
123
+ doc.addEventListener("pointerlockerror", fn, false);
124
+ return function cleanup() {
125
+ doc.removeEventListener("pointerlockerror", fn, false);
126
+ };
127
+ }
128
+ function requestPointerLock(doc, handlers = {}) {
129
+ const { onPointerLock, onPointerUnlock } = handlers;
130
+ const body = doc.body;
131
+ const supported = "pointerLockElement" in doc || "mozPointerLockElement" in doc;
132
+ const locked = !!doc.pointerLockElement;
133
+ function onPointerChange() {
134
+ if (locked)
135
+ onPointerLock == null ? void 0 : onPointerLock();
136
+ else
137
+ onPointerUnlock == null ? void 0 : onPointerUnlock();
138
+ }
139
+ function onPointerError(event) {
140
+ if (locked)
141
+ onPointerUnlock == null ? void 0 : onPointerUnlock();
142
+ console.error("PointerLock error occured:", event);
143
+ exit();
144
+ }
145
+ function exit() {
146
+ doc.exitPointerLock();
147
+ }
148
+ if (!supported)
149
+ return;
150
+ body.requestPointerLock();
151
+ const cleanup = callAll(
152
+ addPointerlockChangeListener(doc, onPointerChange),
153
+ addPointerlockErrorListener(doc, onPointerError)
154
+ );
155
+ return function dispose() {
156
+ if (!supported)
157
+ return;
158
+ cleanup();
159
+ exit();
160
+ };
161
+ }
162
+
163
+ // ../../utilities/number/dist/index.mjs
164
+ function wrap(num, max) {
165
+ return (num % max + max) % max;
166
+ }
167
+ function roundToDevicePixel(num) {
168
+ if (typeof window === "undefined")
169
+ return Math.round(num);
170
+ const dp = window.devicePixelRatio;
171
+ return Math.floor(num * dp + 0.5) / dp;
172
+ }
173
+ function clamp(v, o) {
174
+ return Math.min(Math.max(valueOf(v), o.min), o.max);
175
+ }
176
+ function countDecimals(value) {
177
+ if (!Number.isFinite(value))
178
+ return 0;
179
+ let e = 1, p = 0;
180
+ while (Math.round(value * e) / e !== value) {
181
+ e *= 10;
182
+ p += 1;
183
+ }
184
+ return p;
185
+ }
186
+ var increment = (v, s) => decimalOperation(valueOf(v), "+", s);
187
+ var decrement = (v, s) => decimalOperation(valueOf(v), "-", s);
188
+ function valueOf(v) {
189
+ if (typeof v === "number")
190
+ return v;
191
+ const num = parseFloat(v.toString().replace(/[^\w.-]+/g, ""));
192
+ return !Number.isNaN(num) ? num : 0;
193
+ }
194
+ function formatDecimal(v, o) {
195
+ return new Intl.NumberFormat("en-US", {
196
+ useGrouping: false,
197
+ style: "decimal",
198
+ minimumFractionDigits: o.minFractionDigits,
199
+ maximumFractionDigits: o.maxFractionDigits
200
+ }).format(valueOf(v));
201
+ }
202
+ function isAtMax(v, o) {
203
+ const val = valueOf(v);
204
+ return val >= o.max;
205
+ }
206
+ function isAtMin(v, o) {
207
+ const val = valueOf(v);
208
+ return val <= o.min;
209
+ }
210
+ function isWithinRange(v, o) {
211
+ const val = valueOf(v);
212
+ return val >= o.min && val <= o.max;
213
+ }
214
+ function decimalOperation(a, op, b) {
215
+ let result = op === "+" ? a + b : a - b;
216
+ if (a % 1 !== 0 || b % 1 !== 0) {
217
+ const multiplier = 10 ** Math.max(countDecimals(a), countDecimals(b));
218
+ a = Math.round(a * multiplier);
219
+ b = Math.round(b * multiplier);
220
+ result = op === "+" ? a + b : a - b;
221
+ result /= multiplier;
222
+ }
223
+ return result;
224
+ }
225
+ var nf = new Intl.NumberFormat("en-US", { style: "decimal", maximumFractionDigits: 20 });
226
+
227
+ // src/number-input.dom.ts
228
+ var dom = defineDomHelpers({
229
+ getRootId: (ctx) => {
230
+ var _a;
231
+ return ((_a = ctx.ids) == null ? void 0 : _a.root) ?? `number-input:${ctx.id}`;
232
+ },
233
+ getInputId: (ctx) => {
234
+ var _a;
235
+ return ((_a = ctx.ids) == null ? void 0 : _a.input) ?? `number-input:${ctx.id}:input`;
236
+ },
237
+ getIncButtonId: (ctx) => {
238
+ var _a;
239
+ return ((_a = ctx.ids) == null ? void 0 : _a.incBtn) ?? `number-input:${ctx.id}:inc-btn`;
240
+ },
241
+ getDecButtonId: (ctx) => {
242
+ var _a;
243
+ return ((_a = ctx.ids) == null ? void 0 : _a.decBtn) ?? `number-input:${ctx.id}:dec-btn`;
244
+ },
245
+ getScrubberId: (ctx) => {
246
+ var _a;
247
+ return ((_a = ctx.ids) == null ? void 0 : _a.scrubber) ?? `number-input:${ctx.id}:scrubber`;
248
+ },
249
+ getCursorId: (ctx) => `number-input:${ctx.id}:cursor`,
250
+ getLabelId: (ctx) => {
251
+ var _a;
252
+ return ((_a = ctx.ids) == null ? void 0 : _a.label) ?? `number-input:${ctx.id}:label`;
253
+ },
254
+ getInputEl: (ctx) => dom.getById(ctx, dom.getInputId(ctx)),
255
+ getIncButtonEl: (ctx) => dom.getById(ctx, dom.getIncButtonId(ctx)),
256
+ getDecButtonEl: (ctx) => dom.getById(ctx, dom.getDecButtonId(ctx)),
257
+ getScrubberEl: (ctx) => dom.getById(ctx, dom.getScrubberId(ctx)),
258
+ getCursorEl: (ctx) => dom.getDoc(ctx).getElementById(dom.getCursorId(ctx)),
259
+ getActiveButton: (ctx, hint = ctx.hint) => {
260
+ let btnEl = null;
261
+ if (hint === "increment") {
262
+ btnEl = dom.getIncButtonEl(ctx);
263
+ }
264
+ if (hint === "decrement") {
265
+ btnEl = dom.getDecButtonEl(ctx);
266
+ }
267
+ return btnEl;
268
+ },
269
+ setupVirtualCursor(ctx) {
270
+ if (isSafari() || !supportsPointerEvent())
271
+ return;
272
+ dom.createVirtualCursor(ctx);
273
+ return () => {
274
+ var _a;
275
+ (_a = dom.getCursorEl(ctx)) == null ? void 0 : _a.remove();
276
+ };
277
+ },
278
+ preventTextSelection(ctx) {
279
+ const doc = dom.getDoc(ctx);
280
+ const html = doc.documentElement;
281
+ const body = doc.body;
282
+ body.style.pointerEvents = "none";
283
+ html.style.userSelect = "none";
284
+ html.style.cursor = "ew-resize";
285
+ return () => {
286
+ body.style.pointerEvents = "";
287
+ html.style.userSelect = "";
288
+ html.style.cursor = "";
289
+ if (!html.style.length) {
290
+ html.removeAttribute("style");
291
+ }
292
+ if (!body.style.length) {
293
+ body.removeAttribute("style");
294
+ }
295
+ };
296
+ },
297
+ getMousementValue(ctx, event) {
298
+ const x = roundToDevicePixel(event.movementX);
299
+ const y = roundToDevicePixel(event.movementY);
300
+ let hint = x > 0 ? "increment" : x < 0 ? "decrement" : null;
301
+ if (ctx.isRtl && hint === "increment")
302
+ hint = "decrement";
303
+ if (ctx.isRtl && hint === "decrement")
304
+ hint = "increment";
305
+ const point = {
306
+ x: ctx.scrubberCursorPoint.x + x,
307
+ y: ctx.scrubberCursorPoint.y + y
308
+ };
309
+ const win = dom.getWin(ctx);
310
+ const width = win.innerWidth;
311
+ const half = roundToDevicePixel(7.5);
312
+ point.x = wrap(point.x + half, width) - half;
313
+ return { hint, point };
314
+ },
315
+ createVirtualCursor(ctx) {
316
+ const doc = dom.getDoc(ctx);
317
+ const el = doc.createElement("div");
318
+ el.className = "scrubber--cursor";
319
+ el.id = dom.getCursorId(ctx);
320
+ Object.assign(el.style, {
321
+ width: "15px",
322
+ height: "15px",
323
+ position: "fixed",
324
+ pointerEvents: "none",
325
+ left: "0px",
326
+ top: "0px",
327
+ zIndex: MAX_Z_INDEX,
328
+ transform: ctx.scrubberCursorPoint ? `translate3d(${ctx.scrubberCursorPoint.x}px, ${ctx.scrubberCursorPoint.y}px, 0px)` : void 0,
329
+ willChange: "transform"
330
+ });
331
+ el.innerHTML = `
332
+ <svg width="46" height="15" style="left: -15.5px; position: absolute; top: 0; filter: drop-shadow(rgba(0, 0, 0, 0.4) 0px 1px 1.1px);">
333
+ <g transform="translate(2 3)">
334
+ <path fill-rule="evenodd" d="M 15 4.5L 15 2L 11.5 5.5L 15 9L 15 6.5L 31 6.5L 31 9L 34.5 5.5L 31 2L 31 4.5Z" style="stroke-width: 2px; stroke: white;"></path>
335
+ <path fill-rule="evenodd" d="M 15 4.5L 15 2L 11.5 5.5L 15 9L 15 6.5L 31 6.5L 31 9L 34.5 5.5L 31 2L 31 4.5Z"></path>
336
+ </g>
337
+ </svg>`;
338
+ doc.body.appendChild(el);
339
+ }
340
+ });
341
+
342
+ // src/number-input.utils.ts
343
+ var utils = {
344
+ isValidNumericEvent: (ctx, event) => {
345
+ var _a;
346
+ if (event.key == null)
347
+ return true;
348
+ const isModifier = isModifiedEvent(event);
349
+ const isSingleKey = event.key.length === 1;
350
+ if (isModifier || !isSingleKey)
351
+ return true;
352
+ return ((_a = ctx.validateCharacter) == null ? void 0 : _a.call(ctx, event.key)) ?? utils.isFloatingPoint(event.key);
353
+ },
354
+ isFloatingPoint: (v) => /^[Ee0-9+\-.]$/.test(v),
355
+ sanitize: (ctx, value) => {
356
+ return value.split("").filter(ctx.validateCharacter ?? utils.isFloatingPoint).join("");
357
+ },
358
+ increment: (ctx, step) => {
359
+ const value = increment(ctx.value, step ?? ctx.step);
360
+ return formatDecimal(clamp(value, ctx), ctx);
361
+ },
362
+ decrement: (ctx, step) => {
363
+ const value = decrement(ctx.value, step ?? ctx.step);
364
+ return formatDecimal(clamp(value, ctx), ctx);
365
+ },
366
+ clamp: (ctx) => {
367
+ return formatDecimal(clamp(ctx.value, ctx), ctx);
368
+ },
369
+ parse: (ctx, value) => {
370
+ var _a;
371
+ return ((_a = ctx.parse) == null ? void 0 : _a.call(ctx, value)) ?? value;
372
+ },
373
+ format: (ctx, value) => {
374
+ var _a;
375
+ const _val = value.toString();
376
+ return ((_a = ctx.format) == null ? void 0 : _a.call(ctx, _val)) ?? _val;
377
+ },
378
+ round: (ctx) => {
379
+ return formatDecimal(ctx.value, ctx);
380
+ }
381
+ };
382
+
383
+ // src/number-input.connect.ts
384
+ function connect(state, send, normalize) {
385
+ const isFocused = state.hasTag("focus");
386
+ const isInvalid = state.context.isOutOfRange || !!state.context.invalid;
387
+ const isDisabled = !!state.context.disabled;
388
+ const isValueEmpty = state.context.isValueEmpty;
389
+ const isIncrementDisabled = isDisabled || !state.context.canIncrement;
390
+ const isDecrementDisabled = isDisabled || !state.context.canDecrement;
391
+ const messages = state.context.messages;
392
+ return {
393
+ isFocused,
394
+ isInvalid,
395
+ isValueEmpty,
396
+ value: state.context.formattedValue,
397
+ valueAsNumber: state.context.valueAsNumber,
398
+ setValue(value) {
399
+ send({ type: "SET_VALUE", value: value.toString() });
400
+ },
401
+ clearValue() {
402
+ send("CLEAR_VALUE");
403
+ },
404
+ increment() {
405
+ send("INCREMENT");
406
+ },
407
+ decrement() {
408
+ send("DECREMENT");
409
+ },
410
+ setToMax() {
411
+ send({ type: "SET_VALUE", value: state.context.max });
412
+ },
413
+ setToMin() {
414
+ send({ type: "SET_VALUE", value: state.context.min });
415
+ },
416
+ focus() {
417
+ var _a;
418
+ (_a = dom.getInputEl(state.context)) == null ? void 0 : _a.focus();
419
+ },
420
+ blur() {
421
+ var _a;
422
+ (_a = dom.getInputEl(state.context)) == null ? void 0 : _a.blur();
423
+ },
424
+ rootProps: normalize.element({
425
+ id: dom.getRootId(state.context),
426
+ "data-part": "root",
427
+ "data-disabled": dataAttr(isDisabled)
428
+ }),
429
+ labelProps: normalize.label({
430
+ "data-part": "label",
431
+ "data-disabled": dataAttr(isDisabled),
432
+ "data-invalid": dataAttr(isInvalid),
433
+ id: dom.getLabelId(state.context),
434
+ htmlFor: dom.getInputId(state.context)
435
+ }),
436
+ groupProps: normalize.element({
437
+ "data-part": "group",
438
+ role: "group",
439
+ "aria-disabled": isDisabled,
440
+ "data-disabled": dataAttr(isDisabled),
441
+ "data-invalid": dataAttr(isInvalid),
442
+ "aria-invalid": ariaAttr(state.context.invalid)
443
+ }),
444
+ inputProps: normalize.input({
445
+ "data-part": "input",
446
+ name: state.context.name,
447
+ id: dom.getInputId(state.context),
448
+ role: "spinbutton",
449
+ value: state.context.formattedValue,
450
+ pattern: state.context.pattern,
451
+ inputMode: state.context.inputMode,
452
+ "aria-invalid": isInvalid || void 0,
453
+ "data-invalid": dataAttr(isInvalid),
454
+ disabled: isDisabled,
455
+ "data-disabled": dataAttr(isDisabled),
456
+ readOnly: !!state.context.readonly,
457
+ autoComplete: "off",
458
+ autoCorrect: "off",
459
+ spellCheck: "false",
460
+ type: "text",
461
+ "aria-roledescription": !isIos() ? "number field" : void 0,
462
+ "aria-valuemin": state.context.min,
463
+ "aria-valuemax": state.context.max,
464
+ "aria-valuenow": isNaN(state.context.valueAsNumber) ? void 0 : state.context.valueAsNumber,
465
+ "aria-valuetext": state.context.valueText,
466
+ onFocus() {
467
+ send("FOCUS");
468
+ },
469
+ onBlur() {
470
+ send("BLUR");
471
+ },
472
+ onChange(event) {
473
+ const evt = getNativeEvent(event);
474
+ if (evt.isComposing)
475
+ return;
476
+ send({ type: "CHANGE", target: event.currentTarget, hint: "set" });
477
+ },
478
+ onKeyDown(event) {
479
+ const evt = getNativeEvent(event);
480
+ if (evt.isComposing)
481
+ return;
482
+ if (!utils.isValidNumericEvent(state.context, event)) {
483
+ event.preventDefault();
484
+ }
485
+ const step = getEventStep(event) * state.context.step;
486
+ const keyMap = {
487
+ ArrowUp() {
488
+ send({ type: "ARROW_UP", step });
489
+ },
490
+ ArrowDown() {
491
+ send({ type: "ARROW_DOWN", step });
492
+ },
493
+ Home() {
494
+ send("HOME");
495
+ },
496
+ End() {
497
+ send("END");
498
+ }
499
+ };
500
+ const exec = keyMap[event.key];
501
+ if (exec) {
502
+ exec(event);
503
+ event.preventDefault();
504
+ }
505
+ }
506
+ }),
507
+ decrementButtonProps: normalize.button({
508
+ "data-part": "spin-button",
509
+ "data-type": "decrement",
510
+ id: dom.getDecButtonId(state.context),
511
+ disabled: isDecrementDisabled,
512
+ "data-disabled": dataAttr(isDecrementDisabled),
513
+ "aria-label": messages.decrementLabel,
514
+ type: "button",
515
+ tabIndex: -1,
516
+ "aria-controls": dom.getInputId(state.context),
517
+ onPointerDown(event) {
518
+ if (isDecrementDisabled)
519
+ return;
520
+ send(isLeftClick(event) ? { type: "PRESS_DOWN", hint: "decrement" } : { type: "FOCUS" });
521
+ event.preventDefault();
522
+ },
523
+ onPointerUp() {
524
+ send({ type: "PRESS_UP", hint: "decrement" });
525
+ },
526
+ onPointerLeave() {
527
+ if (isDecrementDisabled)
528
+ return;
529
+ send({ type: "PRESS_UP", hint: "decrement" });
530
+ }
531
+ }),
532
+ incrementButtonProps: normalize.button({
533
+ "data-part": "spin-button",
534
+ "data-type": "increment",
535
+ id: dom.getIncButtonId(state.context),
536
+ disabled: isIncrementDisabled,
537
+ "data-disabled": dataAttr(isIncrementDisabled),
538
+ "aria-label": messages.incrementLabel,
539
+ type: "button",
540
+ tabIndex: -1,
541
+ "aria-controls": dom.getInputId(state.context),
542
+ onPointerDown(event) {
543
+ if (isIncrementDisabled)
544
+ return;
545
+ send(isLeftClick(event) ? { type: "PRESS_DOWN", hint: "increment" } : { type: "FOCUS" });
546
+ event.preventDefault();
547
+ },
548
+ onPointerUp() {
549
+ send({ type: "PRESS_UP", hint: "increment" });
550
+ },
551
+ onPointerLeave() {
552
+ send({ type: "PRESS_UP", hint: "increment" });
553
+ }
554
+ }),
555
+ scrubberProps: normalize.element({
556
+ "data-disabled": dataAttr(isDisabled),
557
+ "data-part": "scrubber",
558
+ id: dom.getScrubberId(state.context),
559
+ role: "presentation",
560
+ onMouseDown(event) {
561
+ if (isDisabled)
562
+ return;
563
+ const evt = getNativeEvent(event);
564
+ event.preventDefault();
565
+ const point = getEventPoint(evt);
566
+ point.x = point.x - roundToDevicePixel(7.5);
567
+ point.y = point.y - roundToDevicePixel(7.5);
568
+ send({ type: "PRESS_DOWN_SCRUBBER", point });
569
+ },
570
+ style: {
571
+ cursor: isDisabled ? void 0 : "ew-resize"
572
+ }
573
+ })
574
+ };
575
+ }
576
+
577
+ // src/number-input.machine.ts
578
+ import { choose, createMachine, guards } from "@zag-js/core";
579
+
580
+ // ../../utilities/core/dist/index.mjs
581
+ var callAll2 = (...fns) => (...a) => {
582
+ fns.forEach(function(fn) {
583
+ fn == null ? void 0 : fn(...a);
584
+ });
585
+ };
586
+
587
+ // src/number-input.machine.ts
588
+ var { not, and } = guards;
589
+ function machine(ctx) {
590
+ return createMachine(
591
+ {
592
+ id: "number-input",
593
+ initial: "unknown",
594
+ context: {
595
+ dir: "ltr",
596
+ focusInputOnChange: true,
597
+ clampValueOnBlur: true,
598
+ allowOverflow: false,
599
+ inputMode: "decimal",
600
+ pattern: "[0-9]*(.[0-9]+)?",
601
+ hint: null,
602
+ value: "",
603
+ step: 1,
604
+ min: Number.MIN_SAFE_INTEGER,
605
+ max: Number.MAX_SAFE_INTEGER,
606
+ scrubberCursorPoint: null,
607
+ invalid: false,
608
+ spinOnPress: true,
609
+ ...ctx,
610
+ messages: {
611
+ incrementLabel: "increment value",
612
+ decrementLabel: "decrease value",
613
+ ...ctx.messages
614
+ }
615
+ },
616
+ computed: {
617
+ isRtl: (ctx2) => ctx2.dir === "rtl",
618
+ valueAsNumber: (ctx2) => valueOf(ctx2.value),
619
+ isAtMin: (ctx2) => isAtMin(ctx2.value, ctx2),
620
+ isAtMax: (ctx2) => isAtMax(ctx2.value, ctx2),
621
+ isOutOfRange: (ctx2) => !isWithinRange(ctx2.value, ctx2),
622
+ isValueEmpty: (ctx2) => ctx2.value === "",
623
+ canIncrement: (ctx2) => ctx2.allowOverflow || !ctx2.isAtMax,
624
+ canDecrement: (ctx2) => ctx2.allowOverflow || !ctx2.isAtMin,
625
+ valueText: (ctx2) => {
626
+ var _a, _b;
627
+ return (_b = (_a = ctx2.messages).valueText) == null ? void 0 : _b.call(_a, ctx2.value);
628
+ },
629
+ formattedValue: (ctx2) => {
630
+ var _a;
631
+ return ((_a = ctx2.format) == null ? void 0 : _a.call(ctx2, ctx2.value).toString()) ?? ctx2.value;
632
+ }
633
+ },
634
+ watch: {
635
+ value: ["invokeOnChange"],
636
+ isOutOfRange: ["invokeOnInvalid"],
637
+ scrubberCursorPoint: ["setVirtualCursorPosition"]
638
+ },
639
+ on: {
640
+ SET_VALUE: {
641
+ actions: ["setValue", "setHintToSet"]
642
+ },
643
+ CLEAR_VALUE: {
644
+ actions: ["clearValue"]
645
+ },
646
+ INCREMENT: {
647
+ actions: ["increment"]
648
+ },
649
+ DECREMENT: {
650
+ actions: ["decrement"]
651
+ }
652
+ },
653
+ states: {
654
+ unknown: {
655
+ on: {
656
+ SETUP: {
657
+ target: "idle",
658
+ actions: "syncInputValue"
659
+ }
660
+ }
661
+ },
662
+ idle: {
663
+ exit: "invokeOnFocus",
664
+ on: {
665
+ PRESS_DOWN: {
666
+ target: "before:spin",
667
+ actions: ["focusInput", "setHint"]
668
+ },
669
+ PRESS_DOWN_SCRUBBER: {
670
+ target: "scrubbing",
671
+ actions: ["focusInput", "setHint", "setCursorPoint"]
672
+ },
673
+ FOCUS: "focused"
674
+ }
675
+ },
676
+ focused: {
677
+ tags: "focus",
678
+ entry: "focusInput",
679
+ activities: "attachWheelListener",
680
+ on: {
681
+ PRESS_DOWN: {
682
+ target: "before:spin",
683
+ actions: ["focusInput", "setHint"]
684
+ },
685
+ PRESS_DOWN_SCRUBBER: {
686
+ target: "scrubbing",
687
+ actions: ["focusInput", "setHint", "setCursorPoint"]
688
+ },
689
+ ARROW_UP: {
690
+ actions: "increment"
691
+ },
692
+ ARROW_DOWN: {
693
+ actions: "decrement"
694
+ },
695
+ HOME: {
696
+ actions: "setToMin"
697
+ },
698
+ END: {
699
+ actions: "setToMax"
700
+ },
701
+ CHANGE: {
702
+ actions: ["setValue", "setHint"]
703
+ },
704
+ BLUR: [
705
+ {
706
+ guard: "isInvalidExponential",
707
+ target: "idle",
708
+ actions: ["clearValue", "clearHint", "invokeOnBlur"]
709
+ },
710
+ {
711
+ guard: and("clampOnBlur", not("isInRange"), not("isEmptyValue")),
712
+ target: "idle",
713
+ actions: ["clampValue", "clearHint", "invokeOnBlur"]
714
+ },
715
+ {
716
+ target: "idle",
717
+ actions: ["roundValue", "invokeOnBlur"]
718
+ }
719
+ ]
720
+ }
721
+ },
722
+ "before:spin": {
723
+ tags: "focus",
724
+ activities: "trackButtonDisabled",
725
+ entry: choose([
726
+ { guard: "isIncrementHint", actions: "increment" },
727
+ { guard: "isDecrementHint", actions: "decrement" }
728
+ ]),
729
+ after: {
730
+ CHANGE_DELAY: {
731
+ target: "spinning",
732
+ guard: and("isInRange", "spinOnPress")
733
+ }
734
+ },
735
+ on: {
736
+ PRESS_UP: {
737
+ target: "focused",
738
+ actions: "clearHint"
739
+ }
740
+ }
741
+ },
742
+ spinning: {
743
+ tags: "focus",
744
+ activities: "trackButtonDisabled",
745
+ every: [
746
+ {
747
+ delay: "CHANGE_INTERVAL",
748
+ guard: and(not("isAtMin"), "isIncrementHint"),
749
+ actions: "increment"
750
+ },
751
+ {
752
+ delay: "CHANGE_INTERVAL",
753
+ guard: and(not("isAtMax"), "isDecrementHint"),
754
+ actions: "decrement"
755
+ }
756
+ ],
757
+ on: {
758
+ PRESS_UP: {
759
+ target: "focused",
760
+ actions: "clearHint"
761
+ }
762
+ }
763
+ },
764
+ scrubbing: {
765
+ tags: "focus",
766
+ exit: "clearCursorPoint",
767
+ activities: ["activatePointerLock", "trackMousemove", "setupVirtualCursor", "preventTextSelection"],
768
+ on: {
769
+ POINTER_UP_SCRUBBER: "focused",
770
+ POINTER_MOVE_SCRUBBER: [
771
+ {
772
+ guard: "isIncrementHint",
773
+ actions: ["increment", "setCursorPoint"]
774
+ },
775
+ {
776
+ guard: "isDecrementHint",
777
+ actions: ["decrement", "setCursorPoint"]
778
+ }
779
+ ]
780
+ }
781
+ }
782
+ }
783
+ },
784
+ {
785
+ delays: {
786
+ CHANGE_INTERVAL: 50,
787
+ CHANGE_DELAY: 300
788
+ },
789
+ guards: {
790
+ clampOnBlur: (ctx2) => !!ctx2.clampValueOnBlur,
791
+ isAtMin: (ctx2) => ctx2.isAtMin,
792
+ spinOnPress: (ctx2) => !!ctx2.spinOnPress,
793
+ isAtMax: (ctx2) => ctx2.isAtMax,
794
+ isInRange: (ctx2) => !ctx2.isOutOfRange,
795
+ isDecrementHint: (ctx2, evt) => (evt.hint ?? ctx2.hint) === "decrement",
796
+ isEmptyValue: (ctx2) => ctx2.isValueEmpty,
797
+ isIncrementHint: (ctx2, evt) => (evt.hint ?? ctx2.hint) === "increment",
798
+ isInvalidExponential: (ctx2) => ctx2.value.toString().startsWith("e")
799
+ },
800
+ activities: {
801
+ setupVirtualCursor(ctx2) {
802
+ return dom.setupVirtualCursor(ctx2);
803
+ },
804
+ preventTextSelection(ctx2) {
805
+ return dom.preventTextSelection(ctx2);
806
+ },
807
+ trackButtonDisabled(ctx2, _evt, { send }) {
808
+ const btn = dom.getActiveButton(ctx2, ctx2.hint);
809
+ return observeAttributes(btn, "disabled", () => send("PRESS_UP"));
810
+ },
811
+ attachWheelListener(ctx2, _evt, { send }) {
812
+ const input = dom.getInputEl(ctx2);
813
+ if (!input)
814
+ return;
815
+ function onWheel(event) {
816
+ const isInputFocused = dom.getDoc(ctx2).activeElement === input;
817
+ if (!ctx2.allowMouseWheel || !isInputFocused)
818
+ return;
819
+ event.preventDefault();
820
+ const dir = Math.sign(event.deltaY) * -1;
821
+ if (dir === 1) {
822
+ send("INCREMENT");
823
+ } else if (dir === -1) {
824
+ send("DECREMENT");
825
+ }
826
+ }
827
+ return addDomEvent(input, "wheel", onWheel, { passive: false });
828
+ },
829
+ activatePointerLock(ctx2) {
830
+ if (isSafari() || !supportsPointerEvent())
831
+ return;
832
+ return requestPointerLock(dom.getDoc(ctx2));
833
+ },
834
+ trackMousemove(ctx2, _evt, { send }) {
835
+ const doc = dom.getDoc(ctx2);
836
+ function onMousemove(event) {
837
+ if (!ctx2.scrubberCursorPoint)
838
+ return;
839
+ const value = dom.getMousementValue(ctx2, event);
840
+ if (!value.hint)
841
+ return;
842
+ send({
843
+ type: "POINTER_MOVE_SCRUBBER",
844
+ hint: value.hint,
845
+ point: value.point
846
+ });
847
+ }
848
+ function onMouseup() {
849
+ send("POINTER_UP_SCRUBBER");
850
+ }
851
+ return callAll2(
852
+ addDomEvent(doc, "mousemove", onMousemove, false),
853
+ addDomEvent(doc, "mouseup", onMouseup, false)
854
+ );
855
+ }
856
+ },
857
+ actions: {
858
+ focusInput(ctx2) {
859
+ if (!ctx2.focusInputOnChange)
860
+ return;
861
+ const input = dom.getInputEl(ctx2);
862
+ raf(() => input == null ? void 0 : input.focus());
863
+ },
864
+ increment(ctx2, evt) {
865
+ ctx2.value = utils.increment(ctx2, evt.step);
866
+ },
867
+ decrement(ctx2, evt) {
868
+ ctx2.value = utils.decrement(ctx2, evt.step);
869
+ },
870
+ clampValue(ctx2) {
871
+ ctx2.value = utils.clamp(ctx2);
872
+ },
873
+ roundValue(ctx2) {
874
+ if (ctx2.value !== "") {
875
+ ctx2.value = utils.round(ctx2);
876
+ }
877
+ },
878
+ setValue(ctx2, evt) {
879
+ var _a;
880
+ const value = ((_a = evt.target) == null ? void 0 : _a.value) ?? evt.value;
881
+ ctx2.value = utils.sanitize(ctx2, utils.parse(ctx2, value.toString()));
882
+ },
883
+ clearValue(ctx2) {
884
+ ctx2.value = "";
885
+ },
886
+ setToMax(ctx2) {
887
+ ctx2.value = ctx2.max.toString();
888
+ },
889
+ setToMin(ctx2) {
890
+ ctx2.value = ctx2.min.toString();
891
+ },
892
+ setHint(ctx2, evt) {
893
+ ctx2.hint = evt.hint;
894
+ },
895
+ clearHint(ctx2) {
896
+ ctx2.hint = null;
897
+ },
898
+ setHintToSet(ctx2) {
899
+ ctx2.hint = "set";
900
+ },
901
+ invokeOnChange(ctx2) {
902
+ var _a;
903
+ (_a = ctx2.onChange) == null ? void 0 : _a.call(ctx2, {
904
+ value: ctx2.value,
905
+ valueAsNumber: ctx2.valueAsNumber
906
+ });
907
+ },
908
+ invokeOnFocus(ctx2, evt) {
909
+ var _a;
910
+ let srcElement = null;
911
+ if (evt.type === "PRESS_DOWN") {
912
+ srcElement = dom.getActiveButton(ctx2, evt.hint);
913
+ } else if (evt.type === "FOCUS") {
914
+ srcElement = dom.getInputEl(ctx2);
915
+ } else if (evt.type === "PRESS_DOWN_SCRUBBER") {
916
+ srcElement = dom.getScrubberEl(ctx2);
917
+ }
918
+ (_a = ctx2.onFocus) == null ? void 0 : _a.call(ctx2, {
919
+ value: ctx2.value,
920
+ valueAsNumber: ctx2.valueAsNumber,
921
+ srcElement
922
+ });
923
+ },
924
+ invokeOnBlur(ctx2) {
925
+ var _a;
926
+ (_a = ctx2.onBlur) == null ? void 0 : _a.call(ctx2, {
927
+ value: ctx2.value,
928
+ valueAsNumber: ctx2.valueAsNumber
929
+ });
930
+ },
931
+ invokeOnInvalid(ctx2) {
932
+ var _a;
933
+ if (!ctx2.isOutOfRange)
934
+ return;
935
+ const reason = ctx2.valueAsNumber > ctx2.max ? "rangeOverflow" : "rangeUnderflow";
936
+ (_a = ctx2.onInvalid) == null ? void 0 : _a.call(ctx2, {
937
+ reason,
938
+ value: ctx2.formattedValue,
939
+ valueAsNumber: ctx2.valueAsNumber
940
+ });
941
+ },
942
+ syncInputValue(ctx2) {
943
+ const input = dom.getInputEl(ctx2);
944
+ if (!input || input.value == ctx2.value)
945
+ return;
946
+ const value = utils.parse(ctx2, input.value);
947
+ ctx2.value = utils.sanitize(ctx2, value);
948
+ },
949
+ setCursorPoint(ctx2, evt) {
950
+ ctx2.scrubberCursorPoint = evt.point;
951
+ },
952
+ clearCursorPoint(ctx2) {
953
+ ctx2.scrubberCursorPoint = null;
954
+ },
955
+ setVirtualCursorPosition(ctx2) {
956
+ const cursor = dom.getCursorEl(ctx2);
957
+ if (!cursor || !ctx2.scrubberCursorPoint)
958
+ return;
959
+ const { x, y } = ctx2.scrubberCursorPoint;
960
+ cursor.style.transform = `translate3d(${x}px, ${y}px, 0px)`;
961
+ }
962
+ },
963
+ hookSync: true
964
+ }
965
+ );
966
+ }
967
+ export {
968
+ connect,
969
+ machine
970
+ };