ja-input-mask 0.1.1 → 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 CHANGED
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
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
+
3
8
  ## 0.1.1
4
9
 
5
10
  - Linked all seven related projects and their live demos from both READMEs and the demo site.
package/README.en.md CHANGED
@@ -12,7 +12,7 @@ Install by package name once the package is published on npm.
12
12
  npm install ja-input-mask
13
13
  ```
14
14
 
15
- To try this checkout, run `npm ci` and `npm pack`, then install the resulting `ja-input-mask-0.1.1.tgz` in your project.
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
16
 
17
17
  ```ts
18
18
  import { applyInputMask, maskPostalCode } from 'ja-input-mask/core'
@@ -48,10 +48,10 @@ Presets cover postal codes, domestic phone numbers (automatic, mobile, landline,
48
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
49
 
50
50
  ```js
51
- import { attachInputMask } from 'https://cdn.jsdelivr.net/npm/ja-input-mask@0.1.1/dist/dom.js'
51
+ import { attachInputMask } from 'https://cdn.jsdelivr.net/npm/ja-input-mask@0.1.2/dist/dom.js'
52
52
  ```
53
53
 
54
- The UNPKG URL is `https://unpkg.com/ja-input-mask@0.1.1/dist/dom.js`.
54
+ The UNPKG URL is `https://unpkg.com/ja-input-mask@0.1.2/dist/dom.js`.
55
55
 
56
56
  ## Related libraries
57
57
 
package/README.md CHANGED
@@ -12,7 +12,7 @@ npm公開後はパッケージ名でインストールできます。
12
12
  npm install ja-input-mask
13
13
  ```
14
14
 
15
- このリポジトリのコードを試す場合は `npm ci` と `npm pack` を実行し、生成された `ja-input-mask-0.1.1.tgz` を利用側のプロジェクトでインストールできます。
15
+ このリポジトリのコードを試す場合は `npm ci` と `npm pack` を実行し、生成された `ja-input-mask-0.1.2.tgz` を利用側のプロジェクトでインストールできます。
16
16
 
17
17
  ```ts
18
18
  import { applyInputMask, maskPostalCode } from 'ja-input-mask/core'
@@ -52,10 +52,10 @@ controller.sync() // 初期値やスクリプトで設定した値にも適用
52
52
  npm公開後は、公開版のバージョンを指定して `<script type="module">` から読み込めます。公開前にブラウザで使う場合は、`npm run build` で生成した `dist/` を静的サーバーに配置し、`./dist/dom.js` を読み込んでください。
53
53
 
54
54
  ```js
55
- import { attachInputMask } from 'https://cdn.jsdelivr.net/npm/ja-input-mask@0.1.1/dist/dom.js'
55
+ import { attachInputMask } from 'https://cdn.jsdelivr.net/npm/ja-input-mask@0.1.2/dist/dom.js'
56
56
  ```
57
57
 
58
- UNPKGのURLは `https://unpkg.com/ja-input-mask@0.1.1/dist/dom.js` です。
58
+ UNPKGのURLは `https://unpkg.com/ja-input-mask@0.1.2/dist/dom.js` です。
59
59
 
60
60
  ## プリセット
61
61
 
package/dist/core.js CHANGED
@@ -65,7 +65,7 @@ function selection(state) {
65
65
  return { value: state.value, selectionStart: Math.min(start, end), selectionEnd: end,
66
66
  selectionDirection: state.selectionDirection ?? 'none' };
67
67
  }
68
- function tokenize(value, mask, separators, normalize, allowed) {
68
+ function tokenize(value, mask, separators, normalize, allowed, separatorBoundary = 0) {
69
69
  const tokens = [];
70
70
  for (let start = 0; start < value.length;) {
71
71
  const character = String.fromCodePoint(value.codePointAt(start));
@@ -73,7 +73,8 @@ function tokenize(value, mask, separators, normalize, allowed) {
73
73
  ? 'T' : mask.prefix === 'yen' && /^[--−]$/u.test(character) ? '-' : undefined);
74
74
  const currency = mask.yen && /^[¥¥]$/u.test(character) && (start === 0 ||
75
75
  tokens.length === 1 && tokens[0]?.kind === 'prefix');
76
- const separator = separators.find((candidate) => value.startsWith(candidate, start));
76
+ const separator = separators.find((candidate) => value.startsWith(candidate, start) &&
77
+ (start >= separatorBoundary || start + candidate.length <= separatorBoundary));
77
78
  const source = !prefix && separator ? separator : character;
78
79
  const text = prefix || normalize(source);
79
80
  const kind = prefix ? 'prefix' : separator || currency ? 'separator' : allowed.test(text) ? 'data' : 'invalid';
@@ -86,17 +87,20 @@ function tokenize(value, mask, separators, normalize, allowed) {
86
87
  function matchingEdges(current, previous) {
87
88
  if (!previous)
88
89
  return { leading: 0, trailing: current.value.length };
89
- const old = selection(previous);
90
- const limit = Math.min(old.selectionStart, current.selectionStart);
90
+ const limit = Math.min(previous.selectionStart, current.selectionStart);
91
91
  let leading = 0;
92
- while (leading < limit && old.value[leading] === current.value[leading])
92
+ while (leading < limit && previous.value[leading] === current.value[leading])
93
93
  leading++;
94
- const trailingLimit = Math.min(old.value.length - old.selectionEnd, current.value.length - leading);
94
+ const trailingLimit = Math.min(previous.value.length - previous.selectionEnd, current.value.length - leading);
95
95
  let trailing = 0;
96
- while (trailing < trailingLimit && old.value.at(-trailing - 1) === current.value.at(-trailing - 1))
96
+ while (trailing < trailingLimit && previous.value.at(-trailing - 1) === current.value.at(-trailing - 1))
97
97
  trailing++;
98
98
  return { leading, trailing: current.value.length - trailing };
99
99
  }
100
+ function rejectedCharacters(tokens) {
101
+ return tokens.flatMap((token) => token.rejection
102
+ ? [{ value: token.source, index: token.start, reason: token.rejection }] : []);
103
+ }
100
104
  function remap(offset, pieces, tokens, formatted) {
101
105
  let left = 0;
102
106
  let tokenIndex = 0;
@@ -166,21 +170,25 @@ function compileMask(mask, options) {
166
170
  /^[--−¥¥]/u.test(separator) && mask.yen) {
167
171
  throw new RangeError('separator characters must be distinct from data and field prefixes');
168
172
  }
169
- const parse = (value) => tokenize(value, mask, separators, normalize, allowed);
173
+ const parse = (value, boundary) => tokenize(value, mask, separators, normalize, allowed, boundary);
170
174
  const layoutFor = (data) => mask.layout(mask.allowed ? '' : asciiDigits(data.map((token) => token.text).join('')));
171
175
  function format(state) {
172
176
  const original = selection(state);
173
177
  if (state.isComposing)
174
178
  return { ...original, rawValue: state.value, complete: false, rejected: [], changed: false };
179
+ const previous = state.previous && selection(state.previous);
175
180
  const current = deletedSeparator(original, state.previous, state.inputType, parse, format);
176
- const tokens = parse(current.value);
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);
177
186
  const data = tokens.filter((token) => token.kind === 'data');
178
187
  const initialLayout = layoutFor(data);
179
188
  const maximum = maxDigits ?? initialLayout?.length ?? mask.length ?? Infinity;
180
- const { leading, trailing } = matchingEdges(current, state.previous);
181
189
  const survived = (token) => token.end <= leading || token.start >= trailing;
182
190
  // When clipping a native edit, give existing suffix data the same priority as the prefix.
183
- const priorities = overflow === 'truncate' && state.previous && data.length > maximum
191
+ const priorities = overflow === 'truncate' && previous && data.length > maximum
184
192
  ? [...data.filter(survived), ...data.filter((token) => !survived(token))] : data;
185
193
  for (const token of priorities.slice(maximum)) {
186
194
  token.rejection = 'overflow';
@@ -188,37 +196,71 @@ function compileMask(mask, options) {
188
196
  }
189
197
  let previousFormatted;
190
198
  const wasDecoration = (token) => {
191
- if (!state.previous || !survived(token))
199
+ if (!previous || !survived(token))
192
200
  return false;
193
201
  if (previousFormatted === undefined) {
194
- const { rawValue } = format({ value: state.previous.value });
195
- previousFormatted = format({ value: rawValue }).value === state.previous.value;
202
+ const { rawValue } = format({ value: previous.value });
203
+ previousFormatted = format({ value: rawValue }).value === previous.value;
196
204
  }
197
205
  return previousFormatted;
198
206
  };
199
207
  let dataBefore = 0;
200
- let lastSeparatorAt = -1;
208
+ let dateSeparator;
201
209
  for (const token of tokens) {
202
- if (token.kind === 'data')
210
+ if (token.kind === 'data') {
203
211
  dataBefore++;
204
- if (token.kind === 'separator') {
205
- const currency = mask.yen && /^[¥¥]$/u.test(token.source);
206
- const misplaced = dataBefore === 0 && !currency || mask.date &&
207
- (!initialLayout?.breaks.includes(dataBefore) || lastSeparatorAt === dataBefore);
208
- if (misplaced && !wasDecoration(token))
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 {
209
230
  token.kind = 'invalid';
210
- lastSeparatorAt = dataBefore;
231
+ }
232
+ }
233
+ else if (dataBefore === 0 && !(mask.yen && /^[¥¥]$/u.test(token.source)) && !wasDecoration(token)) {
234
+ token.kind = 'invalid';
211
235
  }
236
+ }
237
+ for (const token of tokens) {
212
238
  if (token.kind === 'invalid') {
213
239
  token.rejection = 'invalid';
214
240
  token.dropped = invalid === 'drop';
215
241
  }
216
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
+ }
217
261
  const kept = tokens.filter((token) => !token.dropped);
218
262
  const accepted = kept.filter((token) => token.kind === 'data' || token.kind === 'prefix');
219
263
  const rawValue = accepted.map((token) => token.text).join('');
220
- const digits = data.filter((token) => !token.dropped);
221
- const layout = digits.length === data.length ? initialLayout : layoutFor(digits);
222
264
  const preserve = kept.some((token) => token.rejection);
223
265
  const formatted = !preserve && layout !== undefined;
224
266
  const breaks = new Set(layout?.breaks);
@@ -240,9 +282,7 @@ function compileMask(mask, options) {
240
282
  const selectionEnd = remap(current.selectionEnd, pieces, tokens, formatted);
241
283
  const complete = formatted && (mask.yen ? digits.length > 0 : digits.length === layout.length) &&
242
284
  (mask.prefix !== 'invoice' || rawValue.startsWith('T'));
243
- const rejected = tokens.flatMap((token) => token.rejection
244
- ? [{ value: token.source, index: token.start, reason: token.rejection }] : []);
245
- return { value, rawValue, complete, rejected, selectionStart, selectionEnd,
285
+ return { value, rawValue, complete, rejected: rejectedCharacters(tokens), selectionStart, selectionEnd,
246
286
  selectionDirection: current.selectionDirection, changed: value !== original.value ||
247
287
  selectionStart !== original.selectionStart || selectionEnd !== original.selectionEnd };
248
288
  }
package/docs/API.md CHANGED
@@ -22,6 +22,8 @@ All take `(value: string, options?: MaskOptions)` and return a string. `maskYen`
22
22
 
23
23
  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.
24
24
 
25
+ 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.
26
+
25
27
  ## Stateful formatting
26
28
 
27
29
  ```ts
@@ -52,7 +54,7 @@ custom({ value: 'AB123' }).value // 'AB · 123'
52
54
  | `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. |
53
55
  | `fullWidthDigits` | `'convert'` (default) folds `0`–`9` to ASCII. `'preserve'` retains full-width data, with phone layout still inferred from digit values. |
54
56
  | `invalid` | `'preserve'` (default) or `'drop'` |
55
- | `overflow` | `'preserve'` (default) or `'truncate'`. A native edit with a usable `previous` snapshot retains existing data before accepting new excess digits. |
57
+ | `overflow` | `'preserve'` (default) or `'truncate'`. A native edit with a usable `previous` snapshot retains existing data before accepting new excess digits. If a replacement shortens the automatic phone limit and truncation would discard the prefix that selected it, the previous value and selection are restored. Discarded digits are reported as `overflow` at their post-edit offsets. |
56
58
  | `allowNegative` | Yen only. Defaults to `true`. |
57
59
  | `groups` | Custom masks only. Non-empty list of positive group sizes. The sum defines the default limit and completion length. |
58
60
  | `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. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ja-input-mask",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "IME-aware input masks for Japanese web forms",
5
5
  "type": "module",
6
6
  "sideEffects": false,