ja-input-mask 0.0.0-stage → 0.1.2

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/CHANGELOG.md ADDED
@@ -0,0 +1,18 @@
1
+ # Changelog
2
+
3
+ ## 0.1.2
4
+
5
+ - Restore the previous phone value and selection when truncating a replacement would discard the prefix that selected a shorter layout.
6
+ - Report newly inserted duplicate date separators as invalid while keeping the existing separator.
7
+
8
+ ## 0.1.1
9
+
10
+ - Linked all seven related projects and their live demos from both READMEs and the demo site.
11
+ - Added links to the public ja-input-mask demo and repository and updated the installation and CDN examples to 0.1.1.
12
+
13
+ ## 0.1.0
14
+
15
+ - Added pure TypeScript masks for postal codes, domestic phone numbers, dates, birth dates, corporate numbers, invoice registration numbers, bank accounts and integer yen amounts.
16
+ - Added custom groups, separators, accepted code points, width handling, and policies for rejected input and overflow.
17
+ - Added UTF-16 selection mapping, separator-aware deletion and an IME-aware DOM adapter.
18
+ - Added Japanese and English documentation, framework examples, browser tests, and a GitHub Pages demo.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Fusai Hanabi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,18 @@
1
+ Landline formatting metadata / 固定電話の区切りデータ
2
+
3
+ 出典:総務省「市外局番の一覧」(令和8年3月1日現在)および
4
+ 「電気通信番号指定状況」の固定電話番号表(1〜9)。2026年11月28日取得。
5
+
6
+ https://www.soumu.go.jp/main_sosiki/joho_tsusin/top/tel_number/shigai_list.html
7
+ https://www.soumu.go.jp/main_content/000141817.pdf
8
+ https://www.soumu.go.jp/main_sosiki/joho_tsusin/top/tel_number/number_shitei.html
9
+
10
+ 上記資料を加工して作成。市外局番および区切り位置に関係する先頭6桁を抽出し、
11
+ 重複する市外局番の範囲を連続区間に集約しています。
12
+
13
+ Sources: Ministry of Internal Affairs and Communications of Japan, area-code list
14
+ and fixed-line numbering designation tables (leading digits 1–9), retrieved on
15
+ 2026-11-28. Adapted by extracting area codes and exchange blocks, then merging
16
+ adjacent blocks with the same area-code length. See the source terms of use:
17
+ https://www.soumu.go.jp/menu_kyotsuu/policy/tyosaku.html
18
+ https://www.digital.go.jp/resources/open_data/public_data_license_v1.0
package/README.en.md ADDED
@@ -0,0 +1,84 @@
1
+ # ja-input-mask
2
+
3
+ [日本語](README.md) · [API](docs/API.md) · [Live demo](https://fusaihanabi.github.io/ja-input-mask/) · [Related libraries](#related-libraries) · [Design and research (Japanese)](docs/design.md) · [Examples](examples/README.md)
4
+
5
+ Input masks for Japanese web forms. The library handles partial edits, full-width digits, caret and selection offsets, paste, and IME composition. It ships as ESM with TypeScript declarations and zero runtime dependencies. `ja-input-mask/core` also runs in Node.js and supports TypeScript projects that omit the DOM library.
6
+
7
+ ## Install
8
+
9
+ Install by package name once the package is published on npm.
10
+
11
+ ```sh
12
+ npm install ja-input-mask
13
+ ```
14
+
15
+ To try this checkout, run `npm ci` and `npm pack`, then install the resulting `ja-input-mask-0.1.2.tgz` in your project.
16
+
17
+ ```ts
18
+ import { applyInputMask, maskPostalCode } from 'ja-input-mask/core'
19
+
20
+ maskPostalCode('12345') // '123-45'
21
+ const result = applyInputMask({ value: '20240229', selectionStart: 8 }, 'date')
22
+ // result.value === '2024/02/29'
23
+ // result.rawValue === '20240229'
24
+ // result.selectionStart === 10
25
+ ```
26
+
27
+ Use a text-like field with a suitable `inputmode` in the browser. Call `sync()` for an initial or programmatic value and `detach()` when disposing of the field.
28
+
29
+ ```ts
30
+ import { attachInputMask } from 'ja-input-mask/dom'
31
+
32
+ const input = document.querySelector<HTMLInputElement>('#postal')!
33
+ const controller = attachInputMask(input, {
34
+ mask: { preset: 'postalCode' },
35
+ onChange(result) {
36
+ console.log(result.value, result.rawValue, result.selectionStart)
37
+ },
38
+ })
39
+ controller.sync()
40
+ ```
41
+
42
+ Presets cover postal codes, domestic phone numbers (automatic, mobile, landline, IP and toll-free), dates, birth dates, corporate numbers, invoice registration numbers, bank account numbers, and integer yen amounts. Landline formatting uses Japanese area codes and exchange ranges. Ambiguous phone drafts retain their supplied separators. Full-width digits are converted by default. Invalid and excess input remains visible by default and is reported in `rejected`. Set `invalid: 'drop'` and `overflow: 'truncate'` to remove the respective characters.
43
+
44
+ `complete` means the draft has the expected shape. Validate existence, number assignments, dates, and business rules separately. You can normalize at the form boundary with `normalize-ja-input` and validate the resulting display value with `ja-form-validators`. The DOM adapter pauses formatting during composition. Use `ja-ime-utils` to track IME state and control Enter submission. [Integration examples](examples/README.md)
45
+
46
+ ### Browser ESM via CDN
47
+
48
+ Once published on npm, import a specific release from a `<script type="module">`. Before release, run `npm run build`, serve the generated `dist/` directory with your site, and import `./dist/dom.js`.
49
+
50
+ ```js
51
+ import { attachInputMask } from 'https://cdn.jsdelivr.net/npm/ja-input-mask@0.1.2/dist/dom.js'
52
+ ```
53
+
54
+ The UNPKG URL is `https://unpkg.com/ja-input-mask@0.1.2/dist/dom.js`.
55
+
56
+ ## Related libraries
57
+
58
+ Fusai Hanabi OSS includes projects for normalizing and validating input and working with committed values. [Fusai Hanabi website](https://dl.fusai-hanabi.com/)
59
+
60
+ | Project | Purpose | Demo |
61
+ | --- | --- | --- |
62
+ | [normalize-ja-input](https://github.com/fusaihanabi/normalize-ja-input) | Normalize character width, spaces, and hyphen variants | [Live demo](https://fusaihanabi.github.io/normalize-ja-input/) |
63
+ | [ja-form-validators](https://github.com/fusaihanabi/ja-form-validators) | Validate postal codes, phone numbers, and furigana | [Live demo](https://fusaihanabi.github.io/ja-form-validators/) |
64
+ | [tiny-ja-date](https://github.com/fusaihanabi/tiny-ja-date) | Format Japanese dates and calculate business days | [Live demo](https://fusaihanabi.github.io/tiny-ja-date/) |
65
+ | [ja-ime-utils](https://github.com/fusaihanabi/ja-ime-utils) | Track IME state and control Enter submission | [Live demo](https://fusaihanabi.github.io/ja-ime-utils/) |
66
+ | [ja-char-check](https://github.com/fusaihanabi/ja-char-check) | Check character sets, encoding compatibility, and byte counts | [Live demo](https://fusaihanabi.github.io/ja-char-check/) |
67
+ | [tiny-ja-money](https://github.com/fusaihanabi/tiny-ja-money) | Parse and format yen, calculate tax, and allocate amounts | [Live demo](https://fusaihanabi.github.io/tiny-ja-money/) |
68
+ | [ja-zengin-utils](https://github.com/fusaihanabi/ja-zengin-utils) | Handle Zengin kana and fixed-width Japanese bank transfer files | [Live demo](https://fusaihanabi.github.io/ja-zengin-utils/) |
69
+
70
+ ## Development and demo
71
+
72
+ ```sh
73
+ npm ci
74
+ npm run typecheck
75
+ npm test
76
+ npx playwright install chromium firefox webkit
77
+ npm run test:browser
78
+ npm run check:package
79
+ npm run demo
80
+ ```
81
+
82
+ The demo shows incoming and formatted values, the unmasked value, UTF-16 selection offsets, IME state, and an event log. `npm run build:demo` writes the GitHub Pages site to `.pages/`. To publish it, choose GitHub Actions as the Pages source and run the manual `Deploy demo to GitHub Pages` workflow.
83
+
84
+ MIT licensed. See [NOTICE](NOTICE) for fixed-line numbering data attribution.
package/README.md CHANGED
@@ -1,3 +1,118 @@
1
- # Temporary Holding Version
1
+ # ja-input-mask
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [English](README.en.md) · [API](docs/API.md) · [ライブデモ](https://fusaihanabi.github.io/ja-input-mask/) · [関連ライブラリ](#関連ライブラリ) · [設計・調査](docs/design.md) · [利用例](examples/README.md)
4
+
5
+ 日本のWebフォーム向けの入力マスクです。全角数字、入力途中の値、選択範囲、貼り付け、日本語IMEを扱います。TypeScript型定義付きのESMで、ランタイム依存はありません。`ja-input-mask/core` はDOMの型やグローバルを使わず、Node.jsでも動作します。
6
+
7
+ ## インストール
8
+
9
+ npm公開後はパッケージ名でインストールできます。
10
+
11
+ ```sh
12
+ npm install ja-input-mask
13
+ ```
14
+
15
+ このリポジトリのコードを試す場合は `npm ci` と `npm pack` を実行し、生成された `ja-input-mask-0.1.2.tgz` を利用側のプロジェクトでインストールできます。
16
+
17
+ ```ts
18
+ import { applyInputMask, maskPostalCode } from 'ja-input-mask/core'
19
+
20
+ maskPostalCode('12345') // '123-45'
21
+ const result = applyInputMask({ value: '20240229', selectionStart: 8 }, 'date')
22
+ // result.value === '2024/02/29'
23
+ // result.rawValue === '20240229'
24
+ // result.selectionStart === 10
25
+ ```
26
+
27
+ ## ブラウザで使う
28
+
29
+ ```html
30
+ <label for="postal">郵便番号</label>
31
+ <input id="postal" type="text" inputmode="numeric" autocomplete="postal-code">
32
+ ```
33
+
34
+ ```ts
35
+ import { attachInputMask } from 'ja-input-mask/dom'
36
+
37
+ const input = document.querySelector<HTMLInputElement>('#postal')!
38
+ const controller = attachInputMask(input, {
39
+ mask: { preset: 'postalCode' },
40
+ onChange(result) {
41
+ console.log(result.value, result.rawValue, result.selectionStart)
42
+ },
43
+ })
44
+ controller.sync() // 初期値やスクリプトで設定した値にも適用
45
+ // コンポーネントを破棄するときに controller.detach()
46
+ ```
47
+
48
+ 数値入力にも、選択範囲を操作できる `type="text"` と `inputmode` を組み合わせます。`maxlength` は区切り文字と変換途中の文字にも適用されるため、マスク上の上限には `maxDigits` を使用してください。React、Vue、Vanilla JSの接続例を収録しています。 [利用例](examples/README.md)
49
+
50
+ ### CDNから読み込む
51
+
52
+ npm公開後は、公開版のバージョンを指定して `<script type="module">` から読み込めます。公開前にブラウザで使う場合は、`npm run build` で生成した `dist/` を静的サーバーに配置し、`./dist/dom.js` を読み込んでください。
53
+
54
+ ```js
55
+ import { attachInputMask } from 'https://cdn.jsdelivr.net/npm/ja-input-mask@0.1.2/dist/dom.js'
56
+ ```
57
+
58
+ UNPKGのURLは `https://unpkg.com/ja-input-mask@0.1.2/dist/dom.js` です。
59
+
60
+ ## プリセット
61
+
62
+ | 用途 | プリセット | 表示例 |
63
+ | --- | --- | --- |
64
+ | 郵便番号 | `postalCode` | `123-4567` |
65
+ | 電話番号 | `phoneNumber`、`mobilePhone`、`landlinePhone`、`ipPhone`、`tollFree` | `03-1234-5678`、`0422-24-3456`、`0800-123-4567` |
66
+ | 日付・生年月日 | `date`、`birthDate` | `2024/02/29` |
67
+ | 法人番号 | `corporateNumber` | `0001234567890` |
68
+ | インボイス登録番号 | `invoiceNumber` | `T0001234567890` |
69
+ | 銀行口座番号 | `bankAccount` | `0001234` |
70
+ | 円の金額(整数) | `yen` | `-1,234,567` |
71
+
72
+ 電話番号は国内表記を対象に、番号種別と市外局番に応じて区切ります。区切り位置が確定しない間は入力された区切りをそのまま表示します。全角数字は既定で半角に変換し、解釈できない文字や上限を超えた文字は既定で入力欄に保持して `rejected` に記録します。`invalid: 'drop'` と `overflow: 'truncate'` を選ぶと、それぞれ該当の文字を取り除きます。`complete` は形式上の完成を示します。番号の実在、割当、チェックディジット、日付の実在、年齢などの妥当性は別途検証してください。
73
+
74
+ ## 姉妹ライブラリと組み合わせる
75
+
76
+ ```ts
77
+ import { jaInputPresets, normalizeJaInput } from 'normalize-ja-input'
78
+ import { validateStrictPhoneNumberJP } from 'ja-form-validators'
79
+ import { applyInputMask } from 'ja-input-mask/core'
80
+
81
+ function validatePhoneOnSubmit(draft: string) {
82
+ const normalized = normalizeJaInput(draft, jaInputPresets.phone)
83
+ const masked = applyInputMask({ value: normalized }, 'phoneNumber')
84
+ return validateStrictPhoneNumberJP(masked.value, { format: 'domestic' })
85
+ }
86
+ ```
87
+
88
+ `normalize-ja-input` で表記ゆれを正規化し、`ja-form-validators` で確定値を検証します。検証にはフィールドの `value` を使い、`rawValue` を使う場合は `complete` と拒否内容を先に確認してください。IME変換の確定とEnter送信を制御する用途には `ja-ime-utils` を組み合わせられます。
89
+
90
+ ## 関連ライブラリ
91
+
92
+ Fusai Hanabi OSSでは、入力の整形に続く正規化・検証や、確定した値の処理に使えるライブラリを開発しています。 [Fusai Hanabi公式サイト](https://dl.fusai-hanabi.com/)
93
+
94
+ | プロジェクト | 用途 | デモ |
95
+ | --- | --- | --- |
96
+ | [normalize-ja-input](https://github.com/fusaihanabi/normalize-ja-input) | 全角・半角、空白、ハイフンなどの表記ゆれを正規化 | [ライブデモ](https://fusaihanabi.github.io/normalize-ja-input/) |
97
+ | [ja-form-validators](https://github.com/fusaihanabi/ja-form-validators) | 郵便番号、電話番号、フリガナなどの入力を検証 | [ライブデモ](https://fusaihanabi.github.io/ja-form-validators/) |
98
+ | [tiny-ja-date](https://github.com/fusaihanabi/tiny-ja-date) | 日本語の日付表示と営業日計算 | [ライブデモ](https://fusaihanabi.github.io/tiny-ja-date/) |
99
+ | [ja-ime-utils](https://github.com/fusaihanabi/ja-ime-utils) | IMEの変換状態を追跡し、Enter送信を制御 | [ライブデモ](https://fusaihanabi.github.io/ja-ime-utils/) |
100
+ | [ja-char-check](https://github.com/fusaihanabi/ja-char-check) | 文字集合や文字コードの互換性、バイト数を検査 | [ライブデモ](https://fusaihanabi.github.io/ja-char-check/) |
101
+ | [tiny-ja-money](https://github.com/fusaihanabi/tiny-ja-money) | 確定した円金額の読み取り、整形、税や按分の計算 | [ライブデモ](https://fusaihanabi.github.io/tiny-ja-money/) |
102
+ | [ja-zengin-utils](https://github.com/fusaihanabi/ja-zengin-utils) | 全銀カナと総合振込の固定長ファイルを処理 | [ライブデモ](https://fusaihanabi.github.io/ja-zengin-utils/) |
103
+
104
+ ## 開発とデモ
105
+
106
+ ```sh
107
+ npm ci
108
+ npm run typecheck
109
+ npm test
110
+ npx playwright install chromium firefox webkit
111
+ npm run test:browser
112
+ npm run check:package
113
+ npm run demo
114
+ ```
115
+
116
+ `npm run demo` の表示URLで、整形前の入力、画面の値、マスクを除いた値、選択範囲、IME状態、イベント履歴を確認できます。`npm run build:demo` はGitHub Pages用の `.pages/` を生成します。公開を行う場合は、リポジトリの Pages 設定で GitHub Actions を選び、`Deploy demo to GitHub Pages` を手動実行します。ブラウザテストの内容と実IMEの確認手順は設計資料に記載しています。 [設計・調査](docs/design.md)
117
+
118
+ MITライセンス。固定電話の区切りデータの出典は [NOTICE](NOTICE) を参照してください。
package/dist/core.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ import type { InputMask, InputMaskOptions, InputState, MaskOptions, MaskResult, PresetName, YenOptions } from './types.js';
2
+ export type * from './types.js';
3
+ /** Compile reusable options into a pure, DOM-independent mask. */
4
+ export declare function createInputMask(options: InputMaskOptions): InputMask;
5
+ export declare function applyInputMask(state: InputState, mask: InputMask): MaskResult;
6
+ export declare function applyInputMask(state: InputState, mask: 'yen', options?: YenOptions): MaskResult;
7
+ export declare function applyInputMask(state: InputState, mask: PresetName, options?: MaskOptions): MaskResult;
8
+ export declare const maskPostalCode: (value: string, options?: MaskOptions) => string;
9
+ export declare const maskPhoneNumber: (value: string, options?: MaskOptions) => string;
10
+ export declare const maskMobilePhone: (value: string, options?: MaskOptions) => string;
11
+ export declare const maskLandlinePhone: (value: string, options?: MaskOptions) => string;
12
+ export declare const maskIpPhone: (value: string, options?: MaskOptions) => string;
13
+ export declare const maskTollFree: (value: string, options?: MaskOptions) => string;
14
+ export declare const maskDate: (value: string, options?: MaskOptions) => string;
15
+ export declare const maskBirthDate: (value: string, options?: MaskOptions) => string;
16
+ export declare const maskCorporateNumber: (value: string, options?: MaskOptions) => string;
17
+ export declare const maskInvoiceNumber: (value: string, options?: MaskOptions) => string;
18
+ export declare const maskBankAccount: (value: string, options?: MaskOptions) => string;
19
+ export declare function maskYen(value: string, options?: YenOptions): string;
package/dist/core.js ADDED
@@ -0,0 +1,326 @@
1
+ import { phoneLayout } from './phone.js';
2
+ const dashAliases = ['-', '-', '−', '‐', '‑'];
3
+ const digit = /^[0-90-9]$/u;
4
+ const asciiDigits = (value) => value.replace(/[0-9]/gu, (character) => String.fromCharCode(character.charCodeAt(0) - 0xfee0));
5
+ function fixed(length, breaks, separator = '', aliases) {
6
+ return { length, separator, ...(aliases && { aliases }), layout: () => ({ length, breaks }) };
7
+ }
8
+ function phone(preset) {
9
+ return {
10
+ separator: '-', aliases: [...dashAliases, ' ', ' '], length: preset === 'landlinePhone' ? 10 : 11,
11
+ layout(data) {
12
+ const format = phoneLayout(data, preset);
13
+ return format && { breaks: [format.firstBreak, format.secondBreak], length: format.length };
14
+ },
15
+ };
16
+ }
17
+ const postalCode = /* @__PURE__ */ fixed(7, [3], '-', dashAliases);
18
+ const date = { ... /* @__PURE__ */fixed(8, [4, 6], '/', ['/', '/', '.', '.', ...dashAliases]), date: true };
19
+ const corporateNumber = /* @__PURE__ */ fixed(13, []);
20
+ const invoiceNumber = { ...corporateNumber, prefix: 'invoice' };
21
+ const bankAccount = /* @__PURE__ */ fixed(7, []);
22
+ function yen(allowNegative) {
23
+ return {
24
+ separator: ',', aliases: [',', ','], ...(allowNegative && { prefix: 'yen' }), yen: true,
25
+ layout(data) {
26
+ const breaks = [];
27
+ for (let index = data.length % 3 || 3; index < data.length; index += 3)
28
+ breaks.push(index);
29
+ return { breaks };
30
+ },
31
+ };
32
+ }
33
+ function definition(options) {
34
+ if ('groups' in options) {
35
+ if (options.groups.length === 0 || options.groups.some((size) => !Number.isSafeInteger(size) || size < 1)) {
36
+ throw new RangeError('groups must contain positive safe integers');
37
+ }
38
+ let length = 0;
39
+ const breaks = options.groups.map((size) => length += size).slice(0, -1);
40
+ if (!Number.isSafeInteger(length))
41
+ throw new RangeError('the sum of groups must be a safe integer');
42
+ const allowed = options.allowed && new RegExp(`^(?:${options.allowed.source})(?![\\s\\S])`, options.allowed.flags.replace(/[gmy]/gu, ''));
43
+ return { ...fixed(length, breaks, '-'), ...(allowed && { allowed }) };
44
+ }
45
+ switch (options.preset) {
46
+ case 'postalCode': return postalCode;
47
+ case 'date':
48
+ case 'birthDate': return date;
49
+ case 'corporateNumber': return corporateNumber;
50
+ case 'invoiceNumber': return invoiceNumber;
51
+ case 'bankAccount': return bankAccount;
52
+ case 'yen': return yen(options.allowNegative ?? true);
53
+ case 'phoneNumber':
54
+ case 'mobilePhone':
55
+ case 'landlinePhone':
56
+ case 'ipPhone':
57
+ case 'tollFree': return phone(options.preset);
58
+ }
59
+ }
60
+ function selection(state) {
61
+ const clamp = (offset, fallback) => offset === undefined || Number.isNaN(offset)
62
+ ? fallback : Math.max(0, Math.min(state.value.length, Math.trunc(offset)));
63
+ const start = clamp(state.selectionStart, state.value.length);
64
+ const end = clamp(state.selectionEnd, start);
65
+ return { value: state.value, selectionStart: Math.min(start, end), selectionEnd: end,
66
+ selectionDirection: state.selectionDirection ?? 'none' };
67
+ }
68
+ function tokenize(value, mask, separators, normalize, allowed, separatorBoundary = 0) {
69
+ const tokens = [];
70
+ for (let start = 0; start < value.length;) {
71
+ const character = String.fromCodePoint(value.codePointAt(start));
72
+ const prefix = start === 0 && (mask.prefix === 'invoice' && /^[TtTt]$/u.test(character)
73
+ ? 'T' : mask.prefix === 'yen' && /^[--−]$/u.test(character) ? '-' : undefined);
74
+ const currency = mask.yen && /^[¥¥]$/u.test(character) && (start === 0 ||
75
+ tokens.length === 1 && tokens[0]?.kind === 'prefix');
76
+ const separator = separators.find((candidate) => value.startsWith(candidate, start) &&
77
+ (start >= separatorBoundary || start + candidate.length <= separatorBoundary));
78
+ const source = !prefix && separator ? separator : character;
79
+ const text = prefix || normalize(source);
80
+ const kind = prefix ? 'prefix' : separator || currency ? 'separator' : allowed.test(text) ? 'data' : 'invalid';
81
+ const end = start + source.length;
82
+ tokens.push({ source, text, kind, start, end });
83
+ start = end;
84
+ }
85
+ return tokens;
86
+ }
87
+ function matchingEdges(current, previous) {
88
+ if (!previous)
89
+ return { leading: 0, trailing: current.value.length };
90
+ const limit = Math.min(previous.selectionStart, current.selectionStart);
91
+ let leading = 0;
92
+ while (leading < limit && previous.value[leading] === current.value[leading])
93
+ leading++;
94
+ const trailingLimit = Math.min(previous.value.length - previous.selectionEnd, current.value.length - leading);
95
+ let trailing = 0;
96
+ while (trailing < trailingLimit && previous.value.at(-trailing - 1) === current.value.at(-trailing - 1))
97
+ trailing++;
98
+ return { leading, trailing: current.value.length - trailing };
99
+ }
100
+ function rejectedCharacters(tokens) {
101
+ return tokens.flatMap((token) => token.rejection
102
+ ? [{ value: token.source, index: token.start, reason: token.rejection }] : []);
103
+ }
104
+ function remap(offset, pieces, tokens, formatted) {
105
+ let left = 0;
106
+ let tokenIndex = 0;
107
+ for (const piece of pieces) {
108
+ const { token, start, text } = piece;
109
+ if (offset <= token.start) {
110
+ if (!formatted)
111
+ return start;
112
+ while (tokens[tokenIndex] && tokens[tokenIndex].start < offset) {
113
+ const skipped = tokens[tokenIndex++];
114
+ if (skipped.kind === 'separator')
115
+ return start;
116
+ }
117
+ return left;
118
+ }
119
+ if (offset <= token.end)
120
+ return start + Math.min(offset - token.start, text.length);
121
+ left = start + text.length;
122
+ while (tokens[tokenIndex] && tokens[tokenIndex].end <= token.end)
123
+ tokenIndex++;
124
+ }
125
+ return left;
126
+ }
127
+ function deletedSeparator(current, previous, inputType, parse, format) {
128
+ const backward = inputType === 'deleteContentBackward';
129
+ if (!previous || !backward && inputType !== 'deleteContentForward')
130
+ return current;
131
+ const old = selection(previous);
132
+ const removed = old.value.length - current.value.length;
133
+ if (old.selectionStart !== old.selectionEnd || removed <= 0)
134
+ return current;
135
+ const start = old.selectionStart - (backward ? removed : 0);
136
+ const end = start + removed;
137
+ if (start < 0 || old.value.slice(0, start) + old.value.slice(end) !== current.value)
138
+ return current;
139
+ const tokens = parse(old.value);
140
+ const index = tokens.findIndex((token) => token.kind === 'separator' && token.start <= start && token.end >= end);
141
+ if (index < 0)
142
+ return current;
143
+ const { rawValue } = format(old);
144
+ if (format({ value: rawValue }).value !== old.value)
145
+ return current;
146
+ const neighbor = tokens[index + (backward ? -1 : 1)];
147
+ if (neighbor?.kind !== 'data')
148
+ return current;
149
+ const separator = tokens[index];
150
+ const from = Math.min(neighbor.start, separator.start);
151
+ const to = Math.max(neighbor.end, separator.end);
152
+ return { value: old.value.slice(0, from) + old.value.slice(to), selectionStart: from,
153
+ selectionEnd: from, selectionDirection: current.selectionDirection };
154
+ }
155
+ /** Compile reusable options into a pure, DOM-independent mask. */
156
+ export function createInputMask(options) {
157
+ return compileMask(definition(options), options);
158
+ }
159
+ function compileMask(mask, options) {
160
+ const { maxDigits, invalid = 'preserve', overflow = 'preserve', fullWidthDigits = 'convert' } = options;
161
+ if (maxDigits !== undefined && (!Number.isSafeInteger(maxDigits) || maxDigits < 1)) {
162
+ throw new RangeError('maxDigits must be a positive safe integer');
163
+ }
164
+ const normalize = fullWidthDigits === 'convert' ? asciiDigits : (value) => value;
165
+ const allowed = mask.allowed ?? digit;
166
+ const separator = options.separator ?? mask.separator;
167
+ const separators = [...new Set([separator, ...mask.aliases ?? []])].filter(Boolean).sort((a, b) => b.length - a.length);
168
+ if (separators.some((value) => [...value].some((unit) => allowed.test(normalize(unit)))) ||
169
+ /^[TtTt]/u.test(separator) && mask.prefix === 'invoice' ||
170
+ /^[--−¥¥]/u.test(separator) && mask.yen) {
171
+ throw new RangeError('separator characters must be distinct from data and field prefixes');
172
+ }
173
+ const parse = (value, boundary) => tokenize(value, mask, separators, normalize, allowed, boundary);
174
+ const layoutFor = (data) => mask.layout(mask.allowed ? '' : asciiDigits(data.map((token) => token.text).join('')));
175
+ function format(state) {
176
+ const original = selection(state);
177
+ if (state.isComposing)
178
+ return { ...original, rawValue: state.value, complete: false, rejected: [], changed: false };
179
+ const previous = state.previous && selection(state.previous);
180
+ const current = deletedSeparator(original, state.previous, state.inputType, parse, format);
181
+ const { leading, trailing } = matchingEdges(current, previous);
182
+ // An inserted alias must not absorb the start of an intact multi-character date separator.
183
+ const separatorBoundary = mask.date && separator.length > 1 && current.value.startsWith(separator, trailing)
184
+ ? trailing : undefined;
185
+ const tokens = parse(current.value, separatorBoundary);
186
+ const data = tokens.filter((token) => token.kind === 'data');
187
+ const initialLayout = layoutFor(data);
188
+ const maximum = maxDigits ?? initialLayout?.length ?? mask.length ?? Infinity;
189
+ const survived = (token) => token.end <= leading || token.start >= trailing;
190
+ // When clipping a native edit, give existing suffix data the same priority as the prefix.
191
+ const priorities = overflow === 'truncate' && previous && data.length > maximum
192
+ ? [...data.filter(survived), ...data.filter((token) => !survived(token))] : data;
193
+ for (const token of priorities.slice(maximum)) {
194
+ token.rejection = 'overflow';
195
+ token.dropped = overflow === 'truncate';
196
+ }
197
+ let previousFormatted;
198
+ const wasDecoration = (token) => {
199
+ if (!previous || !survived(token))
200
+ return false;
201
+ if (previousFormatted === undefined) {
202
+ const { rawValue } = format({ value: previous.value });
203
+ previousFormatted = format({ value: rawValue }).value === previous.value;
204
+ }
205
+ return previousFormatted;
206
+ };
207
+ let dataBefore = 0;
208
+ let dateSeparator;
209
+ for (const token of tokens) {
210
+ if (token.kind === 'data') {
211
+ dataBefore++;
212
+ dateSeparator = undefined;
213
+ }
214
+ if (token.kind !== 'separator')
215
+ continue;
216
+ if (mask.date) {
217
+ if (dateSeparator) {
218
+ if (survived(token) && !survived(dateSeparator)) {
219
+ dateSeparator.kind = 'invalid';
220
+ dateSeparator = token;
221
+ }
222
+ else if (!wasDecoration(token)) {
223
+ token.kind = 'invalid';
224
+ }
225
+ }
226
+ else if (initialLayout?.breaks.includes(dataBefore) || wasDecoration(token)) {
227
+ dateSeparator = token;
228
+ }
229
+ else {
230
+ token.kind = 'invalid';
231
+ }
232
+ }
233
+ else if (dataBefore === 0 && !(mask.yen && /^[¥¥]$/u.test(token.source)) && !wasDecoration(token)) {
234
+ token.kind = 'invalid';
235
+ }
236
+ }
237
+ for (const token of tokens) {
238
+ if (token.kind === 'invalid') {
239
+ token.rejection = 'invalid';
240
+ token.dropped = invalid === 'drop';
241
+ }
242
+ }
243
+ const digits = data.filter((token) => !token.dropped);
244
+ const layout = digits.length === data.length ? initialLayout : layoutFor(digits);
245
+ // Restore the edit if a shorter phone layout would clip away the prefix that selected it.
246
+ if (overflow === 'truncate' && maxDigits === undefined && initialLayout?.length === maximum &&
247
+ layout?.length !== maximum && previous && previous.selectionStart < previous.selectionEnd &&
248
+ leading === previous.selectionStart && current.value.length - trailing === previous.value.length - previous.selectionEnd) {
249
+ const restored = format(previous);
250
+ const previousLength = mask.layout(asciiDigits(restored.rawValue))?.length ?? 0;
251
+ if (previousLength > maximum) {
252
+ const discarded = tokens.filter((token) => !survived(token));
253
+ for (const token of discarded) {
254
+ if (token.kind === 'data')
255
+ token.rejection = 'overflow';
256
+ }
257
+ return { ...restored, ...previous, complete: restored.complete && restored.value === previous.value,
258
+ changed: true, rejected: rejectedCharacters(discarded) };
259
+ }
260
+ }
261
+ const kept = tokens.filter((token) => !token.dropped);
262
+ const accepted = kept.filter((token) => token.kind === 'data' || token.kind === 'prefix');
263
+ const rawValue = accepted.map((token) => token.text).join('');
264
+ const preserve = kept.some((token) => token.rejection);
265
+ const formatted = !preserve && layout !== undefined;
266
+ const breaks = new Set(layout?.breaks);
267
+ let value = '';
268
+ let count = 0;
269
+ const pieces = [];
270
+ for (const token of kept) {
271
+ if (formatted && token.kind === 'separator')
272
+ continue;
273
+ if (formatted && token.kind === 'data' && breaks.has(count))
274
+ value += separator;
275
+ if (token.kind === 'data')
276
+ count++;
277
+ const text = preserve || token.kind === 'separator' ? token.source : token.text;
278
+ pieces.push({ token, start: value.length, text });
279
+ value += text;
280
+ }
281
+ const selectionStart = remap(current.selectionStart, pieces, tokens, formatted);
282
+ const selectionEnd = remap(current.selectionEnd, pieces, tokens, formatted);
283
+ const complete = formatted && (mask.yen ? digits.length > 0 : digits.length === layout.length) &&
284
+ (mask.prefix !== 'invoice' || rawValue.startsWith('T'));
285
+ return { value, rawValue, complete, rejected: rejectedCharacters(tokens), selectionStart, selectionEnd,
286
+ selectionDirection: current.selectionDirection, changed: value !== original.value ||
287
+ selectionStart !== original.selectionStart || selectionEnd !== original.selectionEnd };
288
+ }
289
+ return format;
290
+ }
291
+ const defaults = /* @__PURE__ */ new Map();
292
+ export function applyInputMask(state, mask, options) {
293
+ if (typeof mask === 'function')
294
+ return mask(state);
295
+ if (options) {
296
+ const { allowNegative, ...common } = options;
297
+ return createInputMask(mask === 'yen' && allowNegative !== undefined
298
+ ? { ...common, preset: mask, allowNegative } : { ...common, preset: mask })(state);
299
+ }
300
+ let compiled = defaults.get(mask);
301
+ if (!compiled) {
302
+ compiled = createInputMask({ preset: mask });
303
+ defaults.set(mask, compiled);
304
+ }
305
+ return compiled(state);
306
+ }
307
+ function formatter(mask) {
308
+ const defaultMask = compileMask(mask, {});
309
+ return (value, options) => (options ? compileMask(mask, options) : defaultMask)({ value }).value;
310
+ }
311
+ export const maskPostalCode = /* @__PURE__ */ formatter(postalCode);
312
+ export const maskPhoneNumber = /* @__PURE__ */ formatter(/* @__PURE__ */ phone('phoneNumber'));
313
+ export const maskMobilePhone = /* @__PURE__ */ formatter(/* @__PURE__ */ phone('mobilePhone'));
314
+ export const maskLandlinePhone = /* @__PURE__ */ formatter(/* @__PURE__ */ phone('landlinePhone'));
315
+ export const maskIpPhone = /* @__PURE__ */ formatter(/* @__PURE__ */ phone('ipPhone'));
316
+ export const maskTollFree = /* @__PURE__ */ formatter(/* @__PURE__ */ phone('tollFree'));
317
+ export const maskDate = /* @__PURE__ */ formatter(date);
318
+ export const maskBirthDate = maskDate;
319
+ export const maskCorporateNumber = /* @__PURE__ */ formatter(corporateNumber);
320
+ export const maskInvoiceNumber = /* @__PURE__ */ formatter(invoiceNumber);
321
+ export const maskBankAccount = /* @__PURE__ */ formatter(bankAccount);
322
+ const formatSignedYen = /* @__PURE__ */ formatter(/* @__PURE__ */ yen(true));
323
+ const formatUnsignedYen = /* @__PURE__ */ formatter(/* @__PURE__ */ yen(false));
324
+ export function maskYen(value, options) {
325
+ return (options?.allowNegative === false ? formatUnsignedYen : formatSignedYen)(value, options);
326
+ }
package/dist/dom.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ import type { InputMask, InputMaskOptions, MaskResult } from './types.js';
2
+ type TextField = HTMLInputElement | HTMLTextAreaElement;
3
+ export interface AttachInputMaskOptions {
4
+ readonly mask: InputMask | InputMaskOptions;
5
+ /** Runs after the field reflects the finalized result. event is null for sync(). */
6
+ readonly onChange?: (result: MaskResult, event: Event | null) => void;
7
+ }
8
+ export interface InputMaskController {
9
+ readonly isComposing: boolean;
10
+ sync(): MaskResult;
11
+ detach(): void;
12
+ }
13
+ /** Attach to a text-like field. Attaching twice returns the existing controller. */
14
+ export declare function attachInputMask(field: TextField, options: AttachInputMaskOptions): InputMaskController;
15
+ export {};