@zag-js/pin-input 0.49.0 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -46,6 +46,7 @@ interface PublicContext extends DirectionProperty, CommonProperties {
46
46
  disabled?: boolean;
47
47
  /**
48
48
  * The placeholder text for the input
49
+ * @default "○"
49
50
  */
50
51
  placeholder?: string;
51
52
  /**
@@ -67,6 +68,7 @@ interface PublicContext extends DirectionProperty, CommonProperties {
67
68
  value: string[];
68
69
  /**
69
70
  * The type of value the pin-input should allow
71
+ * @default "numeric"
70
72
  */
71
73
  type?: "alphanumeric" | "numeric" | "alphabetic";
72
74
  /**
package/dist/index.d.ts CHANGED
@@ -46,6 +46,7 @@ interface PublicContext extends DirectionProperty, CommonProperties {
46
46
  disabled?: boolean;
47
47
  /**
48
48
  * The placeholder text for the input
49
+ * @default "○"
49
50
  */
50
51
  placeholder?: string;
51
52
  /**
@@ -67,6 +68,7 @@ interface PublicContext extends DirectionProperty, CommonProperties {
67
68
  value: string[];
68
69
  /**
69
70
  * The type of value the pin-input should allow
71
+ * @default "numeric"
70
72
  */
71
73
  type?: "alphanumeric" | "numeric" | "alphabetic";
72
74
  /**
package/dist/index.js CHANGED
@@ -1,508 +1,2 @@
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
- anatomy: () => anatomy,
24
- connect: () => connect,
25
- machine: () => machine
26
- });
27
- module.exports = __toCommonJS(src_exports);
28
-
29
- // src/pin-input.anatomy.ts
30
- var import_anatomy = require("@zag-js/anatomy");
31
- var anatomy = (0, import_anatomy.createAnatomy)("pinInput").parts("root", "label", "input", "control");
32
- var parts = anatomy.build();
33
-
34
- // src/pin-input.connect.ts
35
- var import_dom_event = require("@zag-js/dom-event");
36
- var import_dom_query2 = require("@zag-js/dom-query");
37
- var import_utils = require("@zag-js/utils");
38
-
39
- // src/pin-input.dom.ts
40
- var import_dom_query = require("@zag-js/dom-query");
41
- var dom = (0, import_dom_query.createScope)({
42
- getRootId: (ctx) => ctx.ids?.root ?? `pin-input:${ctx.id}`,
43
- getInputId: (ctx, id) => ctx.ids?.input?.(id) ?? `pin-input:${ctx.id}:${id}`,
44
- getHiddenInputId: (ctx) => ctx.ids?.hiddenInput ?? `pin-input:${ctx.id}:hidden`,
45
- getLabelId: (ctx) => ctx.ids?.label ?? `pin-input:${ctx.id}:label`,
46
- getControlId: (ctx) => ctx.ids?.control ?? `pin-input:${ctx.id}:control`,
47
- getRootEl: (ctx) => dom.getById(ctx, dom.getRootId(ctx)),
48
- getInputEls: (ctx) => {
49
- const ownerId = CSS.escape(dom.getRootId(ctx));
50
- const selector = `input[data-ownedby=${ownerId}]`;
51
- return (0, import_dom_query.queryAll)(dom.getRootEl(ctx), selector);
52
- },
53
- getInputEl: (ctx, id) => dom.getById(ctx, dom.getInputId(ctx, id)),
54
- getFocusedInputEl: (ctx) => dom.getInputEls(ctx)[ctx.focusedIndex],
55
- getFirstInputEl: (ctx) => dom.getInputEls(ctx)[0],
56
- getHiddenInputEl: (ctx) => dom.getById(ctx, dom.getHiddenInputId(ctx))
57
- });
58
-
59
- // src/pin-input.utils.ts
60
- var REGEX = {
61
- numeric: /^[0-9]+$/,
62
- alphabetic: /^[A-Za-z]+$/,
63
- alphanumeric: /^[a-zA-Z0-9]+$/i
64
- };
65
- function isValidType(ctx, value) {
66
- if (!ctx.type)
67
- return true;
68
- return !!REGEX[ctx.type]?.test(value);
69
- }
70
- function isValidValue(ctx, value) {
71
- if (!ctx.pattern)
72
- return isValidType(ctx, value);
73
- const regex = new RegExp(ctx.pattern, "g");
74
- return regex.test(value);
75
- }
76
-
77
- // src/pin-input.connect.ts
78
- function connect(state, send, normalize) {
79
- const complete = state.context.isValueComplete;
80
- const invalid = state.context.invalid;
81
- const focusedIndex = state.context.focusedIndex;
82
- const translations = state.context.translations;
83
- function focus() {
84
- dom.getFirstInputEl(state.context)?.focus();
85
- }
86
- return {
87
- focus,
88
- value: state.context.value,
89
- valueAsString: state.context.valueAsString,
90
- complete,
91
- setValue(value) {
92
- if (!Array.isArray(value)) {
93
- (0, import_utils.invariant)("[pin-input/setValue] value must be an array");
94
- }
95
- send({ type: "VALUE.SET", value });
96
- },
97
- clearValue() {
98
- send({ type: "VALUE.CLEAR" });
99
- },
100
- setValueAtIndex(index, value) {
101
- send({ type: "VALUE.SET", value, index });
102
- },
103
- rootProps: normalize.element({
104
- dir: state.context.dir,
105
- ...parts.root.attrs,
106
- id: dom.getRootId(state.context),
107
- "data-invalid": (0, import_dom_query2.dataAttr)(invalid),
108
- "data-disabled": (0, import_dom_query2.dataAttr)(state.context.disabled),
109
- "data-complete": (0, import_dom_query2.dataAttr)(complete)
110
- }),
111
- labelProps: normalize.label({
112
- ...parts.label.attrs,
113
- dir: state.context.dir,
114
- htmlFor: dom.getHiddenInputId(state.context),
115
- id: dom.getLabelId(state.context),
116
- "data-invalid": (0, import_dom_query2.dataAttr)(invalid),
117
- "data-disabled": (0, import_dom_query2.dataAttr)(state.context.disabled),
118
- "data-complete": (0, import_dom_query2.dataAttr)(complete),
119
- onClick(event) {
120
- event.preventDefault();
121
- focus();
122
- }
123
- }),
124
- hiddenInputProps: normalize.input({
125
- "aria-hidden": true,
126
- type: "text",
127
- tabIndex: -1,
128
- id: dom.getHiddenInputId(state.context),
129
- name: state.context.name,
130
- form: state.context.form,
131
- style: import_dom_query2.visuallyHiddenStyle,
132
- maxLength: state.context.valueLength,
133
- defaultValue: state.context.valueAsString
134
- }),
135
- controlProps: normalize.element({
136
- ...parts.control.attrs,
137
- dir: state.context.dir,
138
- id: dom.getControlId(state.context)
139
- }),
140
- getInputProps(props) {
141
- const { index } = props;
142
- const inputType = state.context.type === "numeric" ? "tel" : "text";
143
- return normalize.input({
144
- ...parts.input.attrs,
145
- dir: state.context.dir,
146
- disabled: state.context.disabled,
147
- "data-disabled": (0, import_dom_query2.dataAttr)(state.context.disabled),
148
- "data-complete": (0, import_dom_query2.dataAttr)(complete),
149
- id: dom.getInputId(state.context, index.toString()),
150
- "data-ownedby": dom.getRootId(state.context),
151
- "aria-label": translations.inputLabel(index, state.context.valueLength),
152
- inputMode: state.context.otp || state.context.type === "numeric" ? "numeric" : "text",
153
- "aria-invalid": (0, import_dom_query2.ariaAttr)(invalid),
154
- "data-invalid": (0, import_dom_query2.dataAttr)(invalid),
155
- type: state.context.mask ? "password" : inputType,
156
- defaultValue: state.context.value[index] || "",
157
- autoCapitalize: "none",
158
- autoComplete: state.context.otp ? "one-time-code" : "off",
159
- placeholder: focusedIndex === index ? "" : state.context.placeholder,
160
- onBeforeInput(event) {
161
- try {
162
- const value = (0, import_dom_query2.getBeforeInputValue)(event);
163
- const isValid = isValidValue(state.context, value);
164
- if (!isValid) {
165
- send({ type: "VALUE.INVALID", value });
166
- event.preventDefault();
167
- }
168
- if (value.length > 2) {
169
- event.currentTarget.setSelectionRange(0, 1, "forward");
170
- }
171
- } catch {
172
- }
173
- },
174
- onChange(event) {
175
- const evt = (0, import_dom_event.getNativeEvent)(event);
176
- const { value } = event.currentTarget;
177
- if (evt.inputType === "insertFromPaste" || value.length > 2) {
178
- send({ type: "INPUT.PASTE", value });
179
- event.target.value = value[0];
180
- event.preventDefault();
181
- return;
182
- }
183
- if (evt.inputType === "deleteContentBackward") {
184
- send("INPUT.BACKSPACE");
185
- return;
186
- }
187
- send({ type: "INPUT.CHANGE", value, index });
188
- },
189
- onKeyDown(event) {
190
- if (event.defaultPrevented)
191
- return;
192
- const evt = (0, import_dom_event.getNativeEvent)(event);
193
- if (evt.isComposing)
194
- return;
195
- if ((0, import_dom_event.isModifierKey)(evt))
196
- return;
197
- const keyMap = {
198
- Backspace() {
199
- send("INPUT.BACKSPACE");
200
- },
201
- Delete() {
202
- send("INPUT.DELETE");
203
- },
204
- ArrowLeft() {
205
- send("INPUT.ARROW_LEFT");
206
- },
207
- ArrowRight() {
208
- send("INPUT.ARROW_RIGHT");
209
- },
210
- Enter() {
211
- send("INPUT.ENTER");
212
- }
213
- };
214
- const exec = keyMap[(0, import_dom_event.getEventKey)(event, state.context)];
215
- if (exec) {
216
- exec(event);
217
- event.preventDefault();
218
- }
219
- },
220
- onFocus() {
221
- send({ type: "INPUT.FOCUS", index });
222
- },
223
- onBlur() {
224
- send({ type: "INPUT.BLUR", index });
225
- }
226
- });
227
- }
228
- };
229
- }
230
-
231
- // src/pin-input.machine.ts
232
- var import_core = require("@zag-js/core");
233
- var import_dom_query3 = require("@zag-js/dom-query");
234
- var import_form_utils = require("@zag-js/form-utils");
235
- var import_utils2 = require("@zag-js/utils");
236
- function machine(userContext) {
237
- const ctx = (0, import_utils2.compact)(userContext);
238
- return (0, import_core.createMachine)(
239
- {
240
- id: "pin-input",
241
- initial: "idle",
242
- context: {
243
- value: [],
244
- focusedIndex: -1,
245
- placeholder: "\u25CB",
246
- otp: false,
247
- type: "numeric",
248
- ...ctx,
249
- translations: {
250
- inputLabel: (index, length) => `pin code ${index + 1} of ${length}`,
251
- ...ctx.translations
252
- }
253
- },
254
- computed: {
255
- valueLength: (ctx2) => ctx2.value.length,
256
- filledValueLength: (ctx2) => ctx2.value.filter((v) => v?.trim() !== "").length,
257
- isValueComplete: (ctx2) => ctx2.valueLength === ctx2.filledValueLength,
258
- valueAsString: (ctx2) => ctx2.value.join(""),
259
- focusedValue: (ctx2) => ctx2.value[ctx2.focusedIndex] || ""
260
- },
261
- entry: (0, import_core.choose)([
262
- {
263
- guard: "autoFocus",
264
- actions: ["setupValue", "setFocusIndexToFirst"]
265
- },
266
- { actions: ["setupValue"] }
267
- ]),
268
- watch: {
269
- focusedIndex: ["focusInput", "selectInputIfNeeded"],
270
- value: ["syncInputElements"],
271
- isValueComplete: ["invokeOnComplete", "blurFocusedInputIfNeeded"]
272
- },
273
- on: {
274
- "VALUE.SET": [
275
- {
276
- guard: "hasIndex",
277
- actions: ["setValueAtIndex"]
278
- },
279
- { actions: ["setValue"] }
280
- ],
281
- "VALUE.CLEAR": {
282
- actions: ["clearValue", "setFocusIndexToFirst"]
283
- }
284
- },
285
- states: {
286
- idle: {
287
- on: {
288
- "INPUT.FOCUS": {
289
- target: "focused",
290
- actions: "setFocusedIndex"
291
- }
292
- }
293
- },
294
- focused: {
295
- on: {
296
- "INPUT.CHANGE": [
297
- {
298
- guard: "isFinalValue",
299
- actions: ["setFocusedValue", "syncInputValue"]
300
- },
301
- {
302
- actions: ["setFocusedValue", "setNextFocusedIndex", "syncInputValue"]
303
- }
304
- ],
305
- "INPUT.PASTE": {
306
- actions: ["setPastedValue", "setLastValueFocusIndex"]
307
- },
308
- "INPUT.BLUR": {
309
- target: "idle",
310
- actions: "clearFocusedIndex"
311
- },
312
- "INPUT.DELETE": {
313
- guard: "hasValue",
314
- actions: "clearFocusedValue"
315
- },
316
- "INPUT.ARROW_LEFT": {
317
- actions: "setPrevFocusedIndex"
318
- },
319
- "INPUT.ARROW_RIGHT": {
320
- actions: "setNextFocusedIndex"
321
- },
322
- "INPUT.BACKSPACE": [
323
- {
324
- guard: "hasValue",
325
- actions: ["clearFocusedValue"]
326
- },
327
- {
328
- actions: ["setPrevFocusedIndex", "clearFocusedValue"]
329
- }
330
- ],
331
- "INPUT.ENTER": {
332
- guard: "isValueComplete",
333
- actions: "requestFormSubmit"
334
- },
335
- "VALUE.INVALID": {
336
- actions: "invokeOnInvalid"
337
- }
338
- }
339
- }
340
- }
341
- },
342
- {
343
- guards: {
344
- autoFocus: (ctx2) => !!ctx2.autoFocus,
345
- isValueEmpty: (_ctx, evt) => evt.value === "",
346
- hasValue: (ctx2) => ctx2.value[ctx2.focusedIndex] !== "",
347
- isValueComplete: (ctx2) => ctx2.isValueComplete,
348
- isFinalValue: (ctx2) => ctx2.filledValueLength + 1 === ctx2.valueLength && ctx2.value.findIndex((v) => v.trim() === "") === ctx2.focusedIndex,
349
- hasIndex: (_ctx, evt) => evt.index !== void 0,
350
- isDisabled: (ctx2) => !!ctx2.disabled
351
- },
352
- actions: {
353
- setupValue(ctx2) {
354
- if (ctx2.value.length)
355
- return;
356
- const inputEls = dom.getInputEls(ctx2);
357
- const emptyValues = Array.from({ length: inputEls.length }).fill("");
358
- assignValue(ctx2, emptyValues);
359
- },
360
- focusInput(ctx2) {
361
- if (ctx2.focusedIndex === -1)
362
- return;
363
- dom.getFocusedInputEl(ctx2)?.focus({ preventScroll: true });
364
- },
365
- selectInputIfNeeded(ctx2) {
366
- if (!ctx2.selectOnFocus || ctx2.focusedIndex === -1)
367
- return;
368
- (0, import_dom_query3.raf)(() => {
369
- dom.getFocusedInputEl(ctx2)?.select();
370
- });
371
- },
372
- invokeOnComplete(ctx2) {
373
- if (!ctx2.isValueComplete)
374
- return;
375
- ctx2.onValueComplete?.({
376
- value: Array.from(ctx2.value),
377
- valueAsString: ctx2.valueAsString
378
- });
379
- },
380
- invokeOnInvalid(ctx2, evt) {
381
- ctx2.onValueInvalid?.({
382
- value: evt.value,
383
- index: ctx2.focusedIndex
384
- });
385
- },
386
- clearFocusedIndex(ctx2) {
387
- ctx2.focusedIndex = -1;
388
- },
389
- setFocusedIndex(ctx2, evt) {
390
- ctx2.focusedIndex = evt.index;
391
- },
392
- setValue(ctx2, evt) {
393
- set.value(ctx2, evt.value);
394
- },
395
- setFocusedValue(ctx2, evt) {
396
- const nextValue = getNextValue(ctx2.focusedValue, evt.value);
397
- set.valueAtIndex(ctx2, ctx2.focusedIndex, nextValue);
398
- },
399
- revertInputValue(ctx2) {
400
- const inputEl = dom.getFocusedInputEl(ctx2);
401
- dom.setValue(inputEl, ctx2.focusedValue);
402
- },
403
- syncInputValue(ctx2, evt) {
404
- const inputEl = dom.getInputEl(ctx2, evt.index.toString());
405
- dom.setValue(inputEl, ctx2.value[evt.index]);
406
- },
407
- syncInputElements(ctx2) {
408
- const inputEls = dom.getInputEls(ctx2);
409
- inputEls.forEach((inputEl, index) => {
410
- dom.setValue(inputEl, ctx2.value[index]);
411
- });
412
- },
413
- setPastedValue(ctx2, evt) {
414
- (0, import_dom_query3.raf)(() => {
415
- const startIndex = Math.min(ctx2.focusedIndex, ctx2.filledValueLength);
416
- const left = startIndex > 0 ? ctx2.valueAsString.substring(0, ctx2.focusedIndex) : "";
417
- const right = evt.value.substring(0, ctx2.valueLength - startIndex);
418
- const value = left + right;
419
- set.value(ctx2, value.split(""));
420
- });
421
- },
422
- setValueAtIndex(ctx2, evt) {
423
- const nextValue = getNextValue(ctx2.focusedValue, evt.value);
424
- set.valueAtIndex(ctx2, evt.index, nextValue);
425
- },
426
- clearValue(ctx2) {
427
- const nextValue = Array.from({ length: ctx2.valueLength }).fill("");
428
- set.value(ctx2, nextValue);
429
- },
430
- clearFocusedValue(ctx2) {
431
- set.valueAtIndex(ctx2, ctx2.focusedIndex, "");
432
- },
433
- setFocusIndexToFirst(ctx2) {
434
- ctx2.focusedIndex = 0;
435
- },
436
- setNextFocusedIndex(ctx2) {
437
- ctx2.focusedIndex = Math.min(ctx2.focusedIndex + 1, ctx2.valueLength - 1);
438
- },
439
- setPrevFocusedIndex(ctx2) {
440
- ctx2.focusedIndex = Math.max(ctx2.focusedIndex - 1, 0);
441
- },
442
- setLastValueFocusIndex(ctx2) {
443
- (0, import_dom_query3.raf)(() => {
444
- ctx2.focusedIndex = Math.min(ctx2.filledValueLength, ctx2.valueLength - 1);
445
- });
446
- },
447
- blurFocusedInputIfNeeded(ctx2) {
448
- if (!ctx2.blurOnComplete)
449
- return;
450
- (0, import_dom_query3.raf)(() => {
451
- dom.getFocusedInputEl(ctx2)?.blur();
452
- });
453
- },
454
- requestFormSubmit(ctx2) {
455
- if (!ctx2.name || !ctx2.isValueComplete)
456
- return;
457
- const inputEl = dom.getHiddenInputEl(ctx2);
458
- inputEl?.form?.requestSubmit();
459
- }
460
- }
461
- }
462
- );
463
- }
464
- function assignValue(ctx, value) {
465
- const arr = Array.isArray(value) ? value : value.split("").filter(Boolean);
466
- arr.forEach((value2, index) => {
467
- ctx.value[index] = value2;
468
- });
469
- }
470
- function getNextValue(current, next) {
471
- let nextValue = next;
472
- if (current[0] === next[0])
473
- nextValue = next[1];
474
- else if (current[0] === next[1])
475
- nextValue = next[0];
476
- return nextValue.split("")[nextValue.length - 1];
477
- }
478
- var invoke = {
479
- change(ctx) {
480
- ctx.onValueChange?.({
481
- value: Array.from(ctx.value),
482
- valueAsString: ctx.valueAsString
483
- });
484
- const inputEl = dom.getHiddenInputEl(ctx);
485
- (0, import_form_utils.dispatchInputValueEvent)(inputEl, { value: ctx.valueAsString });
486
- }
487
- };
488
- var set = {
489
- value(ctx, value) {
490
- if ((0, import_utils2.isEqual)(ctx.value, value))
491
- return;
492
- assignValue(ctx, value);
493
- invoke.change(ctx);
494
- },
495
- valueAtIndex(ctx, index, value) {
496
- if ((0, import_utils2.isEqual)(ctx.value[index], value))
497
- return;
498
- ctx.value[index] = value;
499
- invoke.change(ctx);
500
- }
501
- };
502
- // Annotate the CommonJS export names for ESM import in node:
503
- 0 && (module.exports = {
504
- anatomy,
505
- connect,
506
- machine
507
- });
1
+ "use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var src_exports={};__export(src_exports,{anatomy:()=>anatomy,connect:()=>connect,machine:()=>machine});module.exports=__toCommonJS(src_exports);var import_anatomy=require("@zag-js/anatomy");var anatomy=(0,import_anatomy.createAnatomy)("pinInput").parts("root","label","input","control");var parts=anatomy.build();var import_dom_event=require("@zag-js/dom-event");var import_dom_query2=require("@zag-js/dom-query");var import_utils=require("@zag-js/utils");var import_dom_query=require("@zag-js/dom-query");var dom=(0,import_dom_query.createScope)({getRootId:ctx=>ctx.ids?.root??`pin-input:${ctx.id}`,getInputId:(ctx,id)=>ctx.ids?.input?.(id)??`pin-input:${ctx.id}:${id}`,getHiddenInputId:ctx=>ctx.ids?.hiddenInput??`pin-input:${ctx.id}:hidden`,getLabelId:ctx=>ctx.ids?.label??`pin-input:${ctx.id}:label`,getControlId:ctx=>ctx.ids?.control??`pin-input:${ctx.id}:control`,getRootEl:ctx=>dom.getById(ctx,dom.getRootId(ctx)),getInputEls:ctx=>{const ownerId=CSS.escape(dom.getRootId(ctx));const selector=`input[data-ownedby=${ownerId}]`;return(0,import_dom_query.queryAll)(dom.getRootEl(ctx),selector)},getInputEl:(ctx,id)=>dom.getById(ctx,dom.getInputId(ctx,id)),getFocusedInputEl:ctx=>dom.getInputEls(ctx)[ctx.focusedIndex],getFirstInputEl:ctx=>dom.getInputEls(ctx)[0],getHiddenInputEl:ctx=>dom.getById(ctx,dom.getHiddenInputId(ctx))});var REGEX={numeric:/^[0-9]+$/,alphabetic:/^[A-Za-z]+$/,alphanumeric:/^[a-zA-Z0-9]+$/i};function isValidType(ctx,value){if(!ctx.type)return true;return!!REGEX[ctx.type]?.test(value)}function isValidValue(ctx,value){if(!ctx.pattern)return isValidType(ctx,value);const regex=new RegExp(ctx.pattern,"g");return regex.test(value)}function connect(state,send,normalize){const complete=state.context.isValueComplete;const invalid=state.context.invalid;const focusedIndex=state.context.focusedIndex;const translations=state.context.translations;function focus(){dom.getFirstInputEl(state.context)?.focus()}return{focus,value:state.context.value,valueAsString:state.context.valueAsString,complete,setValue(value){if(!Array.isArray(value)){(0,import_utils.invariant)("[pin-input/setValue] value must be an array")}send({type:"VALUE.SET",value})},clearValue(){send({type:"VALUE.CLEAR"})},setValueAtIndex(index,value){send({type:"VALUE.SET",value,index})},rootProps:normalize.element({dir:state.context.dir,...parts.root.attrs,id:dom.getRootId(state.context),"data-invalid":(0,import_dom_query2.dataAttr)(invalid),"data-disabled":(0,import_dom_query2.dataAttr)(state.context.disabled),"data-complete":(0,import_dom_query2.dataAttr)(complete)}),labelProps:normalize.label({...parts.label.attrs,dir:state.context.dir,htmlFor:dom.getHiddenInputId(state.context),id:dom.getLabelId(state.context),"data-invalid":(0,import_dom_query2.dataAttr)(invalid),"data-disabled":(0,import_dom_query2.dataAttr)(state.context.disabled),"data-complete":(0,import_dom_query2.dataAttr)(complete),onClick(event){event.preventDefault();focus()}}),hiddenInputProps:normalize.input({"aria-hidden":true,type:"text",tabIndex:-1,id:dom.getHiddenInputId(state.context),name:state.context.name,form:state.context.form,style:import_dom_query2.visuallyHiddenStyle,maxLength:state.context.valueLength,defaultValue:state.context.valueAsString}),controlProps:normalize.element({...parts.control.attrs,dir:state.context.dir,id:dom.getControlId(state.context)}),getInputProps(props){const{index}=props;const inputType=state.context.type==="numeric"?"tel":"text";return normalize.input({...parts.input.attrs,dir:state.context.dir,disabled:state.context.disabled,"data-disabled":(0,import_dom_query2.dataAttr)(state.context.disabled),"data-complete":(0,import_dom_query2.dataAttr)(complete),id:dom.getInputId(state.context,index.toString()),"data-ownedby":dom.getRootId(state.context),"aria-label":translations.inputLabel(index,state.context.valueLength),inputMode:state.context.otp||state.context.type==="numeric"?"numeric":"text","aria-invalid":(0,import_dom_query2.ariaAttr)(invalid),"data-invalid":(0,import_dom_query2.dataAttr)(invalid),type:state.context.mask?"password":inputType,defaultValue:state.context.value[index]||"",autoCapitalize:"none",autoComplete:state.context.otp?"one-time-code":"off",placeholder:focusedIndex===index?"":state.context.placeholder,onBeforeInput(event){try{const value=(0,import_dom_query2.getBeforeInputValue)(event);const isValid=isValidValue(state.context,value);if(!isValid){send({type:"VALUE.INVALID",value});event.preventDefault()}if(value.length>2){event.currentTarget.setSelectionRange(0,1,"forward")}}catch{}},onChange(event){const evt=(0,import_dom_event.getNativeEvent)(event);const{value}=event.currentTarget;if(evt.inputType==="insertFromPaste"||value.length>2){send({type:"INPUT.PASTE",value});event.target.value=value[0];event.preventDefault();return}if(evt.inputType==="deleteContentBackward"){send("INPUT.BACKSPACE");return}send({type:"INPUT.CHANGE",value,index})},onKeyDown(event){if(event.defaultPrevented)return;const evt=(0,import_dom_event.getNativeEvent)(event);if(evt.isComposing)return;if((0,import_dom_event.isModifierKey)(evt))return;const keyMap={Backspace(){send("INPUT.BACKSPACE")},Delete(){send("INPUT.DELETE")},ArrowLeft(){send("INPUT.ARROW_LEFT")},ArrowRight(){send("INPUT.ARROW_RIGHT")},Enter(){send("INPUT.ENTER")}};const exec=keyMap[(0,import_dom_event.getEventKey)(event,state.context)];if(exec){exec(event);event.preventDefault()}},onFocus(){send({type:"INPUT.FOCUS",index})},onBlur(){send({type:"INPUT.BLUR",index})}})}}}var import_core=require("@zag-js/core");var import_dom_query3=require("@zag-js/dom-query");var import_form_utils=require("@zag-js/form-utils");var import_utils2=require("@zag-js/utils");function machine(userContext){const ctx=(0,import_utils2.compact)(userContext);return(0,import_core.createMachine)({id:"pin-input",initial:"idle",context:{value:[],placeholder:"\u25CB",otp:false,type:"numeric",...ctx,focusedIndex:-1,translations:{inputLabel:(index,length)=>`pin code ${index+1} of ${length}`,...ctx.translations}},computed:{valueLength:ctx2=>ctx2.value.length,filledValueLength:ctx2=>ctx2.value.filter(v=>v?.trim()!=="").length,isValueComplete:ctx2=>ctx2.valueLength===ctx2.filledValueLength,valueAsString:ctx2=>ctx2.value.join(""),focusedValue:ctx2=>ctx2.value[ctx2.focusedIndex]||""},entry:(0,import_core.choose)([{guard:"autoFocus",actions:["setupValue","setFocusIndexToFirst"]},{actions:["setupValue"]}]),watch:{focusedIndex:["focusInput","selectInputIfNeeded"],value:["syncInputElements"],isValueComplete:["invokeOnComplete","blurFocusedInputIfNeeded"]},on:{"VALUE.SET":[{guard:"hasIndex",actions:["setValueAtIndex"]},{actions:["setValue"]}],"VALUE.CLEAR":{actions:["clearValue","setFocusIndexToFirst"]}},states:{idle:{on:{"INPUT.FOCUS":{target:"focused",actions:"setFocusedIndex"}}},focused:{on:{"INPUT.CHANGE":[{guard:"isFinalValue",actions:["setFocusedValue","syncInputValue"]},{actions:["setFocusedValue","setNextFocusedIndex","syncInputValue"]}],"INPUT.PASTE":{actions:["setPastedValue","setLastValueFocusIndex"]},"INPUT.BLUR":{target:"idle",actions:"clearFocusedIndex"},"INPUT.DELETE":{guard:"hasValue",actions:"clearFocusedValue"},"INPUT.ARROW_LEFT":{actions:"setPrevFocusedIndex"},"INPUT.ARROW_RIGHT":{actions:"setNextFocusedIndex"},"INPUT.BACKSPACE":[{guard:"hasValue",actions:["clearFocusedValue"]},{actions:["setPrevFocusedIndex","clearFocusedValue"]}],"INPUT.ENTER":{guard:"isValueComplete",actions:"requestFormSubmit"},"VALUE.INVALID":{actions:"invokeOnInvalid"}}}}},{guards:{autoFocus:ctx2=>!!ctx2.autoFocus,isValueEmpty:(_ctx,evt)=>evt.value==="",hasValue:ctx2=>ctx2.value[ctx2.focusedIndex]!=="",isValueComplete:ctx2=>ctx2.isValueComplete,isFinalValue:ctx2=>ctx2.filledValueLength+1===ctx2.valueLength&&ctx2.value.findIndex(v=>v.trim()==="")===ctx2.focusedIndex,hasIndex:(_ctx,evt)=>evt.index!==void 0,isDisabled:ctx2=>!!ctx2.disabled},actions:{setupValue(ctx2){if(ctx2.value.length)return;const inputEls=dom.getInputEls(ctx2);const emptyValues=Array.from({length:inputEls.length}).fill("");assignValue(ctx2,emptyValues)},focusInput(ctx2){if(ctx2.focusedIndex===-1)return;dom.getFocusedInputEl(ctx2)?.focus({preventScroll:true})},selectInputIfNeeded(ctx2){if(!ctx2.selectOnFocus||ctx2.focusedIndex===-1)return;(0,import_dom_query3.raf)(()=>{dom.getFocusedInputEl(ctx2)?.select()})},invokeOnComplete(ctx2){if(!ctx2.isValueComplete)return;ctx2.onValueComplete?.({value:Array.from(ctx2.value),valueAsString:ctx2.valueAsString})},invokeOnInvalid(ctx2,evt){ctx2.onValueInvalid?.({value:evt.value,index:ctx2.focusedIndex})},clearFocusedIndex(ctx2){ctx2.focusedIndex=-1},setFocusedIndex(ctx2,evt){ctx2.focusedIndex=evt.index},setValue(ctx2,evt){set.value(ctx2,evt.value)},setFocusedValue(ctx2,evt){const nextValue=getNextValue(ctx2.focusedValue,evt.value);set.valueAtIndex(ctx2,ctx2.focusedIndex,nextValue)},revertInputValue(ctx2){const inputEl=dom.getFocusedInputEl(ctx2);dom.setValue(inputEl,ctx2.focusedValue)},syncInputValue(ctx2,evt){const inputEl=dom.getInputEl(ctx2,evt.index.toString());dom.setValue(inputEl,ctx2.value[evt.index])},syncInputElements(ctx2){const inputEls=dom.getInputEls(ctx2);inputEls.forEach((inputEl,index)=>{dom.setValue(inputEl,ctx2.value[index])})},setPastedValue(ctx2,evt){(0,import_dom_query3.raf)(()=>{const startIndex=Math.min(ctx2.focusedIndex,ctx2.filledValueLength);const left=startIndex>0?ctx2.valueAsString.substring(0,ctx2.focusedIndex):"";const right=evt.value.substring(0,ctx2.valueLength-startIndex);const value=left+right;set.value(ctx2,value.split(""))})},setValueAtIndex(ctx2,evt){const nextValue=getNextValue(ctx2.focusedValue,evt.value);set.valueAtIndex(ctx2,evt.index,nextValue)},clearValue(ctx2){const nextValue=Array.from({length:ctx2.valueLength}).fill("");set.value(ctx2,nextValue)},clearFocusedValue(ctx2){set.valueAtIndex(ctx2,ctx2.focusedIndex,"")},setFocusIndexToFirst(ctx2){ctx2.focusedIndex=0},setNextFocusedIndex(ctx2){ctx2.focusedIndex=Math.min(ctx2.focusedIndex+1,ctx2.valueLength-1)},setPrevFocusedIndex(ctx2){ctx2.focusedIndex=Math.max(ctx2.focusedIndex-1,0)},setLastValueFocusIndex(ctx2){(0,import_dom_query3.raf)(()=>{ctx2.focusedIndex=Math.min(ctx2.filledValueLength,ctx2.valueLength-1)})},blurFocusedInputIfNeeded(ctx2){if(!ctx2.blurOnComplete)return;(0,import_dom_query3.raf)(()=>{dom.getFocusedInputEl(ctx2)?.blur()})},requestFormSubmit(ctx2){if(!ctx2.name||!ctx2.isValueComplete)return;const inputEl=dom.getHiddenInputEl(ctx2);inputEl?.form?.requestSubmit()}}})}function assignValue(ctx,value){const arr=Array.isArray(value)?value:value.split("").filter(Boolean);arr.forEach((value2,index)=>{ctx.value[index]=value2})}function getNextValue(current,next){let nextValue=next;if(current[0]===next[0])nextValue=next[1];else if(current[0]===next[1])nextValue=next[0];return nextValue.split("")[nextValue.length-1]}var invoke={change(ctx){ctx.onValueChange?.({value:Array.from(ctx.value),valueAsString:ctx.valueAsString});const inputEl=dom.getHiddenInputEl(ctx);(0,import_form_utils.dispatchInputValueEvent)(inputEl,{value:ctx.valueAsString})}};var set={value(ctx,value){if((0,import_utils2.isEqual)(ctx.value,value))return;assignValue(ctx,value);invoke.change(ctx)},valueAtIndex(ctx,index,value){if((0,import_utils2.isEqual)(ctx.value[index],value))return;ctx.value[index]=value;invoke.change(ctx)}};0&&(module.exports={anatomy,connect,machine});
508
2
  //# sourceMappingURL=index.js.map