text-input-guard 0.1.0 → 0.1.1

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.
@@ -4,6 +4,249 @@
4
4
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.TextInputGuard = {}));
5
5
  })(this, (function (exports) { 'use strict';
6
6
 
7
+ /**
8
+ * The script is part of TextInputGuard.
9
+ *
10
+ * AUTHOR:
11
+ * natade-jp (https://github.com/natade-jp)
12
+ *
13
+ * LICENSE:
14
+ * The MIT license https://opensource.org/licenses/MIT
15
+ */
16
+
17
+ /**
18
+ * SwapState
19
+ *
20
+ * separateValue.mode="swap" のときに使用する
21
+ * 元 input 要素の状態スナップショットおよび復元ロジックを管理するクラス
22
+ *
23
+ * 役割
24
+ * - swap前の input の属性状態を保持する
25
+ * - raw化および display生成時に必要な属性を適用する
26
+ * - detach時に元の状態へ復元する
27
+ *
28
+ * 設計方針
29
+ * - 送信用属性は raw に残す
30
+ * - UIおよびアクセシビリティ属性は display に適用する
31
+ * - tig内部用の data-* は display にコピーしない
32
+ */
33
+ class SwapState {
34
+ /**
35
+ * 元 input の type 属性
36
+ * detach時に復元するため保持する
37
+ * @type {string}
38
+ */
39
+ originalType;
40
+
41
+ /**
42
+ * 元 input の id 属性
43
+ * swap時に display へ移し detach時に rawへ戻す
44
+ * @type {string|null}
45
+ */
46
+ originalId;
47
+
48
+ /**
49
+ * 元 input の name 属性
50
+ * 送信用属性のため raw側に残すが
51
+ * detach時の整合性のため保持する
52
+ * @type {string|null}
53
+ */
54
+ originalName;
55
+
56
+ /**
57
+ * 元 input の class 属性
58
+ * swap時に display へ移す
59
+ * @type {string}
60
+ */
61
+ originalClass;
62
+
63
+ /**
64
+ * UI系属性のスナップショット
65
+ * placeholder inputmode required などを保持する
66
+ *
67
+ * key 属性名
68
+ * value 属性値 未指定の場合は null
69
+ *
70
+ * @type {Object.<string, string|null>}
71
+ */
72
+ originalUiAttrs;
73
+
74
+ /**
75
+ * aria-* 属性のスナップショット
76
+ * アクセシビリティ維持のため display に適用する
77
+ *
78
+ * key aria属性名 例 aria-label
79
+ * value 属性値
80
+ *
81
+ * @type {Object.<string, string>}
82
+ */
83
+ originalAriaAttrs;
84
+
85
+ /**
86
+ * tig 以外の data-* 属性のスナップショット
87
+ * swap後も display へ引き継ぐ
88
+ *
89
+ * key datasetキー camelCase
90
+ * value 属性値
91
+ *
92
+ * @type {Object.<string, string>}
93
+ */
94
+ originalDataset;
95
+
96
+ /**
97
+ * swap時に生成された display 用 input 要素
98
+ * detach時に削除するため保持する
99
+ *
100
+ * @type {HTMLInputElement|null}
101
+ */
102
+ createdDisplay;
103
+
104
+ /**
105
+ * @param {HTMLInputElement} input
106
+ * swap前の元 input 要素
107
+ */
108
+ constructor(input) {
109
+ this.originalType = input.type;
110
+ this.originalId = input.getAttribute("id");
111
+ this.originalName = input.getAttribute("name");
112
+ this.originalClass = input.className;
113
+
114
+ this.originalUiAttrs = {};
115
+ this.originalAriaAttrs = {};
116
+ this.originalDataset = {};
117
+ this.createdDisplay = null;
118
+
119
+ const UI_ATTRS = [
120
+ "placeholder",
121
+ "inputmode",
122
+ "autocomplete",
123
+ "required",
124
+ "minlength",
125
+ "maxlength",
126
+ "pattern",
127
+ "title",
128
+ "tabindex"
129
+ ];
130
+
131
+ for (const name of UI_ATTRS) {
132
+ this.originalUiAttrs[name] =
133
+ input.hasAttribute(name) ? input.getAttribute(name) : null;
134
+ }
135
+
136
+ for (const attr of input.attributes) {
137
+ if (attr.name.startsWith("aria-")) {
138
+ this.originalAriaAttrs[attr.name] = attr.value ?? "";
139
+ }
140
+ }
141
+
142
+ for (const [k, v] of Object.entries(input.dataset)) {
143
+ if (k.startsWith("tig")) { continue; }
144
+ this.originalDataset[k] = v;
145
+ }
146
+ }
147
+
148
+ /**
149
+ * raw 元input を hidden 化する
150
+ * 送信担当要素として扱う
151
+ *
152
+ * @param {HTMLInputElement} input
153
+ * @returns {void}
154
+ */
155
+ applyToRaw(input) {
156
+ // raw化(送信担当)
157
+ input.type = "hidden";
158
+ input.removeAttribute("id");
159
+ input.className = "";
160
+ input.dataset.tigRole = "raw";
161
+
162
+ // 元idのメタを残す(デバッグ/参照用)
163
+ if (this.originalId) {
164
+ input.dataset.tigOriginalId = this.originalId;
165
+ }
166
+ if (this.originalName) {
167
+ input.dataset.tigOriginalName = this.originalName;
168
+ }
169
+ }
170
+
171
+ /**
172
+ * display用 input を生成し UI属性 aria属性 data属性を適用
173
+ *
174
+ * @param {HTMLInputElement} raw hidden化された元input
175
+ * @returns {HTMLInputElement}
176
+ */
177
+ createDisplay(raw) {
178
+ const display = document.createElement("input");
179
+ display.type = "text";
180
+ display.dataset.tigRole = "display";
181
+
182
+ if (this.originalId) {
183
+ display.id = this.originalId;
184
+ }
185
+
186
+ display.className = this.originalClass ?? "";
187
+ display.value = raw.value;
188
+
189
+ for (const [name, v] of Object.entries(this.originalUiAttrs)) {
190
+ if (v == null) {
191
+ display.removeAttribute(name);
192
+ } else {
193
+ display.setAttribute(name, v);
194
+ }
195
+ }
196
+
197
+ for (const [name, v] of Object.entries(this.originalAriaAttrs)) {
198
+ display.setAttribute(name, v);
199
+ }
200
+
201
+ for (const [k, v] of Object.entries(this.originalDataset)) {
202
+ display.dataset[k] = v;
203
+ }
204
+
205
+ this.createdDisplay = display;
206
+ return display;
207
+ }
208
+
209
+ /**
210
+ * detach時に display 要素を削除する
211
+ *
212
+ * @returns {void}
213
+ */
214
+ removeDisplay() {
215
+ if (this.createdDisplay?.parentNode) {
216
+ this.createdDisplay.parentNode.removeChild(this.createdDisplay);
217
+ }
218
+ this.createdDisplay = null;
219
+ }
220
+
221
+ /**
222
+ * raw hidden化された元input を元の状態へ復元する
223
+ *
224
+ * @param {HTMLInputElement} raw
225
+ * @returns {void}
226
+ */
227
+ restoreRaw(raw) {
228
+ raw.type = this.originalType;
229
+
230
+ if (this.originalId) {
231
+ raw.setAttribute("id", this.originalId);
232
+ } else {
233
+ raw.removeAttribute("id");
234
+ }
235
+
236
+ if (this.originalName) {
237
+ raw.setAttribute("name", this.originalName);
238
+ } else {
239
+ raw.removeAttribute("name");
240
+ }
241
+
242
+ raw.className = this.originalClass ?? "";
243
+
244
+ delete raw.dataset.tigRole;
245
+ delete raw.dataset.tigOriginalId;
246
+ delete raw.dataset.tigOriginalName;
247
+ }
248
+ }
249
+
7
250
  /**
8
251
  * The script is part of JPInputGuard.
9
252
  *
@@ -14,6 +257,7 @@
14
257
  * The MIT license https://opensource.org/licenses/MIT
15
258
  */
16
259
 
260
+
17
261
  /**
18
262
  * 対象要素の種別(現在は input と textarea のみ対応)
19
263
  * @typedef {"input"|"textarea"} ElementKind
@@ -41,7 +285,9 @@
41
285
  * @property {() => boolean} isValid - 現在エラーが無いかどうか
42
286
  * @property {() => TigError[]} getErrors - エラー一覧を取得
43
287
  * @property {() => string} getRawValue - 送信用の正規化済み値を取得
44
- * @property {() => HTMLInputElement|HTMLTextAreaElement} getDisplayElement - ユーザーが実際に操作している要素(swap時はdisplay側)
288
+ * @property {() => string} getDisplayValue - ユーザーが実際に操作している要素の値を取得
289
+ * @property {() => HTMLInputElement|HTMLTextAreaElement} getRawElement - 送信用の正規化済み値の要素
290
+ * @property {() => HTMLInputElement|HTMLTextAreaElement} getDisplayElement - ユーザーが実際に操作している要素(swap時はdisplay専用)
45
291
  */
46
292
 
47
293
  /**
@@ -90,17 +336,6 @@
90
336
  * @property {SeparateValueOptions} [separateValue] - 表示値と内部値の分離設定
91
337
  */
92
338
 
93
- /**
94
- * swap時に退避する元inputの情報
95
- * detach時に元の状態へ復元するために使用する
96
- * @typedef {Object} SwapState
97
- * @property {string} originalType - 元のinput.type
98
- * @property {string|null} originalId - 元のid属性
99
- * @property {string|null} originalName - 元のname属性
100
- * @property {string} originalClass - 元のclass文字列
101
- * @property {HTMLInputElement} createdDisplay - 生成した表示用input
102
- */
103
-
104
339
  /**
105
340
  * selection(カーソル/選択範囲)の退避情報
106
341
  * @typedef {Object} SelectionState
@@ -444,61 +679,19 @@
444
679
 
445
680
  const input = /** @type {HTMLInputElement} */ (this.originalElement);
446
681
 
447
- // 退避(detachで戻すため)
448
- /** @type {SwapState} */
449
- this.swapState = {
450
- originalType: input.type,
451
- originalId: input.getAttribute("id"),
452
- originalName: input.getAttribute("name"),
453
- originalClass: input.className,
454
- // 必要になったらここに placeholder/aria/data を追加していく
455
- createdDisplay: null
456
- };
457
-
458
- // raw化(送信担当)
459
- input.type = "hidden";
460
- input.removeAttribute("id"); // displayに引き継ぐため
461
- input.dataset.tigRole = "raw";
462
-
463
- // 元idのメタを残す(デバッグ/参照用)
464
- if (this.swapState.originalId) {
465
- input.dataset.tigOriginalId = this.swapState.originalId;
466
- }
682
+ const state = new SwapState(input);
683
+ state.applyToRaw(input);
467
684
 
468
- if (this.swapState.originalName) {
469
- input.dataset.tigOriginalName = this.swapState.originalName;
470
- }
471
-
472
- // display生成(ユーザー入力担当)
473
- const display = document.createElement("input");
474
- display.type = "text";
475
- display.dataset.tigRole = "display";
476
-
477
- // id は display に移す
478
- if (this.swapState.originalId) {
479
- display.id = this.swapState.originalId;
480
- }
481
-
482
- // name は付けない(送信しない)
483
- display.removeAttribute("name");
484
-
485
- // class は display に
486
- display.className = this.swapState.originalClass;
487
- input.className = "";
488
-
489
- // value 初期同期
490
- display.value = input.value;
491
-
492
- // DOMに挿入(rawの直後)
685
+ const display = state.createDisplay(input);
493
686
  input.after(display);
494
687
 
688
+ this.swapState = state;
689
+
495
690
  // elements更新
496
- this.hostElement = input;
497
- this.displayElement = display;
691
+ this.hostElement = input; // raw
692
+ this.displayElement = display; // display
498
693
  this.rawElement = input;
499
694
 
500
- this.swapState.createdDisplay = display;
501
-
502
695
  // revert 機構
503
696
  this.lastAcceptedValue = display.value;
504
697
  this.lastAcceptedSelection = this.readSelection(display);
@@ -518,10 +711,10 @@
518
711
 
519
712
  // rawは元の input(hidden化されている)
520
713
  const raw = /** @type {HTMLInputElement} */ (this.hostElement);
521
- const display = state.createdDisplay;
522
714
 
523
715
  // displayが存在するなら、最新表示値をrawに同期してから消す(安全策)
524
716
  // ※ rawは常に正規化済みを持つ設計だけど、念のため
717
+ const display = state.createdDisplay;
525
718
  if (display) {
526
719
  try {
527
720
  raw.value = raw.value || display.value;
@@ -531,39 +724,18 @@
531
724
  }
532
725
 
533
726
  // display削除
534
- if (display && display.parentNode) {
535
- display.parentNode.removeChild(display);
536
- }
727
+ state.removeDisplay();
537
728
 
538
729
  // rawを元に戻す(type)
539
- raw.type = state.originalType;
540
-
541
- // id を戻す
542
- if (state.originalId) {
543
- raw.setAttribute("id", state.originalId);
544
- } else {
545
- raw.removeAttribute("id");
546
- }
547
-
548
- // name を戻す(swap中は残している想定だが、念のため)
549
- if (state.originalName) {
550
- raw.setAttribute("name", state.originalName);
551
- } else {
552
- raw.removeAttribute("name");
553
- }
554
-
555
- // class を戻す
556
- raw.className = state.originalClass ?? "";
557
-
558
- // data属性(tig用)は消しておく
559
- delete raw.dataset.tigRole;
560
- delete raw.dataset.tigOriginalId;
561
- delete raw.dataset.tigOriginalName;
730
+ state.restoreRaw(raw);
562
731
 
563
732
  // elements参照を original に戻す
564
733
  this.hostElement = this.originalElement;
565
734
  this.displayElement = this.originalElement;
566
735
  this.rawElement = null;
736
+
737
+ // swapState破棄
738
+ this.swapState = null;
567
739
  }
568
740
 
569
741
  /**
@@ -575,8 +747,6 @@
575
747
  this.unbindEvents();
576
748
  // swap復元
577
749
  this.restoreSeparateValue();
578
- // swapState破棄
579
- this.swapState = null;
580
750
  // 以後このインスタンスは利用不能にしてもいいが、今回は明示しない
581
751
  }
582
752
 
@@ -1086,9 +1256,14 @@
1086
1256
  * @returns {string}
1087
1257
  */
1088
1258
  getRawValue() {
1089
- if (this.rawElement) {
1090
- return this.rawElement.value;
1091
- }
1259
+ return /** @type {HTMLInputElement|HTMLTextAreaElement} */ (this.hostElement).value;
1260
+ }
1261
+
1262
+ /**
1263
+ * 表示用の値を返す(displayの値)
1264
+ * @returns {string}
1265
+ */
1266
+ getDisplayValue() {
1092
1267
  return /** @type {HTMLInputElement|HTMLTextAreaElement} */ (this.displayElement).value;
1093
1268
  }
1094
1269
 
@@ -1103,6 +1278,8 @@
1103
1278
  isValid: () => this.isValid(),
1104
1279
  getErrors: () => this.getErrors(),
1105
1280
  getRawValue: () => this.getRawValue(),
1281
+ getDisplayValue: () => this.getDisplayValue(),
1282
+ getRawElement: () => /** @type {HTMLInputElement|HTMLTextAreaElement} */ (this.hostElement),
1106
1283
  getDisplayElement: () => /** @type {HTMLInputElement|HTMLTextAreaElement} */ (this.displayElement)
1107
1284
  };
1108
1285
  }
@@ -2168,11 +2345,11 @@
2168
2345
 
2169
2346
  /**
2170
2347
  * バージョン(ビルド時に置換したいならここを差し替える)
2171
- * 例: rollup replace で ""0.0.1"" を package.json の version に置換
2348
+ * 例: rollup replace で ""0.1.0"" を package.json の version に置換
2172
2349
  */
2173
2350
  // @ts-ignore
2174
2351
  // eslint-disable-next-line no-undef
2175
- const version = "0.0.1" ;
2352
+ const version = "0.1.0" ;
2176
2353
 
2177
2354
  exports.attach = attach;
2178
2355
  exports.attachAll = attachAll;
@@ -3,4 +3,4 @@
3
3
  * AUTHOR: natade (https://github.com/natade-jp/)
4
4
  * LICENSE: MIT https://opensource.org/licenses/MIT
5
5
  */
6
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).TextInputGuard={})}(this,function(t){"use strict";function e(t,e){e&&console.warn(t)}function i(t,e={}){const i=new n(t,e);return i.init(),i.toGuard()}class n{constructor(t,e){this.originalElement=t,this.options=e;const i=(n=t)instanceof HTMLInputElement?"input":n instanceof HTMLTextAreaElement?"textarea":null;var n;if(!i)throw new TypeError("[text-input-guard] attach() expects an <input> or <textarea> element.");this.kind=i,this.warn=e.warn??!0,this.invalidClass=e.invalidClass??"is-invalid",this.rules=Array.isArray(e.rules)?e.rules:[],this.hostElement=t,this.displayElement=t,this.rawElement=null,this.composing=!1,this.errors=[],this.normalizeCharRules=[],this.normalizeStructureRules=[],this.validateRules=[],this.fixRules=[],this.formatRules=[],this.onCompositionStart=this.onCompositionStart.bind(this),this.onCompositionEnd=this.onCompositionEnd.bind(this),this.onInput=this.onInput.bind(this),this.onBlur=this.onBlur.bind(this),this.onFocus=this.onFocus.bind(this),this.onSelectionChange=this.onSelectionChange.bind(this),this.swapState=null,this.pendingCompositionCommit=!1,this.lastAcceptedValue="",this.lastAcceptedSelection={start:null,end:null,direction:null},this.revertRequest=null}init(){this.buildPipeline(),this.applySeparateValue(),this.bindEvents(),this.evaluateInput()}readSelection(t){return{start:t.selectionStart,end:t.selectionEnd,direction:t.selectionDirection}}writeSelection(t,e){if(null!=e.start&&null!=e.end)try{e.direction?t.setSelectionRange(e.start,e.end,e.direction):t.setSelectionRange(e.start,e.end)}catch(t){}}applySeparateValue(){const t=this.options.separateValue?.mode??"auto";if("swap"!==("auto"===t?this.formatRules.length>0?"swap":"off":t))return;if("input"!==this.kind)return void e('[text-input-guard] separateValue.mode="swap" is not supported for <textarea>. ignored.',this.warn);const i=this.originalElement;this.swapState={originalType:i.type,originalId:i.getAttribute("id"),originalName:i.getAttribute("name"),originalClass:i.className,createdDisplay:null},i.type="hidden",i.removeAttribute("id"),i.dataset.tigRole="raw",this.swapState.originalId&&(i.dataset.tigOriginalId=this.swapState.originalId),this.swapState.originalName&&(i.dataset.tigOriginalName=this.swapState.originalName);const n=document.createElement("input");n.type="text",n.dataset.tigRole="display",this.swapState.originalId&&(n.id=this.swapState.originalId),n.removeAttribute("name"),n.className=this.swapState.originalClass,i.className="",n.value=i.value,i.after(n),this.hostElement=i,this.displayElement=n,this.rawElement=i,this.swapState.createdDisplay=n,this.lastAcceptedValue=n.value,this.lastAcceptedSelection=this.readSelection(n)}restoreSeparateValue(){if(!this.swapState)return;const t=this.swapState,e=this.hostElement,i=t.createdDisplay;if(i)try{e.value=e.value||i.value}catch(t){}i&&i.parentNode&&i.parentNode.removeChild(i),e.type=t.originalType,t.originalId?e.setAttribute("id",t.originalId):e.removeAttribute("id"),t.originalName?e.setAttribute("name",t.originalName):e.removeAttribute("name"),e.className=t.originalClass??"",delete e.dataset.tigRole,delete e.dataset.tigOriginalId,delete e.dataset.tigOriginalName,this.hostElement=this.originalElement,this.displayElement=this.originalElement,this.rawElement=null}detach(){this.unbindEvents(),this.restoreSeparateValue(),this.swapState=null}buildPipeline(){this.normalizeCharRules=[],this.normalizeStructureRules=[],this.validateRules=[],this.fixRules=[],this.formatRules=[];for(const t of this.rules){"input"===this.kind&&t.targets.includes("input")||"textarea"===this.kind&&t.targets.includes("textarea")?(t.normalizeChar&&this.normalizeCharRules.push(t),t.normalizeStructure&&this.normalizeStructureRules.push(t),t.validate&&this.validateRules.push(t),t.fix&&this.fixRules.push(t),t.format&&this.formatRules.push(t)):e(`[text-input-guard] Rule "${t.name}" is not supported for <${this.kind}>. skipped.`,this.warn)}}bindEvents(){this.displayElement.addEventListener("compositionstart",this.onCompositionStart),this.displayElement.addEventListener("compositionend",this.onCompositionEnd),this.displayElement.addEventListener("input",this.onInput),this.displayElement.addEventListener("blur",this.onBlur),this.displayElement.addEventListener("focus",this.onFocus),this.displayElement.addEventListener("keyup",this.onSelectionChange),this.displayElement.addEventListener("mouseup",this.onSelectionChange),this.displayElement.addEventListener("select",this.onSelectionChange),this.displayElement.addEventListener("focus",this.onSelectionChange)}unbindEvents(){this.displayElement.removeEventListener("compositionstart",this.onCompositionStart),this.displayElement.removeEventListener("compositionend",this.onCompositionEnd),this.displayElement.removeEventListener("input",this.onInput),this.displayElement.removeEventListener("blur",this.onBlur),this.displayElement.removeEventListener("focus",this.onFocus),this.displayElement.removeEventListener("keyup",this.onSelectionChange),this.displayElement.removeEventListener("mouseup",this.onSelectionChange),this.displayElement.removeEventListener("select",this.onSelectionChange),this.displayElement.removeEventListener("focus",this.onSelectionChange)}revertDisplay(t){const e=this.displayElement;e.value=this.lastAcceptedValue,this.writeSelection(e,this.lastAcceptedSelection),this.syncRaw(this.lastAcceptedValue),this.clearErrors(),this.applyInvalidClass(),this.revertRequest=null,this.warn}createCtx(){return{hostElement:this.hostElement,displayElement:this.displayElement,rawElement:this.rawElement,kind:this.kind,warn:this.warn,invalidClass:this.invalidClass,composing:this.composing,pushError:t=>this.errors.push(t),requestRevert:t=>{this.revertRequest||(this.revertRequest=t)}}}clearErrors(){this.errors=[]}runNormalizeChar(t,e){let i=t;for(const t of this.normalizeCharRules)i=t.normalizeChar?t.normalizeChar(i,e):i;return i}runNormalizeStructure(t,e){let i=t;for(const t of this.normalizeStructureRules)i=t.normalizeStructure?t.normalizeStructure(i,e):i;return i}runValidate(t,e){for(const i of this.validateRules)i.validate&&i.validate(t,e)}runFix(t,e){let i=t;for(const t of this.fixRules)i=t.fix?t.fix(i,e):i;return i}runFormat(t,e){let i=t;for(const t of this.formatRules)i=t.format?t.format(i,e):i;return i}applyInvalidClass(){const t=this.displayElement;this.errors.length>0?t.classList.add(this.invalidClass):t.classList.remove(this.invalidClass)}syncRaw(t){this.rawElement&&(this.rawElement.value=t)}syncDisplay(t){(this.displayElement instanceof HTMLInputElement||this.displayElement instanceof HTMLTextAreaElement)&&(this.displayElement.value=t)}onCompositionStart(){this.composing=!0}onCompositionEnd(){this.composing=!1,this.pendingCompositionCommit=!0,queueMicrotask(()=>{this.pendingCompositionCommit&&(this.pendingCompositionCommit=!1,this.evaluateInput())})}onInput(){this.pendingCompositionCommit=!1,this.evaluateInput()}onBlur(){this.evaluateCommit()}onFocus(){if(this.composing)return;const t=this.displayElement,e=t.value,i=this.createCtx();let n=e;n=this.runNormalizeChar(n,i),n=this.runNormalizeStructure(n,i),n!==e&&(this.setDisplayValuePreserveCaret(t,n,i),this.syncRaw(n)),this.lastAcceptedValue=n,this.lastAcceptedSelection=this.readSelection(t),this.onSelectionChange()}onSelectionChange(){if(this.composing)return;const t=this.displayElement;this.lastAcceptedSelection=this.readSelection(t)}setDisplayValuePreserveCaret(t,e,i){const n=t.value;if(n===e)return;const s=t.selectionStart,r=t.selectionEnd;if(null==s||null==r)return void(t.value=e);let a=n.slice(0,s);a=this.runNormalizeChar(a,i),a=this.runNormalizeStructure(a,i),t.value=e;const l=Math.min(a.length,e.length);try{t.setSelectionRange(l,l)}catch(t){}}evaluateInput(){if(this.composing)return;this.clearErrors(),this.revertRequest=null;const t=this.displayElement,e=t.value,i=this.createCtx();let n=e;n=this.runNormalizeChar(n,i),n=this.runNormalizeStructure(n,i),n!==e&&this.setDisplayValuePreserveCaret(t,n,i),this.runValidate(n,i),this.revertRequest?this.revertDisplay(this.revertRequest):(this.syncRaw(n),this.applyInvalidClass(),this.lastAcceptedValue=n,this.lastAcceptedSelection=this.readSelection(t))}evaluateCommit(){if(this.composing)return;this.clearErrors(),this.revertRequest=null;const t=this.displayElement,e=this.createCtx();let i=t.value;if(i=this.runNormalizeChar(i,e),i=this.runNormalizeStructure(i,e),this.runValidate(i,e),this.revertRequest)return void this.revertDisplay(this.revertRequest);if(i=this.runFix(i,e),this.clearErrors(),this.revertRequest=null,this.runValidate(i,e),this.revertRequest)return void this.revertDisplay(this.revertRequest);this.syncRaw(i);let n=i;n=this.runFormat(n,e),this.syncDisplay(n),this.applyInvalidClass(),this.lastAcceptedValue=i,this.lastAcceptedSelection=this.readSelection(t)}isValid(){return 0===this.errors.length}getErrors(){return this.errors.slice()}getRawValue(){return this.rawElement?this.rawElement.value:this.displayElement.value}toGuard(){return{detach:()=>this.detach(),isValid:()=>this.isValid(),getErrors:()=>this.getErrors(),getRawValue:()=>this.getRawValue(),getDisplayElement:()=>this.displayElement}}}function s(t){if(null==t)return;const e=String(t).trim().toLowerCase();return""===e||"true"===e||"1"===e||"yes"===e||"on"===e||"false"!==e&&"0"!==e&&"no"!==e&&"off"!==e&&void 0}function r(t){if(null==t)return;const e=String(t).trim();if(""===e)return;const i=Number(e);return Number.isFinite(i)?i:void 0}function a(t,e){if(null==t)return;const i=String(t).trim();return""!==i&&e.includes(i)?i:void 0}function l(t){if(null==t||""===String(t).trim())return"auto";const e=String(t).trim().toLowerCase();return"auto"===e||"swap"===e||"off"===e?e:"auto"}function o(t){if(null!=t.tigSeparate)return!0;if(null!=t.tigWarn)return!0;if(null!=t.tigInvalidClass)return!0;for(const e in t)if(e.startsWith("tigRules"))return!0;return!1}function u(t={}){const e=t.allowFullWidth??!0,i=t.allowMinus??!1,n=t.allowDecimal??!1,s=t.allowEmpty??!0,r=new Set(["ー","-","−","‐","-","‒","–","—","―"]),a=new Set([".","。","。"]);function l(t){if(t>="0"&&t<="9")return t;if(e){const e=function(t){const e=t.charCodeAt(0);return 65296<=e&&e<=65305?String.fromCharCode(e-65296+48):null}(t);if(e)return e}return"."===t||e&&a.has(t)?n?".":"":"-"===t?i?"-":"":e&&r.has(t)&&i?"-":""}return{name:"numeric",targets:["input"],normalizeChar(t){let e=String(t);e=e.replace(/,/g,"");let i="";for(const t of e)i+=l(t);return i},normalizeStructure(t){let e="",s=!1,r=!1;for(const a of String(t))a>="0"&&a<="9"?e+=a:"-"===a&&i?s||0!==e.length||(e+="-",s=!0):"."===a&&n&&(r||(e+=".",r=!0));return e},fix(t){let e=String(t);if(""===e)return s?"":"0";if("-"===e||"."===e||"-."===e)return s?"":"0";e.startsWith("-.")&&(e="-0"+e.slice(1)),e.startsWith(".")&&(e="0"+e),e.endsWith(".")&&(e=e.slice(0,-1));let i="";e.startsWith("-")&&(i="-",e=e.slice(1));const n=e.indexOf(".");let r=n>=0?e.slice(0,n):e;const a=n>=0?e.slice(n+1):"";return r=r.replace(/^0+/,""),""===r&&(r="0"),"-"!==i||"0"!==r||a&&!/^0*$/.test(a)||(i=""),n>=0?`${i}${r}.${a}`:`${i}${r}`},validate(t,e){}}}function c(t){let e="",i=String(t);i.startsWith("-")&&(e="-",i=i.slice(1));const n=i.indexOf(".");if(!(n>=0))return{sign:e,intPart:i,fracPart:"",hasDot:!1};return{sign:e,intPart:i.slice(0,n),fracPart:i.slice(n+1),hasDot:!0}}function h(t){let e=1;const i=t.split("");for(let t=i.length-1;t>=0;t--){const n=i[t].charCodeAt(0)-48+e;if(!(n>=10)){i[t]=String.fromCharCode(48+n),e=0;break}i[t]="0",e=1}return 1===e&&i.unshift("1"),i.join("")}function d(t={}){const e={int:"number"==typeof t.int?t.int:void 0,frac:"number"==typeof t.frac?t.frac:void 0,countLeadingZeros:t.countLeadingZeros??!0,fixIntOnBlur:t.fixIntOnBlur??"none",fixFracOnBlur:t.fixFracOnBlur??"none",overflowInputInt:t.overflowInputInt??"none",overflowInputFrac:t.overflowInputFrac??"none",forceFracOnBlur:t.forceFracOnBlur??!1};return{name:"digits",targets:["input"],validate(t,i){const n=String(t);if(""===n||"-"===n||"."===n||"-."===n)return;const{intPart:s,fracPart:r}=c(n);if("number"==typeof e.int){const t=function(t,e){const i=t??"";if(0===i.length)return 0;if(e)return i.length;const n=i.replace(/^0+/,"");return 0===n.length?1:n.length}(s,e.countLeadingZeros);if(t>e.int){if("block"===e.overflowInputInt)return void i.requestRevert({reason:"digits.int_overflow",detail:{limit:e.int,actual:t}});i.pushError({code:"digits.int_overflow",rule:"digits",phase:"validate",detail:{limit:e.int,actual:t}})}}if("number"==typeof e.frac){const t=(r??"").length;if(t>e.frac){if("block"===e.overflowInputFrac)return void i.requestRevert({reason:"digits.frac_overflow",detail:{limit:e.frac,actual:t}});i.pushError({code:"digits.frac_overflow",rule:"digits",phase:"validate",detail:{limit:e.frac,actual:t}})}}},fix(t,i){const n=String(t);if(""===n||"-"===n||"."===n||"-."===n)return n;const s=c(n);let{intPart:r,fracPart:a}=s;const{sign:l,hasDot:o}=s;if("number"==typeof e.int&&"none"!==e.fixIntOnBlur){(r??"").length>e.int&&("truncateLeft"===e.fixIntOnBlur?r=r.slice(r.length-e.int):"truncateRight"===e.fixIntOnBlur?r=r.slice(0,e.int):"clamp"===e.fixIntOnBlur&&(r="9".repeat(e.int)))}if("number"==typeof e.frac&&"none"!==e.fixFracOnBlur&&o){const t=e.frac,i=a??"";if(i.length>t)if("truncate"===e.fixFracOnBlur)a=i.slice(0,t);else if("round"===e.fixFracOnBlur){const e=function(t,e,i){const n=e??"";if(n.length<=i)return{intPart:t,fracPart:n};const s=n.slice(0,i);if(n.charCodeAt(i)-48<5)return{intPart:t,fracPart:s};if(0===i)return{intPart:h(t.length?t:"0"),fracPart:""};let r=1;const a=s.split("");for(let t=a.length-1;t>=0;t--){const e=a[t].charCodeAt(0)-48+r;if(!(e>=10)){a[t]=String.fromCharCode(48+e),r=0;break}a[t]="0",r=1}const l=a.join("");let o=t;return 1===r&&(o=h(t.length?t:"0")),{intPart:o,fracPart:l}}(r,i,t);r=e.intPart,a=e.fracPart}}if(e.forceFracOnBlur&&"number"==typeof e.frac&&e.frac>0){const t=e.frac;o||(a="");const i=a??"";i.length<t&&(a=i+"0".repeat(t-i.length))}if("number"!=typeof e.frac)return`${l}${r}`;if(0===e.frac)return`${l}${r}`;if(o||e.forceFracOnBlur&&e.frac>0){return`${l}${r}.${a??""}`}return`${l}${r}`}}}function f(){return{name:"comma",targets:["input"],format(t){const e=String(t);if(""===e||"-"===e||"."===e||"-."===e)return e;let i="",n=e;n.startsWith("-")&&(i="-",n=n.slice(1));const s=n.indexOf("."),r=s>=0?n.slice(0,s):n,a=s>=0?n.slice(s+1):null,l=r.replace(/\B(?=(\d{3})+(?!\d))/g,",");return null!=a?`${i}${l}.${a}`:`${i}${l}`}}}u.fromDataset=function(t,e){if(null==t.tigRulesNumeric)return null;const i={},n=s(t.tigRulesNumericAllowFullWidth);null!=n&&(i.allowFullWidth=n);const r=s(t.tigRulesNumericAllowMinus);null!=r&&(i.allowMinus=r);const a=s(t.tigRulesNumericAllowDecimal);null!=a&&(i.allowDecimal=a);const l=s(t.tigRulesNumericAllowEmpty);return null!=l&&(i.allowEmpty=l),u(i)},d.fromDataset=function(t,e){if(null==t.tigRulesDigits)return null;const i={},n=r(t.tigRulesDigitsInt);null!=n&&(i.int=n);const l=r(t.tigRulesDigitsFrac);null!=l&&(i.frac=l);const o=s(t.tigRulesDigitsCountLeadingZeros);null!=o&&(i.countLeadingZeros=o);const u=a(t.tigRulesDigitsFixIntOnBlur,["none","truncateLeft","truncateRight","clamp"]);null!=u&&(i.fixIntOnBlur=u);const c=a(t.tigRulesDigitsFixFracOnBlur,["none","truncate","round"]);null!=c&&(i.fixFracOnBlur=c);const h=a(t.tigRulesDigitsOverflowInputInt,["none","block"]);null!=h&&(i.overflowInputInt=h);const f=a(t.tigRulesDigitsOverflowInputFrac,["none","block"]);null!=f&&(i.overflowInputFrac=f);const m=s(t.tigRulesDigitsForceFracOnBlur);return null!=m&&(i.forceFracOnBlur=m),d(i)},f.fromDataset=function(t,e){return null==t.tigRulesComma?null:f()};const m=new class{constructor(t,e){this.attachFn=t,this.ruleFactories=Array.isArray(e)?e:[]}register(t){this.ruleFactories.push(t)}autoAttach(t=document){const e=[],i=[];if(t.querySelectorAll){const e=t.querySelectorAll("input, textarea");for(const t of e)(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&i.push(t)}(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&(i.includes(t)||i.push(t));for(const t of i){const i=t.dataset;if("true"===i.tigAttached)continue;if(!o(i))continue;const n={},r=s(i.tigWarn);null!=r&&(n.warn=r),null!=i.tigInvalidClass&&""!==String(i.tigInvalidClass).trim()&&(n.invalidClass=String(i.tigInvalidClass)),n.separateValue={mode:l(i.tigSeparate)};const a=[];for(const e of this.ruleFactories)try{const n=e.fromDataset(i,t);n&&a.push(n)}catch(t){(n.warn??!0)&&console.warn(`[text-input-guard] autoAttach: rule "${e.name}" fromDataset() threw an error.`,t)}if(a.length>0&&(n.rules=a),!n.rules||0===n.rules.length)continue;const u=this.attachFn(t,n);e.push(u),t.dataset.tigAttached="true"}return{detach:()=>{for(const t of e)t.detach()},isValid:()=>e.every(t=>t.isValid()),getErrors:()=>e.flatMap(t=>t.getErrors()),getGuards:()=>e}}}(i,[{name:"numeric",fromDataset:u.fromDataset},{name:"digits",fromDataset:d.fromDataset},{name:"comma",fromDataset:f.fromDataset}]),p={numeric:u,digits:d,comma:f};t.attach=i,t.attachAll=function(t,e={}){const n=[];for(const s of t)n.push(i(s,e));return{detach:()=>{for(const t of n)t.detach()},isValid:()=>n.every(t=>t.isValid()),getErrors:()=>n.flatMap(t=>t.getErrors()),getGuards:()=>n}},t.autoAttach=t=>m.autoAttach(t),t.comma=f,t.digits=d,t.numeric=u,t.rules=p,t.version="0.0.1"});
6
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).TextInputGuard={})}(this,function(t){"use strict";class e{originalType;originalId;originalName;originalClass;originalUiAttrs;originalAriaAttrs;originalDataset;createdDisplay;constructor(t){this.originalType=t.type,this.originalId=t.getAttribute("id"),this.originalName=t.getAttribute("name"),this.originalClass=t.className,this.originalUiAttrs={},this.originalAriaAttrs={},this.originalDataset={},this.createdDisplay=null;const e=["placeholder","inputmode","autocomplete","required","minlength","maxlength","pattern","title","tabindex"];for(const i of e)this.originalUiAttrs[i]=t.hasAttribute(i)?t.getAttribute(i):null;for(const e of t.attributes)e.name.startsWith("aria-")&&(this.originalAriaAttrs[e.name]=e.value??"");for(const[e,i]of Object.entries(t.dataset))e.startsWith("tig")||(this.originalDataset[e]=i)}applyToRaw(t){t.type="hidden",t.removeAttribute("id"),t.className="",t.dataset.tigRole="raw",this.originalId&&(t.dataset.tigOriginalId=this.originalId),this.originalName&&(t.dataset.tigOriginalName=this.originalName)}createDisplay(t){const e=document.createElement("input");e.type="text",e.dataset.tigRole="display",this.originalId&&(e.id=this.originalId),e.className=this.originalClass??"",e.value=t.value;for(const[t,i]of Object.entries(this.originalUiAttrs))null==i?e.removeAttribute(t):e.setAttribute(t,i);for(const[t,i]of Object.entries(this.originalAriaAttrs))e.setAttribute(t,i);for(const[t,i]of Object.entries(this.originalDataset))e.dataset[t]=i;return this.createdDisplay=e,e}removeDisplay(){this.createdDisplay?.parentNode&&this.createdDisplay.parentNode.removeChild(this.createdDisplay),this.createdDisplay=null}restoreRaw(t){t.type=this.originalType,this.originalId?t.setAttribute("id",this.originalId):t.removeAttribute("id"),this.originalName?t.setAttribute("name",this.originalName):t.removeAttribute("name"),t.className=this.originalClass??"",delete t.dataset.tigRole,delete t.dataset.tigOriginalId,delete t.dataset.tigOriginalName}}function i(t,e){e&&console.warn(t)}function n(t,e={}){const i=new s(t,e);return i.init(),i.toGuard()}class s{constructor(t,e){this.originalElement=t,this.options=e;const i=(n=t)instanceof HTMLInputElement?"input":n instanceof HTMLTextAreaElement?"textarea":null;var n;if(!i)throw new TypeError("[text-input-guard] attach() expects an <input> or <textarea> element.");this.kind=i,this.warn=e.warn??!0,this.invalidClass=e.invalidClass??"is-invalid",this.rules=Array.isArray(e.rules)?e.rules:[],this.hostElement=t,this.displayElement=t,this.rawElement=null,this.composing=!1,this.errors=[],this.normalizeCharRules=[],this.normalizeStructureRules=[],this.validateRules=[],this.fixRules=[],this.formatRules=[],this.onCompositionStart=this.onCompositionStart.bind(this),this.onCompositionEnd=this.onCompositionEnd.bind(this),this.onInput=this.onInput.bind(this),this.onBlur=this.onBlur.bind(this),this.onFocus=this.onFocus.bind(this),this.onSelectionChange=this.onSelectionChange.bind(this),this.swapState=null,this.pendingCompositionCommit=!1,this.lastAcceptedValue="",this.lastAcceptedSelection={start:null,end:null,direction:null},this.revertRequest=null}init(){this.buildPipeline(),this.applySeparateValue(),this.bindEvents(),this.evaluateInput()}readSelection(t){return{start:t.selectionStart,end:t.selectionEnd,direction:t.selectionDirection}}writeSelection(t,e){if(null!=e.start&&null!=e.end)try{e.direction?t.setSelectionRange(e.start,e.end,e.direction):t.setSelectionRange(e.start,e.end)}catch(t){}}applySeparateValue(){const t=this.options.separateValue?.mode??"auto";if("swap"!==("auto"===t?this.formatRules.length>0?"swap":"off":t))return;if("input"!==this.kind)return void i('[text-input-guard] separateValue.mode="swap" is not supported for <textarea>. ignored.',this.warn);const n=this.originalElement,s=new e(n);s.applyToRaw(n);const r=s.createDisplay(n);n.after(r),this.swapState=s,this.hostElement=n,this.displayElement=r,this.rawElement=n,this.lastAcceptedValue=r.value,this.lastAcceptedSelection=this.readSelection(r)}restoreSeparateValue(){if(!this.swapState)return;const t=this.swapState,e=this.hostElement,i=t.createdDisplay;if(i)try{e.value=e.value||i.value}catch(t){}t.removeDisplay(),t.restoreRaw(e),this.hostElement=this.originalElement,this.displayElement=this.originalElement,this.rawElement=null,this.swapState=null}detach(){this.unbindEvents(),this.restoreSeparateValue()}buildPipeline(){this.normalizeCharRules=[],this.normalizeStructureRules=[],this.validateRules=[],this.fixRules=[],this.formatRules=[];for(const t of this.rules){"input"===this.kind&&t.targets.includes("input")||"textarea"===this.kind&&t.targets.includes("textarea")?(t.normalizeChar&&this.normalizeCharRules.push(t),t.normalizeStructure&&this.normalizeStructureRules.push(t),t.validate&&this.validateRules.push(t),t.fix&&this.fixRules.push(t),t.format&&this.formatRules.push(t)):i(`[text-input-guard] Rule "${t.name}" is not supported for <${this.kind}>. skipped.`,this.warn)}}bindEvents(){this.displayElement.addEventListener("compositionstart",this.onCompositionStart),this.displayElement.addEventListener("compositionend",this.onCompositionEnd),this.displayElement.addEventListener("input",this.onInput),this.displayElement.addEventListener("blur",this.onBlur),this.displayElement.addEventListener("focus",this.onFocus),this.displayElement.addEventListener("keyup",this.onSelectionChange),this.displayElement.addEventListener("mouseup",this.onSelectionChange),this.displayElement.addEventListener("select",this.onSelectionChange),this.displayElement.addEventListener("focus",this.onSelectionChange)}unbindEvents(){this.displayElement.removeEventListener("compositionstart",this.onCompositionStart),this.displayElement.removeEventListener("compositionend",this.onCompositionEnd),this.displayElement.removeEventListener("input",this.onInput),this.displayElement.removeEventListener("blur",this.onBlur),this.displayElement.removeEventListener("focus",this.onFocus),this.displayElement.removeEventListener("keyup",this.onSelectionChange),this.displayElement.removeEventListener("mouseup",this.onSelectionChange),this.displayElement.removeEventListener("select",this.onSelectionChange),this.displayElement.removeEventListener("focus",this.onSelectionChange)}revertDisplay(t){const e=this.displayElement;e.value=this.lastAcceptedValue,this.writeSelection(e,this.lastAcceptedSelection),this.syncRaw(this.lastAcceptedValue),this.clearErrors(),this.applyInvalidClass(),this.revertRequest=null,this.warn}createCtx(){return{hostElement:this.hostElement,displayElement:this.displayElement,rawElement:this.rawElement,kind:this.kind,warn:this.warn,invalidClass:this.invalidClass,composing:this.composing,pushError:t=>this.errors.push(t),requestRevert:t=>{this.revertRequest||(this.revertRequest=t)}}}clearErrors(){this.errors=[]}runNormalizeChar(t,e){let i=t;for(const t of this.normalizeCharRules)i=t.normalizeChar?t.normalizeChar(i,e):i;return i}runNormalizeStructure(t,e){let i=t;for(const t of this.normalizeStructureRules)i=t.normalizeStructure?t.normalizeStructure(i,e):i;return i}runValidate(t,e){for(const i of this.validateRules)i.validate&&i.validate(t,e)}runFix(t,e){let i=t;for(const t of this.fixRules)i=t.fix?t.fix(i,e):i;return i}runFormat(t,e){let i=t;for(const t of this.formatRules)i=t.format?t.format(i,e):i;return i}applyInvalidClass(){const t=this.displayElement;this.errors.length>0?t.classList.add(this.invalidClass):t.classList.remove(this.invalidClass)}syncRaw(t){this.rawElement&&(this.rawElement.value=t)}syncDisplay(t){(this.displayElement instanceof HTMLInputElement||this.displayElement instanceof HTMLTextAreaElement)&&(this.displayElement.value=t)}onCompositionStart(){this.composing=!0}onCompositionEnd(){this.composing=!1,this.pendingCompositionCommit=!0,queueMicrotask(()=>{this.pendingCompositionCommit&&(this.pendingCompositionCommit=!1,this.evaluateInput())})}onInput(){this.pendingCompositionCommit=!1,this.evaluateInput()}onBlur(){this.evaluateCommit()}onFocus(){if(this.composing)return;const t=this.displayElement,e=t.value,i=this.createCtx();let n=e;n=this.runNormalizeChar(n,i),n=this.runNormalizeStructure(n,i),n!==e&&(this.setDisplayValuePreserveCaret(t,n,i),this.syncRaw(n)),this.lastAcceptedValue=n,this.lastAcceptedSelection=this.readSelection(t),this.onSelectionChange()}onSelectionChange(){if(this.composing)return;const t=this.displayElement;this.lastAcceptedSelection=this.readSelection(t)}setDisplayValuePreserveCaret(t,e,i){const n=t.value;if(n===e)return;const s=t.selectionStart,r=t.selectionEnd;if(null==s||null==r)return void(t.value=e);let a=n.slice(0,s);a=this.runNormalizeChar(a,i),a=this.runNormalizeStructure(a,i),t.value=e;const l=Math.min(a.length,e.length);try{t.setSelectionRange(l,l)}catch(t){}}evaluateInput(){if(this.composing)return;this.clearErrors(),this.revertRequest=null;const t=this.displayElement,e=t.value,i=this.createCtx();let n=e;n=this.runNormalizeChar(n,i),n=this.runNormalizeStructure(n,i),n!==e&&this.setDisplayValuePreserveCaret(t,n,i),this.runValidate(n,i),this.revertRequest?this.revertDisplay(this.revertRequest):(this.syncRaw(n),this.applyInvalidClass(),this.lastAcceptedValue=n,this.lastAcceptedSelection=this.readSelection(t))}evaluateCommit(){if(this.composing)return;this.clearErrors(),this.revertRequest=null;const t=this.displayElement,e=this.createCtx();let i=t.value;if(i=this.runNormalizeChar(i,e),i=this.runNormalizeStructure(i,e),this.runValidate(i,e),this.revertRequest)return void this.revertDisplay(this.revertRequest);if(i=this.runFix(i,e),this.clearErrors(),this.revertRequest=null,this.runValidate(i,e),this.revertRequest)return void this.revertDisplay(this.revertRequest);this.syncRaw(i);let n=i;n=this.runFormat(n,e),this.syncDisplay(n),this.applyInvalidClass(),this.lastAcceptedValue=i,this.lastAcceptedSelection=this.readSelection(t)}isValid(){return 0===this.errors.length}getErrors(){return this.errors.slice()}getRawValue(){return this.hostElement.value}getDisplayValue(){return this.displayElement.value}toGuard(){return{detach:()=>this.detach(),isValid:()=>this.isValid(),getErrors:()=>this.getErrors(),getRawValue:()=>this.getRawValue(),getDisplayValue:()=>this.getDisplayValue(),getRawElement:()=>this.hostElement,getDisplayElement:()=>this.displayElement}}}function r(t){if(null==t)return;const e=String(t).trim().toLowerCase();return""===e||"true"===e||"1"===e||"yes"===e||"on"===e||"false"!==e&&"0"!==e&&"no"!==e&&"off"!==e&&void 0}function a(t){if(null==t)return;const e=String(t).trim();if(""===e)return;const i=Number(e);return Number.isFinite(i)?i:void 0}function l(t,e){if(null==t)return;const i=String(t).trim();return""!==i&&e.includes(i)?i:void 0}function o(t){if(null==t||""===String(t).trim())return"auto";const e=String(t).trim().toLowerCase();return"auto"===e||"swap"===e||"off"===e?e:"auto"}function u(t){if(null!=t.tigSeparate)return!0;if(null!=t.tigWarn)return!0;if(null!=t.tigInvalidClass)return!0;for(const e in t)if(e.startsWith("tigRules"))return!0;return!1}function c(t={}){const e=t.allowFullWidth??!0,i=t.allowMinus??!1,n=t.allowDecimal??!1,s=t.allowEmpty??!0,r=new Set(["ー","-","−","‐","-","‒","–","—","―"]),a=new Set([".","。","。"]);function l(t){if(t>="0"&&t<="9")return t;if(e){const e=function(t){const e=t.charCodeAt(0);return 65296<=e&&e<=65305?String.fromCharCode(e-65296+48):null}(t);if(e)return e}return"."===t||e&&a.has(t)?n?".":"":"-"===t?i?"-":"":e&&r.has(t)&&i?"-":""}return{name:"numeric",targets:["input"],normalizeChar(t){let e=String(t);e=e.replace(/,/g,"");let i="";for(const t of e)i+=l(t);return i},normalizeStructure(t){let e="",s=!1,r=!1;for(const a of String(t))a>="0"&&a<="9"?e+=a:"-"===a&&i?s||0!==e.length||(e+="-",s=!0):"."===a&&n&&(r||(e+=".",r=!0));return e},fix(t){let e=String(t);if(""===e)return s?"":"0";if("-"===e||"."===e||"-."===e)return s?"":"0";e.startsWith("-.")&&(e="-0"+e.slice(1)),e.startsWith(".")&&(e="0"+e),e.endsWith(".")&&(e=e.slice(0,-1));let i="";e.startsWith("-")&&(i="-",e=e.slice(1));const n=e.indexOf(".");let r=n>=0?e.slice(0,n):e;const a=n>=0?e.slice(n+1):"";return r=r.replace(/^0+/,""),""===r&&(r="0"),"-"!==i||"0"!==r||a&&!/^0*$/.test(a)||(i=""),n>=0?`${i}${r}.${a}`:`${i}${r}`},validate(t,e){}}}function h(t){let e="",i=String(t);i.startsWith("-")&&(e="-",i=i.slice(1));const n=i.indexOf(".");if(!(n>=0))return{sign:e,intPart:i,fracPart:"",hasDot:!1};return{sign:e,intPart:i.slice(0,n),fracPart:i.slice(n+1),hasDot:!0}}function d(t){let e=1;const i=t.split("");for(let t=i.length-1;t>=0;t--){const n=i[t].charCodeAt(0)-48+e;if(!(n>=10)){i[t]=String.fromCharCode(48+n),e=0;break}i[t]="0",e=1}return 1===e&&i.unshift("1"),i.join("")}function f(t={}){const e={int:"number"==typeof t.int?t.int:void 0,frac:"number"==typeof t.frac?t.frac:void 0,countLeadingZeros:t.countLeadingZeros??!0,fixIntOnBlur:t.fixIntOnBlur??"none",fixFracOnBlur:t.fixFracOnBlur??"none",overflowInputInt:t.overflowInputInt??"none",overflowInputFrac:t.overflowInputFrac??"none",forceFracOnBlur:t.forceFracOnBlur??!1};return{name:"digits",targets:["input"],validate(t,i){const n=String(t);if(""===n||"-"===n||"."===n||"-."===n)return;const{intPart:s,fracPart:r}=h(n);if("number"==typeof e.int){const t=function(t,e){const i=t??"";if(0===i.length)return 0;if(e)return i.length;const n=i.replace(/^0+/,"");return 0===n.length?1:n.length}(s,e.countLeadingZeros);if(t>e.int){if("block"===e.overflowInputInt)return void i.requestRevert({reason:"digits.int_overflow",detail:{limit:e.int,actual:t}});i.pushError({code:"digits.int_overflow",rule:"digits",phase:"validate",detail:{limit:e.int,actual:t}})}}if("number"==typeof e.frac){const t=(r??"").length;if(t>e.frac){if("block"===e.overflowInputFrac)return void i.requestRevert({reason:"digits.frac_overflow",detail:{limit:e.frac,actual:t}});i.pushError({code:"digits.frac_overflow",rule:"digits",phase:"validate",detail:{limit:e.frac,actual:t}})}}},fix(t,i){const n=String(t);if(""===n||"-"===n||"."===n||"-."===n)return n;const s=h(n);let{intPart:r,fracPart:a}=s;const{sign:l,hasDot:o}=s;if("number"==typeof e.int&&"none"!==e.fixIntOnBlur){(r??"").length>e.int&&("truncateLeft"===e.fixIntOnBlur?r=r.slice(r.length-e.int):"truncateRight"===e.fixIntOnBlur?r=r.slice(0,e.int):"clamp"===e.fixIntOnBlur&&(r="9".repeat(e.int)))}if("number"==typeof e.frac&&"none"!==e.fixFracOnBlur&&o){const t=e.frac,i=a??"";if(i.length>t)if("truncate"===e.fixFracOnBlur)a=i.slice(0,t);else if("round"===e.fixFracOnBlur){const e=function(t,e,i){const n=e??"";if(n.length<=i)return{intPart:t,fracPart:n};const s=n.slice(0,i);if(n.charCodeAt(i)-48<5)return{intPart:t,fracPart:s};if(0===i)return{intPart:d(t.length?t:"0"),fracPart:""};let r=1;const a=s.split("");for(let t=a.length-1;t>=0;t--){const e=a[t].charCodeAt(0)-48+r;if(!(e>=10)){a[t]=String.fromCharCode(48+e),r=0;break}a[t]="0",r=1}const l=a.join("");let o=t;return 1===r&&(o=d(t.length?t:"0")),{intPart:o,fracPart:l}}(r,i,t);r=e.intPart,a=e.fracPart}}if(e.forceFracOnBlur&&"number"==typeof e.frac&&e.frac>0){const t=e.frac;o||(a="");const i=a??"";i.length<t&&(a=i+"0".repeat(t-i.length))}if("number"!=typeof e.frac)return`${l}${r}`;if(0===e.frac)return`${l}${r}`;if(o||e.forceFracOnBlur&&e.frac>0){return`${l}${r}.${a??""}`}return`${l}${r}`}}}function m(){return{name:"comma",targets:["input"],format(t){const e=String(t);if(""===e||"-"===e||"."===e||"-."===e)return e;let i="",n=e;n.startsWith("-")&&(i="-",n=n.slice(1));const s=n.indexOf("."),r=s>=0?n.slice(0,s):n,a=s>=0?n.slice(s+1):null,l=r.replace(/\B(?=(\d{3})+(?!\d))/g,",");return null!=a?`${i}${l}.${a}`:`${i}${l}`}}}c.fromDataset=function(t,e){if(null==t.tigRulesNumeric)return null;const i={},n=r(t.tigRulesNumericAllowFullWidth);null!=n&&(i.allowFullWidth=n);const s=r(t.tigRulesNumericAllowMinus);null!=s&&(i.allowMinus=s);const a=r(t.tigRulesNumericAllowDecimal);null!=a&&(i.allowDecimal=a);const l=r(t.tigRulesNumericAllowEmpty);return null!=l&&(i.allowEmpty=l),c(i)},f.fromDataset=function(t,e){if(null==t.tigRulesDigits)return null;const i={},n=a(t.tigRulesDigitsInt);null!=n&&(i.int=n);const s=a(t.tigRulesDigitsFrac);null!=s&&(i.frac=s);const o=r(t.tigRulesDigitsCountLeadingZeros);null!=o&&(i.countLeadingZeros=o);const u=l(t.tigRulesDigitsFixIntOnBlur,["none","truncateLeft","truncateRight","clamp"]);null!=u&&(i.fixIntOnBlur=u);const c=l(t.tigRulesDigitsFixFracOnBlur,["none","truncate","round"]);null!=c&&(i.fixFracOnBlur=c);const h=l(t.tigRulesDigitsOverflowInputInt,["none","block"]);null!=h&&(i.overflowInputInt=h);const d=l(t.tigRulesDigitsOverflowInputFrac,["none","block"]);null!=d&&(i.overflowInputFrac=d);const m=r(t.tigRulesDigitsForceFracOnBlur);return null!=m&&(i.forceFracOnBlur=m),f(i)},m.fromDataset=function(t,e){return null==t.tigRulesComma?null:m()};const p=new class{constructor(t,e){this.attachFn=t,this.ruleFactories=Array.isArray(e)?e:[]}register(t){this.ruleFactories.push(t)}autoAttach(t=document){const e=[],i=[];if(t.querySelectorAll){const e=t.querySelectorAll("input, textarea");for(const t of e)(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&i.push(t)}(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&(i.includes(t)||i.push(t));for(const t of i){const i=t.dataset;if("true"===i.tigAttached)continue;if(!u(i))continue;const n={},s=r(i.tigWarn);null!=s&&(n.warn=s),null!=i.tigInvalidClass&&""!==String(i.tigInvalidClass).trim()&&(n.invalidClass=String(i.tigInvalidClass)),n.separateValue={mode:o(i.tigSeparate)};const a=[];for(const e of this.ruleFactories)try{const n=e.fromDataset(i,t);n&&a.push(n)}catch(t){(n.warn??!0)&&console.warn(`[text-input-guard] autoAttach: rule "${e.name}" fromDataset() threw an error.`,t)}if(a.length>0&&(n.rules=a),!n.rules||0===n.rules.length)continue;const l=this.attachFn(t,n);e.push(l),t.dataset.tigAttached="true"}return{detach:()=>{for(const t of e)t.detach()},isValid:()=>e.every(t=>t.isValid()),getErrors:()=>e.flatMap(t=>t.getErrors()),getGuards:()=>e}}}(n,[{name:"numeric",fromDataset:c.fromDataset},{name:"digits",fromDataset:f.fromDataset},{name:"comma",fromDataset:m.fromDataset}]),g={numeric:c,digits:f,comma:m};t.attach=n,t.attachAll=function(t,e={}){const i=[];for(const s of t)i.push(n(s,e));return{detach:()=>{for(const t of i)t.detach()},isValid:()=>i.every(t=>t.isValid()),getErrors:()=>i.flatMap(t=>t.getErrors()),getGuards:()=>i}},t.autoAttach=t=>p.autoAttach(t),t.comma=m,t.digits=f,t.numeric=c,t.rules=g,t.version="0.1.0"});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "text-input-guard",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "A JavaScript input guard library for Japanese web apps, handling full-width digits, numeric rules, digit limits, and formatted display.",
5
5
  "keywords": ["input-validation",
6
6
  "numeric-input",
@@ -33,7 +33,7 @@
33
33
  "bugs": {
34
34
  "url": "https://github.com/natade-jp/text-input-guard/issues"
35
35
  },
36
- "homepage": "https://github.com/natade-jp/text-input-guard",
36
+ "homepage": "https://natade-jp.github.io/text-input-guard/",
37
37
  "files": [
38
38
  "dist/"
39
39
  ],