react-native-nitro-input 0.3.0 → 0.3.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.
Files changed (150) hide show
  1. package/CHANGELOG.md +80 -0
  2. package/README.md +120 -5
  3. package/android/src/main/cpp/JMaskEngine.cpp +45 -0
  4. package/android/src/main/cpp/JMaskEngine.hpp +9 -0
  5. package/android/src/main/cpp/JReflowEngine.cpp +32 -0
  6. package/android/src/main/cpp/JReflowEngine.hpp +13 -0
  7. package/android/src/main/cpp/JRollingEngine.cpp +42 -2
  8. package/android/src/main/cpp/JRollingEngine.hpp +9 -1
  9. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroInputView.kt +24 -0
  10. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroNumberFormatPlatform.kt +76 -1
  11. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroNumberView.kt +88 -0
  12. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroTextMeasure.kt +25 -0
  13. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroTextView.kt +140 -0
  14. package/android/src/main/java/com/margelo/nitro/nitroinput/MaskEngine.kt +16 -0
  15. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputPackage.kt +2 -1
  16. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputView.kt +96 -6
  17. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroNumberView.kt +388 -136
  18. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroTextView.kt +868 -0
  19. package/android/src/main/java/com/margelo/nitro/nitroinput/ReflowEngine.kt +21 -0
  20. package/android/src/main/java/com/margelo/nitro/nitroinput/RollingEngine.kt +13 -2
  21. package/cpp/MaskEngine.cpp +294 -33
  22. package/cpp/MaskEngine.hpp +68 -0
  23. package/cpp/RollingEngine.cpp +92 -8
  24. package/cpp/RollingEngine.hpp +36 -2
  25. package/ios/HybridNitroInputView.swift +18 -0
  26. package/ios/HybridNitroNumberFormatPlatform.swift +87 -9
  27. package/ios/HybridNitroNumberView.swift +82 -1
  28. package/ios/HybridNitroTextView.swift +134 -0
  29. package/ios/NitroInputView.swift +125 -7
  30. package/ios/NitroNumberView.swift +368 -135
  31. package/ios/NitroTextView.swift +583 -0
  32. package/lib/commonjs/nitrogen/generated/shared/json/NitroInputViewConfig.json +6 -0
  33. package/lib/commonjs/nitrogen/generated/shared/json/NitroNumberViewConfig.json +20 -0
  34. package/lib/commonjs/nitrogen/generated/shared/json/NitroTextViewConfig.json +30 -0
  35. package/lib/commonjs/src/NitroInput.js +15 -2
  36. package/lib/commonjs/src/NitroNumber.js +52 -3
  37. package/lib/commonjs/src/NitroText.js +138 -0
  38. package/lib/commonjs/src/NitroTime.js +65 -0
  39. package/lib/commonjs/src/formatProps.js +76 -16
  40. package/lib/commonjs/src/index.js +6 -1
  41. package/lib/commonjs/src/specs/NitroText.nitro.js +2 -0
  42. package/lib/module/nitrogen/generated/shared/json/NitroInputViewConfig.json +6 -0
  43. package/lib/module/nitrogen/generated/shared/json/NitroNumberViewConfig.json +20 -0
  44. package/lib/module/nitrogen/generated/shared/json/NitroTextViewConfig.json +30 -0
  45. package/lib/module/src/NitroInput.js +15 -2
  46. package/lib/module/src/NitroNumber.js +53 -4
  47. package/lib/module/src/NitroText.js +98 -0
  48. package/lib/module/src/NitroTime.js +29 -0
  49. package/lib/module/src/formatProps.js +76 -17
  50. package/lib/module/src/index.js +2 -0
  51. package/lib/module/src/specs/NitroText.nitro.js +1 -0
  52. package/lib/typescript/src/NitroInput.d.ts +39 -1
  53. package/lib/typescript/src/NitroNumber.d.ts +79 -1
  54. package/lib/typescript/src/NitroText.d.ts +67 -0
  55. package/lib/typescript/src/NitroTime.d.ts +19 -0
  56. package/lib/typescript/src/formatProps.d.ts +30 -4
  57. package/lib/typescript/src/index.d.ts +5 -2
  58. package/lib/typescript/src/specs/NitroInput.nitro.d.ts +43 -0
  59. package/lib/typescript/src/specs/NitroNumber.nitro.d.ts +67 -0
  60. package/lib/typescript/src/specs/NitroText.nitro.d.ts +60 -0
  61. package/nitro.json +20 -0
  62. package/nitrogen/generated/android/NitroInput+autolinking.cmake +6 -0
  63. package/nitrogen/generated/android/NitroInputOnLoad.cpp +34 -0
  64. package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.cpp +102 -0
  65. package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.hpp +12 -0
  66. package/nitrogen/generated/android/c++/JHybridNitroNumberViewSpec.cpp +243 -0
  67. package/nitrogen/generated/android/c++/JHybridNitroNumberViewSpec.hpp +40 -0
  68. package/nitrogen/generated/android/c++/JHybridNitroTextMeasureSpec.cpp +58 -0
  69. package/nitrogen/generated/android/c++/JHybridNitroTextMeasureSpec.hpp +64 -0
  70. package/nitrogen/generated/android/c++/JHybridNitroTextViewSpec.cpp +253 -0
  71. package/nitrogen/generated/android/c++/JHybridNitroTextViewSpec.hpp +104 -0
  72. package/nitrogen/generated/android/c++/JNitroInputCharacterMapping.hpp +61 -0
  73. package/nitrogen/generated/android/c++/JNitroInputMaskAffinity.hpp +64 -0
  74. package/nitrogen/generated/android/c++/JNitroInputTextCase.hpp +61 -0
  75. package/nitrogen/generated/android/c++/JNitroNumberShimmerDirection.hpp +61 -0
  76. package/nitrogen/generated/android/c++/JNitroNumberSignDisplay.hpp +67 -0
  77. package/nitrogen/generated/android/c++/views/JHybridNitroInputViewStateUpdater.cpp +30 -0
  78. package/nitrogen/generated/android/c++/views/JHybridNitroNumberViewStateUpdater.cpp +100 -0
  79. package/nitrogen/generated/android/c++/views/JHybridNitroTextViewStateUpdater.cpp +174 -0
  80. package/nitrogen/generated/android/c++/views/JHybridNitroTextViewStateUpdater.hpp +54 -0
  81. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroInputViewSpec.kt +36 -0
  82. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroNumberViewSpec.kt +136 -0
  83. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroTextMeasureSpec.kt +60 -0
  84. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroTextViewSpec.kt +179 -0
  85. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputCharacterMapping.kt +56 -0
  86. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputMaskAffinity.kt +25 -0
  87. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputTextCase.kt +24 -0
  88. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroNumberShimmerDirection.kt +24 -0
  89. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroNumberSignDisplay.kt +26 -0
  90. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/views/HybridNitroTextViewManager.kt +96 -0
  91. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/views/HybridNitroTextViewStateUpdater.kt +23 -0
  92. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Bridge.cpp +34 -0
  93. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Bridge.hpp +146 -11
  94. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Umbrella.hpp +25 -0
  95. package/nitrogen/generated/ios/NitroInputAutolinking.mm +16 -0
  96. package/nitrogen/generated/ios/NitroInputAutolinking.swift +24 -0
  97. package/nitrogen/generated/ios/c++/HybridNitroInputViewSpecSwift.hpp +50 -0
  98. package/nitrogen/generated/ios/c++/HybridNitroNumberViewSpecSwift.hpp +146 -0
  99. package/nitrogen/generated/ios/c++/HybridNitroTextMeasureSpecSwift.cpp +11 -0
  100. package/nitrogen/generated/ios/c++/HybridNitroTextMeasureSpecSwift.hpp +90 -0
  101. package/nitrogen/generated/ios/c++/HybridNitroTextViewSpecSwift.cpp +11 -0
  102. package/nitrogen/generated/ios/c++/HybridNitroTextViewSpecSwift.hpp +233 -0
  103. package/nitrogen/generated/ios/c++/views/HybridNitroInputViewComponent.mm +36 -0
  104. package/nitrogen/generated/ios/c++/views/HybridNitroNumberViewComponent.mm +120 -0
  105. package/nitrogen/generated/ios/c++/views/HybridNitroTextViewComponent.mm +264 -0
  106. package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec.swift +6 -0
  107. package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec_cxx.swift +78 -0
  108. package/nitrogen/generated/ios/swift/HybridNitroNumberViewSpec.swift +20 -0
  109. package/nitrogen/generated/ios/swift/HybridNitroNumberViewSpec_cxx.swift +493 -0
  110. package/nitrogen/generated/ios/swift/HybridNitroTextMeasureSpec.swift +56 -0
  111. package/nitrogen/generated/ios/swift/HybridNitroTextMeasureSpec_cxx.swift +150 -0
  112. package/nitrogen/generated/ios/swift/HybridNitroTextViewSpec.swift +75 -0
  113. package/nitrogen/generated/ios/swift/HybridNitroTextViewSpec_cxx.swift +608 -0
  114. package/nitrogen/generated/ios/swift/NitroInputCharacterMapping.swift +34 -0
  115. package/nitrogen/generated/ios/swift/NitroInputMaskAffinity.swift +48 -0
  116. package/nitrogen/generated/ios/swift/NitroInputTextCase.swift +44 -0
  117. package/nitrogen/generated/ios/swift/NitroNumberShimmerDirection.swift +44 -0
  118. package/nitrogen/generated/ios/swift/NitroNumberSignDisplay.swift +52 -0
  119. package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.cpp +12 -0
  120. package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.hpp +21 -0
  121. package/nitrogen/generated/shared/c++/HybridNitroNumberViewSpec.cpp +40 -0
  122. package/nitrogen/generated/shared/c++/HybridNitroNumberViewSpec.hpp +46 -0
  123. package/nitrogen/generated/shared/c++/HybridNitroTextMeasureSpec.cpp +22 -0
  124. package/nitrogen/generated/shared/c++/HybridNitroTextMeasureSpec.hpp +63 -0
  125. package/nitrogen/generated/shared/c++/HybridNitroTextViewSpec.cpp +62 -0
  126. package/nitrogen/generated/shared/c++/HybridNitroTextViewSpec.hpp +115 -0
  127. package/nitrogen/generated/shared/c++/NitroInputCharacterMapping.hpp +87 -0
  128. package/nitrogen/generated/shared/c++/NitroInputMaskAffinity.hpp +84 -0
  129. package/nitrogen/generated/shared/c++/NitroInputTextCase.hpp +80 -0
  130. package/nitrogen/generated/shared/c++/NitroNumberShimmerDirection.hpp +80 -0
  131. package/nitrogen/generated/shared/c++/NitroNumberSignDisplay.hpp +88 -0
  132. package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.cpp +12 -0
  133. package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.hpp +21 -0
  134. package/nitrogen/generated/shared/c++/views/HybridNitroNumberViewComponent.cpp +40 -0
  135. package/nitrogen/generated/shared/c++/views/HybridNitroNumberViewComponent.hpp +62 -0
  136. package/nitrogen/generated/shared/c++/views/HybridNitroTextViewComponent.cpp +74 -0
  137. package/nitrogen/generated/shared/c++/views/HybridNitroTextViewComponent.hpp +149 -0
  138. package/nitrogen/generated/shared/json/NitroInputViewConfig.json +6 -0
  139. package/nitrogen/generated/shared/json/NitroNumberViewConfig.json +20 -0
  140. package/nitrogen/generated/shared/json/NitroTextViewConfig.json +30 -0
  141. package/package.json +2 -2
  142. package/src/NitroInput.tsx +73 -0
  143. package/src/NitroNumber.tsx +183 -9
  144. package/src/NitroText.tsx +166 -0
  145. package/src/NitroTime.tsx +68 -0
  146. package/src/formatProps.ts +108 -18
  147. package/src/index.ts +8 -0
  148. package/src/specs/NitroInput.nitro.ts +46 -0
  149. package/src/specs/NitroNumber.nitro.ts +69 -0
  150. package/src/specs/NitroText.nitro.ts +65 -0
@@ -44,4 +44,25 @@ class ReflowEngine {
44
44
  * and returns the number of doubles written, or -1 if [out] is too small.
45
45
  */
46
46
  external fun frameInto(out: DoubleArray): Int
47
+
48
+ /**
49
+ * A whole line in one JNI crossing instead of one per character:
50
+ * `setReduceMotion`, `beginText`, an `addGlyph` per character (all in
51
+ * [role], none a placeholder) and `commitText`. Returns [needsFrames].
52
+ */
53
+ external fun commitLine(
54
+ characters: IntArray, kinds: IntArray, widths: DoubleArray, count: Int,
55
+ role: Int, reduceMotion: Boolean, caret: Int, now: Double,
56
+ ): Boolean
57
+
58
+ /**
59
+ * [tick] and [frameInto] in one crossing: the doubles written (or -1 when
60
+ * [out] is too small, after ticking), with [MORE_FRAMES] set while the
61
+ * engine still needs frames.
62
+ */
63
+ external fun tickInto(now: Double, out: DoubleArray): Int
64
+
65
+ companion object {
66
+ const val MORE_FRAMES = 1 shl 30
67
+ }
47
68
  }
@@ -23,7 +23,18 @@ class RollingEngine {
23
23
  external fun setFlash(seconds: Double)
24
24
  external fun setPopOnChange(overshoot: Double)
25
25
  external fun setReduceMotion(reduceMotion: Boolean)
26
- /** A text slot (0 prefix, 1 suffix, 2 grouping, 3 decimal) changed; see `RollingEngine::changeText`. */
26
+ external fun setContinuous(continuous: Boolean)
27
+ /** The highest digit the wheel at integer [power] shows before it wraps (a clock's 5); see `RollingEngine::setDigitMax`. */
28
+ external fun setDigitMax(power: Int, max: Int)
29
+ external fun clearDigitMax()
30
+ /** Places the wheel at [index] wraps after: 10, or `max + 1`. [frameInto] carries it per wheel too. */
31
+ external fun wheelModulus(index: Int): Int
32
+ /** ECMA-402's signDisplay: 0 auto, 1 always, 2 exceptZero, 3 negative, 4 never. */
33
+ external fun setSignDisplay(mode: Int)
34
+ /** True when the sign shown (or last shown) is a plus. */
35
+ external fun signPositive(): Boolean
36
+ external fun signFactor(): Double
37
+ /** A text slot (0 prefix, 1 suffix, 2 grouping, 3 decimal, 4 sign) changed; see `RollingEngine::changeText`. */
27
38
  external fun changeText(slot: Int, now: Double)
28
39
  /** `setFormat`, the change played; see `RollingEngine::changeFormat`. */
29
40
  external fun changeFormat(fractionDigits: Int, minimumIntegerDigits: Int, now: Double)
@@ -46,7 +57,7 @@ class RollingEngine {
46
57
  external fun revealMilestoneValue(index: Int): Double
47
58
  /**
48
59
  * Fills [out] with the render state without allocating:
49
- * `[signFactor, loadingProgress, revealScale, wheelCount, (position, width, linear, blankZero, fromGlyph, toGlyph, blend, fromAbove, flash, flashUp, focus, grow, blurOut, progress)…]`,
60
+ * `[signFactor, loadingProgress, revealScale, wheelCount, (position, width, linear, blankZero, fromGlyph, toGlyph, blend, fromAbove, flash, flashUp, focus, grow, blurOut, progress, modulus)…]`,
50
61
  * then each text slot's swap and the decimal columns.
51
62
  * Returns the number of doubles written, or -1 if [out] is too small.
52
63
  */
@@ -8,6 +8,7 @@
8
8
  #include "AmountFormatter.hpp"
9
9
 
10
10
  #include <algorithm>
11
+ #include <climits>
11
12
  #include <optional>
12
13
 
13
14
  namespace margelo::nitro::nitroinput {
@@ -20,8 +21,67 @@ bool isDigit(uint32_t c) {
20
21
  return c >= '0' && c <= '9';
21
22
  }
22
23
 
24
+ /// Letters a `[A]`/`[a]` slot takes: ASCII and the alphabetic blocks of the
25
+ /// scripts people type into forms (Latin with its diacritics, Greek,
26
+ /// Cyrillic, Armenian, Hebrew, Arabic, Devanagari, Thai, Hangul, kana and CJK
27
+ /// ideographs). Not a full Unicode letter table - that would outweigh the
28
+ /// engine - but no longer ASCII only, which refused every Cyrillic name.
23
29
  bool isLetter(uint32_t c) {
24
- return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
30
+ if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) return true;
31
+ if (c < 0xC0) return false;
32
+ if (c <= 0x24F) return c != 0xD7 && c != 0xF7; // Latin-1 letters, Latin Extended-A/B
33
+ if (c >= 0x370 && c <= 0x3FF) return c >= 0x386 && c != 0x387 && c != 0x3F6; // Greek
34
+ if (c >= 0x400 && c <= 0x52F) return (c < 0x482 || c > 0x489); // Cyrillic (+ supplement)
35
+ if (c >= 0x531 && c <= 0x587) return c <= 0x556 || c >= 0x561; // Armenian
36
+ if (c >= 0x5D0 && c <= 0x5EA) return true; // Hebrew
37
+ if (c >= 0x620 && c <= 0x64A) return true; // Arabic
38
+ if (c >= 0x904 && c <= 0x939) return true; // Devanagari
39
+ if (c >= 0xE01 && c <= 0xE30) return true; // Thai
40
+ if (c >= 0x1E00 && c <= 0x1EFF) return true; // Latin Extended Additional (Vietnamese)
41
+ if (c >= 0x3041 && c <= 0x30FA) return c != 0x30A0; // Hiragana, Katakana
42
+ if (c >= 0x4E00 && c <= 0x9FFF) return true; // CJK ideographs
43
+ if (c >= 0xAC00 && c <= 0xD7A3) return true; // Hangul syllables
44
+ return false;
45
+ }
46
+
47
+ /// Upper- and lower-case counterparts for the cased scripts `isLetter` knows.
48
+ /// Anything else maps to itself.
49
+ uint32_t toUpper(uint32_t c) {
50
+ if (c >= 'a' && c <= 'z') return c - 32;
51
+ if (c < 0xE0) return c;
52
+ if (c == 0xFF) return 0x178; // ÿ → Ÿ
53
+ if (c <= 0xFE) return c == 0xF7 ? c : c - 32; // Latin-1
54
+ if (c >= 0x100 && c <= 0x17F) { // Latin Extended-A
55
+ if ((c >= 0x139 && c <= 0x148) || (c >= 0x179 && c <= 0x17E)) return (c % 2 == 0) ? c - 1 : c;
56
+ if (c == 0x131 || c == 0x138 || c == 0x149 || c == 0x17F) return c;
57
+ return (c % 2 == 1) ? c - 1 : c;
58
+ }
59
+ if (c >= 0x3B1 && c <= 0x3C9) return c == 0x3C2 ? 0x3A3 : c - 32; // Greek (final sigma → Σ)
60
+ if (c >= 0x430 && c <= 0x44F) return c - 32; // Cyrillic
61
+ if (c >= 0x450 && c <= 0x45F) return c - 80;
62
+ if ((c >= 0x460 && c <= 0x481) || (c >= 0x48A && c <= 0x4BF)) return (c % 2 == 1) ? c - 1 : c;
63
+ if (c >= 0x561 && c <= 0x586) return c - 48; // Armenian
64
+ if (c >= 0x1E00 && c <= 0x1EFF) return (c % 2 == 1) ? c - 1 : c; // Vietnamese and co.
65
+ return c;
66
+ }
67
+
68
+ uint32_t toLower(uint32_t c) {
69
+ if (c >= 'A' && c <= 'Z') return c + 32;
70
+ if (c < 0xC0) return c;
71
+ if (c <= 0xDE) return c == 0xD7 ? c : c + 32; // Latin-1
72
+ if (c == 0x178) return 0xFF; // Ÿ → ÿ
73
+ if (c >= 0x100 && c <= 0x17F) { // Latin Extended-A
74
+ if ((c >= 0x139 && c <= 0x148) || (c >= 0x179 && c <= 0x17E)) return (c % 2 == 1) ? c + 1 : c;
75
+ if (c == 0x130 || c == 0x131 || c == 0x138 || c == 0x149 || c == 0x17F) return c;
76
+ return (c % 2 == 0) ? c + 1 : c;
77
+ }
78
+ if (c >= 0x391 && c <= 0x3A9 && c != 0x3A2) return c + 32; // Greek
79
+ if (c >= 0x410 && c <= 0x42F) return c + 32; // Cyrillic
80
+ if (c >= 0x400 && c <= 0x40F) return c + 80;
81
+ if ((c >= 0x460 && c <= 0x481) || (c >= 0x48A && c <= 0x4BF)) return (c % 2 == 0) ? c + 1 : c;
82
+ if (c >= 0x531 && c <= 0x556) return c + 48; // Armenian
83
+ if (c >= 0x1E00 && c <= 0x1EFF) return (c % 2 == 0) ? c + 1 : c;
84
+ return c;
25
85
  }
26
86
 
27
87
  constexpr uint32_t kEllipsis = 0x2026; // …
@@ -244,8 +304,12 @@ void normalizeBlock(const CodePoints& block, std::vector<CodePoints>* out) {
244
304
  if (!run.empty()) runs.push_back(run);
245
305
 
246
306
  for (CodePoints& piece : runs) {
247
- // Mandatory before optional, order otherwise preserved.
248
- std::stable_partition(piece.begin(), piece.end(), [](uint32_t c) { return !isOptionalSlot(c); });
307
+ // Mandatory before optional, order otherwise preserved - and an ellipsis
308
+ // always last: it repeats the slot in front of it, so `[9…]` moved to
309
+ // `[…9]` would repeat nothing and take letters (upstream sorts by code,
310
+ // which leaves `…` last for the same reason).
311
+ const auto rank = [](uint32_t c) { return c == kEllipsis ? 2 : isOptionalSlot(c) ? 1 : 0; };
312
+ std::stable_sort(piece.begin(), piece.end(), [&](uint32_t a, uint32_t b) { return rank(a) < rank(b); });
249
313
  CodePoints wrapped;
250
314
  wrapped.reserve(piece.size() + 2);
251
315
  wrapped.push_back('[');
@@ -396,31 +460,91 @@ bool MaskEngine::setFormat(const std::string& format) {
396
460
  return setFormat(format, staged_);
397
461
  }
398
462
 
399
- bool MaskEngine::setFormat(const std::string& format, const std::vector<Notation>& notations) {
400
- compiled_.reset();
401
- if (format.empty()) return false;
463
+ std::shared_ptr<const MaskEngine::Compiled> MaskEngine::compileFormat(const std::string& format,
464
+ const std::vector<Notation>& notations) {
465
+ if (format.empty()) return nullptr;
402
466
 
403
- auto next = std::make_unique<Compiled>();
467
+ auto next = std::make_shared<Compiled>();
404
468
  next->notations = notations;
405
469
 
406
470
  // A notation may not redefine a built-in slot character - the compiler would
407
471
  // never reach it, so the caller's intent could not be honoured.
408
472
  for (const Notation& notation : next->notations) {
409
- if (isReservedSlot(notation.character) || notation.characterSet.empty()) return false;
473
+ if (isReservedSlot(notation.character) || notation.characterSet.empty()) return nullptr;
410
474
  }
411
475
 
412
476
  CodePoints sanitized;
413
- if (!sanitize(AmountFormatter::decode(format), &sanitized)) return false;
477
+ if (!sanitize(AmountFormatter::decode(format), &sanitized)) return nullptr;
414
478
 
415
479
  bool ok = true;
416
480
  const State* initial = compile(*next, sanitized, 0, false, false, 0, &ok);
417
- if (!ok || initial == nullptr) return false;
418
-
481
+ if (!ok || initial == nullptr) return nullptr;
419
482
  next->initial = initial;
420
- compiled_ = std::move(next);
483
+
484
+ // What the format can hold, for the capacity strategies and the paste rule.
485
+ bool leading = true;
486
+ for (const State* s = initial; s != nullptr && s->slot != Slot::EndOfLine; s = s->child) {
487
+ if (s->elliptical) {
488
+ next->textCapacity = kUnbounded;
489
+ next->valueCapacity = kUnbounded;
490
+ break;
491
+ }
492
+ if (s->slot == Slot::Free || s->slot == Slot::Fixed) {
493
+ if (leading) next->leadingConstants.push_back(s->ownCharacter);
494
+ next->textCapacity += 1;
495
+ if (s->slot == Slot::Fixed) next->valueCapacity += 1;
496
+ } else {
497
+ leading = false;
498
+ next->textCapacity += 1;
499
+ next->valueCapacity += 1;
500
+ }
501
+ }
502
+ return next;
503
+ }
504
+
505
+ bool MaskEngine::setFormat(const std::string& format, const std::vector<Notation>& notations) {
506
+ compiled_.reset();
507
+ alternatives_.clear();
508
+ compiled_ = compileFormat(format, notations);
509
+ if (compiled_ == nullptr) return false;
510
+ for (const std::string& alternative : stagedAffinityFormats_) {
511
+ if (auto compiled = compileFormat(alternative, notations)) alternatives_.push_back(std::move(compiled));
512
+ }
421
513
  return true;
422
514
  }
423
515
 
516
+ void MaskEngine::clearAffinityFormats() {
517
+ stagedAffinityFormats_.clear();
518
+ }
519
+
520
+ void MaskEngine::addAffinityFormat(const std::string& format) {
521
+ stagedAffinityFormats_.push_back(format);
522
+ }
523
+
524
+ void MaskEngine::setAffinityStrategy(int strategy) {
525
+ affinityStrategy_ = std::clamp(strategy, kAffinityWholeString, kAffinityExtractedValueCapacity);
526
+ }
527
+
528
+ void MaskEngine::setTextCase(int textCase) {
529
+ textCase_ = std::clamp(textCase, kTextCaseNone, kTextCaseLower);
530
+ }
531
+
532
+ void MaskEngine::clearCharacterMap() {
533
+ characterMap_.clear();
534
+ }
535
+
536
+ void MaskEngine::addCharacterMapping(const std::string& from, const std::string& to) {
537
+ const CodePoints source = AmountFormatter::decode(from);
538
+ if (source.empty()) return;
539
+ const CodePoints target = AmountFormatter::decode(to);
540
+ characterMap_.emplace_back(source[0], target.empty() ? 0 : target[0]);
541
+ }
542
+
543
+ void MaskEngine::setSlotPlaceholder(const std::string& character) {
544
+ const CodePoints decoded = AmountFormatter::decode(character);
545
+ slotPlaceholder_ = decoded.empty() ? 0 : decoded[0];
546
+ }
547
+
424
548
  // MARK: - Applying
425
549
 
426
550
  MaskEngine::Result MaskEngine::apply(const std::string& text, int caret, bool caretForward, bool autocomplete,
@@ -443,11 +567,123 @@ MaskEngine::Result MaskEngine::apply(const std::string& text, int caret, bool ca
443
567
  return apply(text, caret, caretForward, false, autoSkip);
444
568
  }
445
569
 
446
- const CodePoints input = AmountFormatter::decode(text);
447
- const int caretPosition = std::clamp(caret, 0, static_cast<int>(input.size()));
570
+ int caretPosition = std::clamp(caret, 0, AmountFormatter::codePointCount(text));
571
+ CodePoints input = prepareInput(AmountFormatter::decode(text), &caretPosition);
572
+
573
+ if (alternatives_.empty()) {
574
+ return applyCompiled(*compiled_, input, caretPosition, caretForward, autocomplete, autoSkip);
575
+ }
576
+
577
+ // With several formats the text still carries the separators whichever one
578
+ // won last time inserted: "3782 8224 6" typed under 4-4-4-4 would count its
579
+ // spaces against the Amex 4-6-5 format and never let it take over. So every
580
+ // format re-masks the value characters alone; each puts its own literals back.
581
+ const std::vector<Notation>& notations = compiled_->notations;
582
+ const auto isValueCharacter = [&](uint32_t c) {
583
+ if (isDigit(c) || isLetter(c)) return true;
584
+ return std::any_of(notations.begin(), notations.end(), [c](const Notation& n) {
585
+ return std::find(n.characterSet.begin(), n.characterSet.end(), c) != n.characterSet.end();
586
+ });
587
+ };
588
+ CodePoints values;
589
+ values.reserve(input.size());
590
+ const int originalCaret = caretPosition;
591
+ for (size_t i = 0; i < input.size(); ++i) {
592
+ if (isValueCharacter(input[i])) {
593
+ values.push_back(input[i]);
594
+ } else if (static_cast<int>(i) < originalCaret) {
595
+ caretPosition -= 1;
596
+ }
597
+ }
598
+
599
+ // Ties go to the format that keeps more of what the field already shows -
600
+ // the one whose output shares the longer prefix with the text. The text
601
+ // still carries the separators of whichever format is showing, so that is
602
+ // the incumbent: a 4-6-5 card does not flip back to 4-4-4-4 at the 11th and
603
+ // 12th digit, where the two score the same. With nothing to tell them apart
604
+ // (an empty field, or text both lay out alike) the primary keeps it.
605
+ const auto sharedPrefix = [&](const Result& result) {
606
+ const CodePoints formatted = AmountFormatter::decode(result.formattedText);
607
+ size_t shared = 0;
608
+ while (shared < formatted.size() && shared < input.size() && formatted[shared] == input[shared]) shared++;
609
+ return static_cast<int>(shared);
610
+ };
611
+ Result best = applyCompiled(*compiled_, values, caretPosition, caretForward, autocomplete, autoSkip);
612
+ int bestScore = score(*compiled_, best, input, values);
613
+ int bestShared = sharedPrefix(best);
614
+ for (size_t i = 0; i < alternatives_.size(); ++i) {
615
+ Result candidate = applyCompiled(*alternatives_[i], values, caretPosition, caretForward, autocomplete, autoSkip);
616
+ const int candidateScore = score(*alternatives_[i], candidate, input, values);
617
+ const int candidateShared = sharedPrefix(candidate);
618
+ if (candidateScore > bestScore || (candidateScore == bestScore && candidateShared > bestShared)) {
619
+ bestScore = candidateScore;
620
+ bestShared = candidateShared;
621
+ best = std::move(candidate);
622
+ best.formatIndex = static_cast<int>(i) + 1;
623
+ }
624
+ }
625
+ return best;
626
+ }
627
+
628
+ std::vector<uint32_t> MaskEngine::prepareInput(const std::vector<uint32_t>& input, int* caret) const {
629
+ if (textCase_ == kTextCaseNone && characterMap_.empty()) return input;
630
+ CodePoints out;
631
+ out.reserve(input.size());
632
+ const int originalCaret = *caret;
633
+ for (size_t i = 0; i < input.size(); ++i) {
634
+ uint32_t c = input[i];
635
+ for (const auto& [from, to] : characterMap_) {
636
+ if (c == from) {
637
+ c = to;
638
+ break;
639
+ }
640
+ }
641
+ if (c == 0) {
642
+ // Dropped: everything after it moves left, the caret with it.
643
+ if (static_cast<int>(i) < originalCaret) *caret -= 1;
644
+ continue;
645
+ }
646
+ if (textCase_ == kTextCaseUpper) c = toUpper(c);
647
+ if (textCase_ == kTextCaseLower) c = toLower(c);
648
+ out.push_back(c);
649
+ }
650
+ return out;
651
+ }
652
+
653
+ /// `text` is the input as typed (case-folded and mapped), `values` the same
654
+ /// with its separators taken out. Prefix and capacity measure what was typed;
655
+ /// value capacity counts what would have to fit, which the result itself
656
+ /// cannot tell - it has already dropped whatever overflowed.
657
+ int MaskEngine::score(const Compiled& compiled, const Result& result, const std::vector<uint32_t>& text,
658
+ const std::vector<uint32_t>& values) const {
659
+ switch (affinityStrategy_) {
660
+ case kAffinityPrefix: {
661
+ const CodePoints formatted = AmountFormatter::decode(result.formattedText);
662
+ size_t shared = 0;
663
+ while (shared < formatted.size() && shared < text.size() && formatted[shared] == text[shared]) shared++;
664
+ return static_cast<int>(shared);
665
+ }
666
+ case kAffinityCapacity: {
667
+ const int length = static_cast<int>(text.size());
668
+ return length > compiled.textCapacity ? INT_MIN : length - compiled.textCapacity;
669
+ }
670
+ case kAffinityExtractedValueCapacity: {
671
+ const int length = static_cast<int>(values.size());
672
+ return length > compiled.valueCapacity ? INT_MIN : length - compiled.valueCapacity;
673
+ }
674
+ default:
675
+ return result.affinity;
676
+ }
677
+ }
448
678
 
679
+ MaskEngine::Result MaskEngine::applyCompiled(const Compiled& compiled, const std::vector<uint32_t>& input,
680
+ int caretPosition, bool caretForward, bool autocomplete,
681
+ bool autoSkip) const {
449
682
  const auto insertionAffectsCaret = [&](size_t at) {
450
- return caretForward ? static_cast<int>(at) < caretPosition : static_cast<int>(at) <= caretPosition;
683
+ // RedMadRobot's gravity: typing (forward) moves the caret past a constant
684
+ // inserted right at it, so "11|" + "1" under "[00]{.}[00]" lands after the
685
+ // dot; deleting (backward) leaves the caret in front of it.
686
+ return caretForward ? static_cast<int>(at) <= caretPosition : static_cast<int>(at) < caretPosition;
451
687
  };
452
688
  const auto deletionAffectsCaret = [&](size_t at) { return static_cast<int>(at) < caretPosition; };
453
689
 
@@ -455,7 +691,7 @@ MaskEngine::Result MaskEngine::apply(const std::string& text, int caret, bool ca
455
691
  CodePoints extracted;
456
692
  int modifiedCaret = caretPosition;
457
693
  int affinity = 0;
458
- const State* state = compiled_->initial;
694
+ const State* state = compiled.initial;
459
695
  std::vector<Step> autocompletionStack;
460
696
 
461
697
  size_t at = 0;
@@ -502,21 +738,9 @@ MaskEngine::Result MaskEngine::apply(const std::string& text, int caret, bool ca
502
738
 
503
739
  // Trailing constants are filled in once the caret has reached the end of the
504
740
  // input - typing "212" into "+1 ([000]) [000]" leaves "+1 (212) " with the
505
- // caret after the space, ready for the next digit.
506
- //
507
- // The engine this is modelled on gates this on `insertionAffectsCaret`, which
508
- // is `index < caret` under forward gravity. The walk only ends when the index
509
- // has reached the end of the input, and the caret can never be past that, so
510
- // that test is always false and its loop is unreachable: constants only turn
511
- // up retroactively, when the next value character arrives. Running both side
512
- // by side on "+1 ([000]) [000]-[0000]":
513
- //
514
- // typed reference here
515
- // 212 "+1 (212" "+1 (212) "
516
- // 212555 "+1 (212) 555" "+1 (212) 555-"
517
- //
518
- // Gate it on the caret instead, which is the behaviour that was always
519
- // described (and their issues #148 and #31).
741
+ // caret after the space, ready for the next digit. That is RedMadRobot's
742
+ // `insertionAffectsCaret` at the end of the input (`index <= caret` under
743
+ // forward gravity), spelled out.
520
744
  const bool caretAtEnd = caretPosition >= static_cast<int>(input.size());
521
745
  while (autocomplete && caretAtEnd) {
522
746
  const std::optional<Step> step = autocompleteOf(state);
@@ -566,7 +790,7 @@ MaskEngine::Result MaskEngine::apply(const std::string& text, int caret, bool ca
566
790
  } else if (s->elliptical) {
567
791
  break;
568
792
  } else {
569
- placeholderTail.push_back(s->placeholderCharacter());
793
+ placeholderTail.push_back(slotPlaceholder_ != 0 ? slotPlaceholder_ : s->placeholderCharacter());
570
794
  }
571
795
  s = s->child;
572
796
  }
@@ -580,7 +804,8 @@ MaskEngine::Result MaskEngine::applyEdit(const std::string& current, int start,
580
804
  const int count = static_cast<int>(text.size());
581
805
  start = std::clamp(start, 0, count);
582
806
  end = std::clamp(end, start, count);
583
- const CodePoints inserted = AmountFormatter::decode(replacement);
807
+ CodePoints inserted = AmountFormatter::decode(replacement);
808
+ if (inserted.size() > 1 && isActive()) inserted = withoutRepeatedPrefix(text, start, end, inserted);
584
809
 
585
810
  CodePoints spliced(text.begin(), text.begin() + start);
586
811
  spliced.insert(spliced.end(), inserted.begin(), inserted.end());
@@ -593,4 +818,40 @@ MaskEngine::Result MaskEngine::applyEdit(const std::string& current, int start,
593
818
  return apply(AmountFormatter::encode(spliced), caret, !deleting, !deleting && autocomplete, deleting && autoSkip);
594
819
  }
595
820
 
821
+ std::vector<uint32_t> MaskEngine::withoutRepeatedPrefix(const std::vector<uint32_t>& text, int start, int end,
822
+ const std::vector<uint32_t>& inserted) const {
823
+ // A paste or autofill that repeats the mask's own leading constants -
824
+ // "+63 912 345 6789" into "+63 [000] [000] [0000]", whose "+63 " the field
825
+ // already shows - would have its "63" taken as the first two digits and its
826
+ // last two cut off. Drop the repeat, but only when the paste lands inside
827
+ // those constants and keeping it would overflow the mask: a value that
828
+ // merely starts with the same digits, and fits, is left alone.
829
+ const auto isValueCharacter = [](uint32_t c) { return isDigit(c) || isLetter(c); };
830
+ const CodePoints& leading = compiled_->leadingConstants;
831
+ if (start > static_cast<int>(leading.size())) return inserted;
832
+
833
+ CodePoints repeated;
834
+ for (uint32_t c : leading) {
835
+ if (isValueCharacter(c)) repeated.push_back(c);
836
+ }
837
+ if (repeated.empty()) return inserted;
838
+
839
+ const auto countValue = [&](auto from, auto to) {
840
+ return static_cast<int>(std::count_if(from, to, isValueCharacter));
841
+ };
842
+ const int incoming = countValue(inserted.begin(), inserted.end()) + countValue(text.begin() + end, text.end());
843
+ if (incoming <= compiled_->valueCapacity) return inserted;
844
+
845
+ size_t matched = 0;
846
+ for (size_t i = 0; i < inserted.size(); ++i) {
847
+ const uint32_t c = inserted[i];
848
+ if (!isValueCharacter(c)) continue; // "+", spaces, brackets
849
+ if (c != repeated[matched]) return inserted;
850
+ if (++matched == repeated.size()) {
851
+ return CodePoints(inserted.begin() + static_cast<long>(i) + 1, inserted.end());
852
+ }
853
+ }
854
+ return inserted;
855
+ }
856
+
596
857
  } // namespace margelo::nitro::nitroinput
@@ -21,6 +21,14 @@
21
21
  // \ escapes the next character
22
22
  // plus any number of caller-supplied `Notation`s.
23
23
  //
24
+ // Around the walk
25
+ // - Input is case-folded and character-mapped first (`setTextCase`,
26
+ // `addCharacterMapping`), so the caret never moves because of it.
27
+ // - Alternative formats (`addAffinityFormat`) are each tried and the one
28
+ // the `AffinityStrategy` scores best wins; the primary wins ties.
29
+ // - A paste that repeats the mask's own leading constants ("+63…" into
30
+ // "+63 [000]…") loses them, when keeping them would overflow the mask.
31
+ //
24
32
  // The algorithm follows RedMadRobot's input-mask (MIT), by way of
25
33
  // react-native-advanced-input-mask. It differs from both in three ways that
26
34
  // matter: it works in code points rather than UTF-16 units (so an astral
@@ -62,8 +70,26 @@ public:
62
70
  bool complete = false;
63
71
  /// How well the input fitted: +1 per accepted character, -1 per rejected.
64
72
  int affinity = 0;
73
+ /// Which format produced this: 0 the primary, 1… the affinity formats in
74
+ /// the order they were added.
75
+ int formatIndex = 0;
65
76
  };
66
77
 
78
+ /// How input letters are cased before masking.
79
+ static constexpr int kTextCaseNone = 0;
80
+ static constexpr int kTextCaseUpper = 1;
81
+ static constexpr int kTextCaseLower = 2;
82
+
83
+ /// How the best of several formats is chosen (RedMadRobot's strategies).
84
+ /// Whole string: accepted minus rejected characters.
85
+ static constexpr int kAffinityWholeString = 0;
86
+ /// Prefix: how many leading characters the input and the result share.
87
+ static constexpr int kAffinityPrefix = 1;
88
+ /// Capacity: fits the formatted text into the format, best the fullest.
89
+ static constexpr int kAffinityCapacity = 2;
90
+ /// Extracted value capacity: the same for the extracted value.
91
+ static constexpr int kAffinityExtractedValueCapacity = 3;
92
+
67
93
  /// Freely copyable: a compiled mask is immutable and shared, so a copy is a
68
94
  /// refcount bump. That also lets Swift and Kotlin hold one as a plain value.
69
95
  MaskEngine();
@@ -90,6 +116,25 @@ public:
90
116
  /// `characterSet` is every character that slot accepts.
91
117
  void addNotation(const std::string& character, const std::string& characterSet, bool isOptional);
92
118
 
119
+ /// Stages alternative formats for the next `setFormat`, compiled with the
120
+ /// same notations. A malformed one is skipped rather than failing the rest.
121
+ void clearAffinityFormats();
122
+ void addAffinityFormat(const std::string& format);
123
+ /// One of the `kAffinity…` constants. Default: whole string.
124
+ void setAffinityStrategy(int strategy);
125
+
126
+ /// One of the `kTextCase…` constants, applied to input before masking.
127
+ void setTextCase(int textCase);
128
+ /// Replaces `from` with `to` in the input before masking, e.g. a Cyrillic
129
+ /// "С" with a Latin "C", or "," with "." for a decimal mask. Each is one
130
+ /// character (its first code point); an empty `to` drops the character.
131
+ void clearCharacterMap();
132
+ void addCharacterMapping(const std::string& from, const std::string& to);
133
+
134
+ /// The character the tail placeholder shows for each empty slot, e.g. "_".
135
+ /// Empty (the default): the slot's own notation character ("0", "a", "-").
136
+ void setSlotPlaceholder(const std::string& character);
137
+
93
138
  /// False until a valid format has been set; `apply` then passes text through.
94
139
  bool isActive() const;
95
140
 
@@ -121,7 +166,24 @@ private:
121
166
  std::vector<std::unique_ptr<State>> arena;
122
167
  const State* initial = nullptr;
123
168
  std::vector<Notation> notations;
169
+ /// Characters the format can hold at most (literals included), and value
170
+ /// characters; `kUnbounded` with an ellipsis.
171
+ int textCapacity = 0;
172
+ int valueCapacity = 0;
173
+ /// The constants before the first slot, e.g. "+63 " for "+63 [000]".
174
+ std::vector<uint32_t> leadingConstants;
124
175
  };
176
+ static constexpr int kUnbounded = 1 << 30;
177
+
178
+ static std::shared_ptr<const Compiled> compileFormat(const std::string& format,
179
+ const std::vector<Notation>& notations);
180
+ Result applyCompiled(const Compiled& compiled, const std::vector<uint32_t>& input, int caret, bool caretForward,
181
+ bool autocomplete, bool autoSkip) const;
182
+ std::vector<uint32_t> prepareInput(const std::vector<uint32_t>& input, int* caret) const;
183
+ int score(const Compiled& compiled, const Result& result, const std::vector<uint32_t>& text,
184
+ const std::vector<uint32_t>& values) const;
185
+ std::vector<uint32_t> withoutRepeatedPrefix(const std::vector<uint32_t>& text, int start, int end,
186
+ const std::vector<uint32_t>& inserted) const;
125
187
 
126
188
  static const State* compile(Compiled& out, const std::vector<uint32_t>& format, size_t index, bool valuable,
127
189
  bool fixed, uint32_t lastCharacter, bool* ok);
@@ -130,7 +192,13 @@ private:
130
192
  const Notation** notation);
131
193
 
132
194
  std::shared_ptr<const Compiled> compiled_;
195
+ std::vector<std::shared_ptr<const Compiled>> alternatives_;
133
196
  std::vector<Notation> staged_;
197
+ std::vector<std::string> stagedAffinityFormats_;
198
+ int affinityStrategy_ = kAffinityWholeString;
199
+ int textCase_ = kTextCaseNone;
200
+ std::vector<std::pair<uint32_t, uint32_t>> characterMap_; // to == 0: drop
201
+ uint32_t slotPlaceholder_ = 0;
134
202
  };
135
203
 
136
204
  } // namespace margelo::nitro::nitroinput