# API

The package root exports all public APIs. `ja-input-mask/core` exports pure functions and their types. `ja-input-mask/dom` exports `attachInputMask`, `AttachInputMaskOptions`, and `InputMaskController`.

## String formatters

All take `(value: string, options?: MaskOptions)` and return a string. `maskYen` accepts `YenOptions`.

| Function | Preset | Default format and completion |
| --- | --- | --- |
| `maskPostalCode` | `postalCode` | 3–4 digits |
| `maskPhoneNumber` | `phoneNumber` | Automatic domestic layout |
| `maskMobilePhone` | `mobilePhone` | 3–4–4 for `060`, `070`, `080`, `090`, excluding `0800` |
| `maskLandlinePhone` | `landlinePhone` | 10 digits with a 2–5 digit domestic area code |
| `maskIpPhone` | `ipPhone` | 3–4–4 for `050` |
| `maskTollFree` | `tollFree` | 4–3–3 for `0120`, 4–3–4 for `0800` |
| `maskDate` / `maskBirthDate` | `date` / `birthDate` | 4/2/2 digits, `YYYY/MM/DD` |
| `maskCorporateNumber` | `corporateNumber` | 13 digits |
| `maskInvoiceNumber` | `invoiceNumber` | Typed `T` then 13 digits. Leading `t`, `Ｔ` and `ｔ` become `T`. |
| `maskBankAccount` | `bankAccount` | 7 digits. Leading zeros remain. |
| `maskYen` | `yen` | Integer digits in thousands groups, optional leading minus. A leading `¥` or `￥` can be pasted as display decoration. |

Separators appear when the following group starts. Postal and phone masks accept common dash variants and phone masks accept spaces between digits. Date masks accept `/`, `.`, and common dash variants at the year and month boundaries, including full-width variants. Ambiguous dates such as `2024/2/29` remain visible and incomplete under the default policy. National and international dialing syntax such as `+81`, extensions, and service numbers outside the listed presets stays available as an unformatted draft.

Date masks report duplicate separators at the same boundary as invalid. With a `previous` snapshot, a separator that survived the edit takes priority over a newly inserted one. Without that history, the first separator at each boundary takes priority.

## Stateful formatting

```ts
applyInputMask(state, 'postalCode', options?)
applyInputMask(state, 'yen', yenOptions?)
applyInputMask(state, compiledMask)
const compiledMask = createInputMask({ preset: 'date', separator: '-' })
const custom = createInputMask({ groups: [2, 3], allowed: /[A-Z0-9]/u, separator: ' · ' })
custom({ value: 'AB１２３' }).value // 'AB · 123'
```

`InputState.value` is the **post-edit** text. `selectionStart` and `selectionEnd` are UTF-16 code-unit offsets in that text. Start defaults to the end of the text and end defaults to start. `selectionDirection` accepts `'forward'`, `'backward'`, or `'none'`. Set `inputType` to the native `InputEvent.inputType` when available. Pass the pre-edit `InputSnapshot` in `previous` to retain existing suffix data when truncating an insertion and to support deleting through a generated separator. `isComposing: true` bypasses formatting.

| `MaskResult` field | Meaning |
| --- | --- |
| `value` | Display value to put back in the field |
| `rawValue` | Accepted data without display separators, including a typed invoice `T` or a yen minus. Preserved excess data remains here. Rejected non-data is available in `rejected`. During composition this equals the input value. |
| `selectionStart`, `selectionEnd`, `selectionDirection` | Selection in `value` |
| `complete` | Expected display shape reached. During composition, with retained rejections, or with an unresolved phone layout this is `false`. |
| `rejected` | Original token text, UTF-16 offset, and reason (`invalid` or `overflow`). Offsets address the draft being processed. |
| `changed` | Display value or selection offsets changed relative to the post-edit snapshot |

## Options

| Option | Meaning |
| --- | --- |
| `separator` | Literal display separator. Use `''` for no separators. Its characters must be distinct from accepted data. |
| `maxDigits` | Positive maximum for data tokens, with a preset default where applicable. Prefixes are excluded. A custom mask counts accepted Unicode code points. A limit override leaves the preset completion length intact. |
| `fullWidthDigits` | `'convert'` (default) folds `０`–`９` to ASCII. `'preserve'` retains full-width data, with phone layout still inferred from digit values. |
| `invalid` | `'preserve'` (default) or `'drop'` |
| `overflow` | `'preserve'` (default) or `'truncate'`. An edit with a usable `previous` snapshot retains existing data before accepting new excess digits. If typing or pasting digits shortens the automatic phone limit and truncation would remove existing digits outside the edit or make the shorter limit invalid, the previous value and selection are restored. Discarded input digits are reported as `overflow` at their post-edit offsets. |
| `allowNegative` | Yen only. Defaults to `true`. |
| `groups` | Custom masks only. Non-empty list of positive group sizes. The sum defines the default limit and completion length. |
| `allowed` | Custom masks only. Regex that must match each complete code point after width handling. The regex is copied with `g`, `m`, and `y` removed. The default accepts ASCII and full-width digits. |

Retaining rejected tokens also retains the display text and structure around them. An explicitly enabled removal still applies to its own rejection class. Presets with no groups keep their identifiers continuous even if configured with a separator.

## DOM adapter

```ts
const handle = attachInputMask(input, {
  mask: { preset: 'postalCode' }, // or a compiled InputMask
  onChange(result, event) {},
})
handle.sync()
handle.isComposing
handle.detach()
```

Supported targets are `textarea` and `input` types that implement `setSelectionRange`, including `text`, `search`, and `tel`. Composition events and `InputEvent.isComposing` protect active composition text. A task queued by `compositionend` reads the committed value even when an engine sends commit events in a different order. `beforeinput` captures the pre-edit field for native deletion and clipping. With only `input`, ordinary formatting still runs using the post-edit value.

The controller's `isComposing` remains `true` during composition and while the queued commit is waiting to run. During that time, `sync()` passes `isComposing: true` to the mask and returns its result without changing the field or selection, running the queued commit early, or calling `onChange`. Built-in masks return the current text with `complete: false` during this period.

The adapter formats the restored value in the next task after the field's form resets, including when the field is associated through its `form` attribute. It reads the current value and selection and leaves `defaultValue` intact. A canceled reset has no effect on the mask. A reset that coincides with an IME commit is applied once the field can be formatted, with the accepted `reset` event taking priority over `compositionend`.

The adapter follows native Undo and Redo when the browser changes the value. If a paired `beforeinput` and `input` with `historyUndo` or `historyRedo` leave the value unchanged after a mask rewrite, it can restore a recorded value and selection and report the original `input` event through `onChange`. The adapter keeps up to 100 edits per field, records an IME commit as one edit, and discards the redo branch when a new edit changes the value. A successful form reset, a value change detected by `sync()`, or `detach()` clears the saved history.

For a focused, editable field, `Ctrl/Cmd+Z` and `Ctrl/Cmd+Shift+Z` can also restore history if the browser sends no editing events for the shortcut. The adapter waits until the next task, then checks that the shortcut was allowed, focus and the field snapshot still match, and the recorded history entry is still available. This fallback passes the original `keydown` event to `onChange`. Native history events, including a canceled `beforeinput`, take priority over the keyboard fallback. Composition and accepted form resets also take priority.

`onChange` runs after the result is applied and receives the original event or `null` from `sync()`. A queued IME commit or form reset reports `isComposing: false` in the callback. A result that leaves the last reported value and selection unchanged and requires no formatting produces no additional notification. The adapter is imperative and dispatches no extra DOM events. Code that assigns `input.value` can call `sync()` explicitly. The first attachment owns the field until `detach()`. Calling `attachInputMask` again returns the existing handle. Detach is idempotent, cancels pending composition and reset work, and clears `isComposing`.
