text-input-guard 1.0.2 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -413,6 +413,7 @@ class SwapState {
413
413
  * @property {string} [invalidClass="is-invalid"] - エラー時に付けるclass名
414
414
  * @property {SeparateValueOptions} [separateValue] - 表示値と内部値の分離設定
415
415
  * @property {(result: ValidateResult) => void} [onValidate] - 評価完了時の通知(input/commitごと)
416
+ * @property {(result: Guard) => void} [onChange] - フォーカスが外れた値が変更されていた場合の通知
416
417
  */
417
418
 
418
419
  /**
@@ -578,6 +579,18 @@ class InputGuard {
578
579
  */
579
580
  this.onValidate = options.onValidate;
580
581
 
582
+ /**
583
+ * blur時に値が変更されていた場合の通知
584
+ * @type {((result: Guard) => void) | undefined}
585
+ */
586
+ this.onChange = options.onChange;
587
+
588
+ /**
589
+ * onChange 判定のための直前の値(blur時にこれと比較して変化を検知する)
590
+ * @type {string}
591
+ */
592
+ this.previousValue = "";
593
+
581
594
  /**
582
595
  * 実際に送信を担う要素(swap時は hidden(raw) 側)
583
596
  * swapしない場合は originalElement と同一
@@ -758,6 +771,8 @@ class InputGuard {
758
771
  this.bindEvents();
759
772
  // 初期値を評価
760
773
  this.evaluateCommit();
774
+ // 初期値を記録
775
+ this.previousValue = this.getDisplayValue();
761
776
  }
762
777
 
763
778
  /**
@@ -990,11 +1005,49 @@ class InputGuard {
990
1005
  if (this.warn) ;
991
1006
  }
992
1007
 
1008
+ /**
1009
+ * 変更前後の文字列から置換範囲と挿入文字列を推測
1010
+ * @param {string} beforeText
1011
+ * @param {string} afterText
1012
+ * @returns {{ replaceStart: number, replaceEnd: number, insertedText: string }}
1013
+ */
1014
+ detectTextDiff(beforeText, afterText) {
1015
+ let start = 0;
1016
+
1017
+ while (
1018
+ start < beforeText.length &&
1019
+ start < afterText.length &&
1020
+ beforeText[start] === afterText[start]
1021
+ ) {
1022
+ start++;
1023
+ }
1024
+
1025
+ let beforeEnd = beforeText.length;
1026
+ let afterEnd = afterText.length;
1027
+
1028
+ while (
1029
+ beforeEnd > start &&
1030
+ afterEnd > start &&
1031
+ beforeText[beforeEnd - 1] === afterText[afterEnd - 1]
1032
+ ) {
1033
+ beforeEnd--;
1034
+ afterEnd--;
1035
+ }
1036
+
1037
+ return {
1038
+ replaceStart: start,
1039
+ replaceEnd: beforeEnd,
1040
+ insertedText: afterText.slice(start, afterEnd)
1041
+ };
1042
+ }
1043
+
993
1044
  /**
994
1045
  * ルール実行に渡すコンテキストを作る(pushErrorで errors に積める)
995
1046
  * @returns {GuardContext}
996
1047
  */
997
1048
  createCtx({ useSnapshot = true } = {}) {
1049
+ // 入力後のテキストを取得
1050
+ const afterText = /** @type {HTMLInputElement|HTMLTextAreaElement} */ (this.displayElement).value;
998
1051
  const snap = useSnapshot ? this.beforeInputSnapshot : null;
999
1052
  let inputType = snap?.inputType ?? "";
1000
1053
  let insertedText = snap?.insertedText ?? "";
@@ -1037,23 +1090,23 @@ class InputGuard {
1037
1090
  baseSel = lastSel;
1038
1091
  }
1039
1092
 
1040
- // beforeinput がない環境では、差分再構成の基準が「前回の受理値」しかないため、そこから今回の編集内容を推測する必要がある。
1093
+ // オートコンプリートの処理
1094
+ // inputType が取得できないため existBeforeInputEvent 情報で判断
1095
+ // 差分再構成の基準が「前回の受理値」しかないため、そこから今回の編集内容を推測する必要がある。
1041
1096
  if (beforeText.length === 0 || !this.existBeforeInputEvent) {
1042
- const display = /** @type {HTMLInputElement|HTMLTextAreaElement} */ (this.displayElement);
1043
- const current = display.value;
1044
1097
  // 前回の値がとれないものの、何かしら入力情報がある状態
1045
- if (current.length > 0) {
1098
+ if (afterText.length > 0) {
1046
1099
  // 文字列の先頭が前回の受理値と同じなら、末尾に何かしら入力されたと考えられる(オートコンプリート等)
1047
- if (current.toLocaleLowerCase().startsWith(beforeText.toLocaleLowerCase())) {
1048
- if (!current.startsWith(beforeText)) {
1100
+ if (afterText.toLocaleLowerCase().startsWith(beforeText.toLocaleLowerCase())) {
1101
+ if (!afterText.startsWith(beforeText)) {
1049
1102
  // 文字は同じだが、大文字と小文字の情報が替わっているなどのパターン
1050
1103
  // 差し代わりが起きているため、前回値は基準にならないと判断して、差分全体を insertedText とする
1051
1104
  beforeText = "";
1052
- insertedText = current;
1105
+ insertedText = afterText;
1053
1106
  } else {
1054
1107
  // 末尾に追加されたと考えられる部分を insertedText とする
1055
- // 例: beforeText="abc" → current="abcde" なら、"de" が insertedText
1056
- insertedText = current.slice(beforeText.length);
1108
+ // 例: beforeText="abc" → afterText="abcde" なら、"de" が insertedText
1109
+ insertedText = afterText.slice(beforeText.length);
1057
1110
  }
1058
1111
  // キャレットは前回値の末尾にあると推測する
1059
1112
  baseSel = /** @type {SelectionState} */ {
@@ -1072,10 +1125,10 @@ class InputGuard {
1072
1125
  let replaceStart = baseSel.start ?? 0;
1073
1126
  let replaceEnd = baseSel.end ?? 0;
1074
1127
 
1128
+ // 削除操作の特殊処理
1075
1129
  // Backspace / Delete は「挿入文字がない(dataがnull)」ことが多い。
1076
1130
  // そのままだと差分再構成で “何も変わらない” 扱いになって削除が効かなくなるため、
1077
1131
  // 選択範囲が無い場合は「削除される1文字ぶん」の置換範囲をここで作る。
1078
- //
1079
1132
  // ※ 選択範囲がある削除は replaceStart!=replaceEnd なので補正不要(その範囲を消すだけでよい)
1080
1133
  if (replaceStart === replaceEnd) {
1081
1134
  if (inputType === "deleteContentBackward") {
@@ -1091,6 +1144,14 @@ class InputGuard {
1091
1144
  // deleteWordBackward / deleteWordForward / deleteByCut / deleteSoftLineBackward ... etc
1092
1145
  }
1093
1146
 
1147
+ // アンドゥリドゥの特殊処理
1148
+ if (inputType === "historyUndo" || inputType === "historyRedo") {
1149
+ const diff = this.detectTextDiff(beforeText, afterText);
1150
+ replaceStart = diff.replaceStart;
1151
+ replaceEnd = diff.replaceEnd;
1152
+ insertedText = diff.insertedText;
1153
+ }
1154
+
1094
1155
  return {
1095
1156
  hostElement: this.hostElement,
1096
1157
  displayElement: this.displayElement,
@@ -1104,7 +1165,7 @@ class InputGuard {
1104
1165
  replaceStart,
1105
1166
  replaceEnd,
1106
1167
  insertedText,
1107
- afterText: null, // 後で代入する
1168
+ afterText,
1108
1169
  pushError: (e) => this.errors.push(e),
1109
1170
  requestRevert: (req) => {
1110
1171
  // 1回でもrevert要求が出たら採用(最初の理由を保持)
@@ -1314,7 +1375,10 @@ class InputGuard {
1314
1375
  /** @type {string|null} */
1315
1376
  const inputType = typeof e.inputType === "string" ? e.inputType : null;
1316
1377
  /** @type {string|null} */
1317
- const insertedText = typeof e.data === "string" ? e.data : null;
1378
+ let insertedText = typeof e.data === "string" ? e.data : null;
1379
+ if (insertedText === null && (inputType === "insertLineBreak" || inputType === "insertParagraph")) {
1380
+ insertedText = "\n";
1381
+ }
1318
1382
  this.existBeforeInputEvent = true;
1319
1383
  this.beforeInputSnapshot = { selection, inputType, insertedText };
1320
1384
  }
@@ -1326,6 +1390,12 @@ class InputGuard {
1326
1390
  onBlur() {
1327
1391
  // console.log("[text-input-guard] blur");
1328
1392
  this.evaluateCommit();
1393
+ if (this.previousValue !== this.getDisplayValue()) {
1394
+ this.previousValue = this.getDisplayValue();
1395
+ if (this.onChange) {
1396
+ this.onChange(this.getGuard());
1397
+ }
1398
+ }
1329
1399
  }
1330
1400
 
1331
1401
  /**
@@ -1450,10 +1520,7 @@ class InputGuard {
1450
1520
  * @returns {GuardContext}
1451
1521
  */
1452
1522
  createCtxAndNormalize() {
1453
- const display = /** @type {HTMLInputElement|HTMLTextAreaElement} */ (this.displayElement);
1454
- const current = display.value;
1455
1523
  const ctx = this.createCtx();
1456
- ctx.afterText = current;
1457
1524
 
1458
1525
  // 元のテキスト
1459
1526
  const beforeText = ctx.beforeText;
@@ -1465,7 +1532,7 @@ class InputGuard {
1465
1532
  const replaceStart = ctx.replaceStart;
1466
1533
 
1467
1534
  // 現状のテキスト
1468
- const tempText = current;
1535
+ const tempText = ctx.afterText;
1469
1536
 
1470
1537
  // 作成する全体のテキスト
1471
1538
  let newText = beforeText;
@@ -1510,7 +1577,7 @@ class InputGuard {
1510
1577
 
1511
1578
  // 画面を更新
1512
1579
  this.syncDisplay(newText);
1513
- this.writeSelection(display, newSelection);
1580
+ this.writeSelection(this.displayElement, newSelection);
1514
1581
 
1515
1582
  // CTX の情報を最新の情報へ更新する
1516
1583
  ctx.afterText = newText;
@@ -6975,9 +7042,10 @@ width.fromDataset = function fromDataset(dataset, _el) {
6975
7042
  /**
6976
7043
  * bytes ルールのオプション
6977
7044
  * @typedef {Object} BytesRuleOptions
6978
- * @property {number} [max] - 最大長(グラフェム数)。未指定なら制限なし
7045
+ * @property {number} [max] - バイト数。未指定なら制限なし
6979
7046
  * @property {"block"|"error"} [mode="block"] - 入力中に最大長を超えたときの挙動
6980
7047
  * @property {"utf-8"|"utf-16"|"utf-32"|"sjis"|"cp932"} [unit="utf-8"] - サイズの単位(sjis系を使用する場合はfilterも必須)
7048
+ * @property {"\n"|"\r"|"\r\n"} [newline="\n"] - 改行の扱い(バイト数計算に影響あり)
6981
7049
  */
6982
7050
 
6983
7051
  /**
@@ -6986,25 +7054,28 @@ width.fromDataset = function fromDataset(dataset, _el) {
6986
7054
  */
6987
7055
 
6988
7056
  /**
6989
- * グラフェム/UTF-16コード単位/UTF-32コード単位の長さを調べる
7057
+ * テキストのバイト数を調べる
6990
7058
  * @param {string} text
6991
7059
  * @param {"utf-8"|"utf-16"|"utf-32"|"sjis"|"cp932"} unit
7060
+ * @param {"\n"|"\r"|"\r\n"} newline
6992
7061
  * @returns {number}
6993
7062
  */
6994
- const getTextBytesByUnit = function(text, unit) {
7063
+ const getTextBytesByUnit = function(text, unit, newline) {
6995
7064
  if (text.length === 0) {
6996
7065
  return 0;
6997
7066
  }
7067
+
7068
+ const normalizedText = text.replace(/\r?\n/g, newline);
7069
+
6998
7070
  if (unit === "utf-8") {
6999
- return Mojix.toUTF8Array(text).length;
7071
+ return Mojix.toUTF8Array(normalizedText).length;
7000
7072
  } else if (unit === "utf-16") {
7001
- return Mojix.toUTF16Array(text).length * 2;
7073
+ return Mojix.toUTF16Array(normalizedText).length * 2;
7002
7074
  } else if (unit === "utf-32") {
7003
- return Mojix.toUTF32Array(text).length * 4;
7075
+ return Mojix.toUTF32Array(normalizedText).length * 4;
7004
7076
  } else if (unit === "sjis" || unit === "cp932") {
7005
- return Mojix.encode(text, "Shift_JIS").length;
7077
+ return Mojix.encode(normalizedText, "Shift_JIS").length;
7006
7078
  } else {
7007
- // ここには来ない
7008
7079
  throw new Error(`Invalid unit: ${unit}`);
7009
7080
  }
7010
7081
  };
@@ -7014,9 +7085,10 @@ const getTextBytesByUnit = function(text, unit) {
7014
7085
  * @param {string} text
7015
7086
  * @param {"utf-8"|"utf-16"|"utf-32"|"sjis"|"cp932"} unit
7016
7087
  * @param {number} max
7088
+ * @param {"\n"|"\r"|"\r\n"} newline
7017
7089
  * @returns {string}
7018
7090
  */
7019
- const cutTextByUnit = function(text, unit, max) {
7091
+ const cutTextByUnit = function(text, unit, max, newline) {
7020
7092
  /**
7021
7093
  * グラフェムの配列
7022
7094
  * @type {Grapheme[]}
@@ -7035,19 +7107,10 @@ const cutTextByUnit = function(text, unit, max) {
7035
7107
  const outputGraphemeArray = [];
7036
7108
 
7037
7109
  for (let i = 0; i < graphemeArray.length; i++) {
7038
- const g = graphemeArray[i];
7039
-
7040
7110
  // 1グラフェムあたりの長さ
7041
- let byteCount = 0;
7042
- if (unit === "utf-8") {
7043
- byteCount = Mojix.toUTF8Array(Mojix.toStringFromMojiArray([g])).length;
7044
- } else if (unit === "utf-16") {
7045
- byteCount = Mojix.toUTF16Array(Mojix.toStringFromMojiArray([g])).length * 2;
7046
- } else if (unit === "utf-32") {
7047
- byteCount = Mojix.toUTF32Array(Mojix.toStringFromMojiArray([g])).length * 4;
7048
- } else if (unit === "sjis" || unit === "cp932") {
7049
- byteCount = Mojix.encode(Mojix.toStringFromMojiArray([g]), "Shift_JIS").length;
7050
- }
7111
+ const g = graphemeArray[i];
7112
+ const gText = Mojix.toStringFromMojiArray([g]);
7113
+ const byteCount = getTextBytesByUnit(gText, unit, newline);
7051
7114
 
7052
7115
  if (count + byteCount > max) {
7053
7116
  // 空配列を渡すとNUL文字を返すため、空配列のときは空文字を返す
@@ -7072,15 +7135,16 @@ const cutTextByUnit = function(text, unit, max) {
7072
7135
  * @param {string} insertedText 追加するテキスト
7073
7136
  * @param {"utf-8"|"utf-16"|"utf-32"|"sjis"|"cp932"} unit
7074
7137
  * @param {number} max
7138
+ * @param {"\n"|"\r"|"\r\n"} newline
7075
7139
  * @returns {string} 追加するテキストを切ったもの(切る必要がない場合は insertedText をそのまま返す)
7076
7140
  */
7077
- const cutBytes = function(beforeText, insertedText, unit, max) {
7078
- const beforeTextLen = getTextBytesByUnit(beforeText, unit);
7141
+ const cutBytes = function(beforeText, insertedText, unit, max, newline) {
7142
+ const beforeTextLen = getTextBytesByUnit(beforeText, unit, newline);
7079
7143
 
7080
7144
  // すでに最大長を超えている場合は追加のテキストを全て切る
7081
7145
  if (beforeTextLen >= max) { return ""; }
7082
7146
 
7083
- const insertedTextLen = getTextBytesByUnit(insertedText, unit);
7147
+ const insertedTextLen = getTextBytesByUnit(insertedText, unit, newline);
7084
7148
  const totalLen = beforeTextLen + insertedTextLen;
7085
7149
 
7086
7150
  if (totalLen <= max) {
@@ -7090,7 +7154,7 @@ const cutBytes = function(beforeText, insertedText, unit, max) {
7090
7154
 
7091
7155
  // 超える場合は追加のテキストを切る
7092
7156
  const allowedAddLen = max - beforeTextLen;
7093
- return cutTextByUnit(insertedText, unit, allowedAddLen);
7157
+ return cutTextByUnit(insertedText, unit, allowedAddLen, newline);
7094
7158
  };
7095
7159
 
7096
7160
  /**
@@ -7099,12 +7163,10 @@ const cutBytes = function(beforeText, insertedText, unit, max) {
7099
7163
  * @returns {Rule}
7100
7164
  */
7101
7165
  function bytes(options = {}) {
7102
- /** @type {BytesRuleOptions} */
7103
- const opt = {
7104
- max: typeof options.max === "number" ? options.max : undefined,
7105
- mode: options.mode ?? "block",
7106
- unit: options.unit ?? "utf-8"
7107
- };
7166
+ const max = typeof options.max === "number" ? options.max : undefined;
7167
+ const mode = options.mode ?? "block";
7168
+ const unit = options.unit ?? "utf-8";
7169
+ const newline = options.newline ?? "\n";
7108
7170
 
7109
7171
  return {
7110
7172
  name: "bytes",
@@ -7112,35 +7174,35 @@ function bytes(options = {}) {
7112
7174
 
7113
7175
  normalizeChar(value, ctx) {
7114
7176
  // block 以外は何もしない
7115
- if (opt.mode !== "block") {
7177
+ if (mode !== "block") {
7116
7178
  return value;
7117
7179
  }
7118
7180
  // max 未指定なら制限なし
7119
- if (typeof opt.max !== "number") {
7181
+ if (typeof max !== "number") {
7120
7182
  return value;
7121
7183
  }
7122
7184
 
7123
- const cutText = cutBytes(ctx.beforeText, value, opt.unit, opt.max);
7185
+ const cutText = cutBytes(ctx.beforeText, value, unit, max, newline);
7124
7186
  return cutText;
7125
7187
  },
7126
7188
 
7127
7189
  validate(value, ctx) {
7128
7190
  // error 以外は何もしない
7129
- if (opt.mode !== "error") {
7191
+ if (mode !== "error") {
7130
7192
  return;
7131
7193
  }
7132
7194
  // max 未指定なら制限なし
7133
- if (typeof opt.max !== "number") {
7195
+ if (typeof max !== "number") {
7134
7196
  return;
7135
7197
  }
7136
7198
 
7137
- const len = getTextBytesByUnit(value, opt.unit);
7138
- if (len > opt.max) {
7199
+ const len = getTextBytesByUnit(value, unit, newline);
7200
+ if (len > max) {
7139
7201
  ctx.pushError({
7140
7202
  code: "bytes.max_overflow",
7141
7203
  rule: "bytes",
7142
7204
  phase: "validate",
7143
- detail: { limit: opt.max, actual: len }
7205
+ detail: { limit: max, actual: len }
7144
7206
  });
7145
7207
  }
7146
7208
  }
@@ -7157,6 +7219,7 @@ function bytes(options = {}) {
7157
7219
  * - data-tig-rules-bytes-max -> dataset.tigRulesBytesMax
7158
7220
  * - data-tig-rules-bytes-mode -> dataset.tigRulesBytesMode
7159
7221
  * - data-tig-rules-bytes-unit -> dataset.tigRulesBytesUnit
7222
+ * - data-tig-rules-bytes-newline -> dataset.tigRulesBytesNewline
7160
7223
  *
7161
7224
  * @param {DOMStringMap} dataset
7162
7225
  * @param {HTMLInputElement|HTMLTextAreaElement} _el
@@ -7189,6 +7252,14 @@ bytes.fromDataset = function fromDataset(dataset, _el) {
7189
7252
  options.unit = unit;
7190
7253
  }
7191
7254
 
7255
+ const newline = parseDatasetEnum(
7256
+ dataset.tigRulesBytesNewline,
7257
+ ["\n", "\r", "\r\n"]
7258
+ );
7259
+ if (newline != null) {
7260
+ options.newline = newline;
7261
+ }
7262
+
7192
7263
  return bytes(options);
7193
7264
  };
7194
7265
 
@@ -7486,10 +7557,34 @@ const rules = {
7486
7557
 
7487
7558
  /**
7488
7559
  * バージョン(ビルド時に置換したいならここを差し替える)
7489
- * 例: rollup replace で ""1.0.2"" を package.json の version に置換
7560
+ * 例: rollup replace で ""1.1.0"" を package.json の version に置換
7490
7561
  */
7491
7562
  // @ts-ignore
7492
7563
  // eslint-disable-next-line no-undef
7493
- const version = "1.0.2" ;
7564
+ const version = "1.1.0" ;
7565
+
7566
+ /**
7567
+ * UMD公開時のグローバルオブジェクト
7568
+ */
7569
+ const TextInputGuard = {
7570
+ attach,
7571
+ attachAll,
7572
+ autoAttach,
7573
+ rules,
7574
+ numeric,
7575
+ digits,
7576
+ comma,
7577
+ imeOff,
7578
+ kana,
7579
+ ascii,
7580
+ filter,
7581
+ length,
7582
+ width,
7583
+ bytes,
7584
+ prefix,
7585
+ suffix,
7586
+ trim,
7587
+ version
7588
+ };
7494
7589
 
7495
- export { ascii, attach, attachAll, autoAttach, bytes, comma, digits, filter, imeOff, kana, length, numeric, prefix, rules, suffix, trim, version, width };
7590
+ export { TextInputGuard, ascii, attach, attachAll, autoAttach, bytes, comma, digits, filter, imeOff, kana, length, numeric, prefix, rules, suffix, trim, version, width };