@zag-js/number-input 0.0.0-dev-20220919164136 → 0.0.0-dev-20220928124757

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