react-native-nitro-input 0.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.
Files changed (187) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/LICENSE +21 -0
  3. package/NitroInput.podspec +54 -0
  4. package/README.md +524 -0
  5. package/android/CMakeLists.txt +52 -0
  6. package/android/build.gradle +158 -0
  7. package/android/fix-prefab.gradle +51 -0
  8. package/android/gradle.properties +4 -0
  9. package/android/src/main/AndroidManifest.xml +2 -0
  10. package/android/src/main/cpp/JAmountFormatter.cpp +70 -0
  11. package/android/src/main/cpp/JAmountFormatter.hpp +45 -0
  12. package/android/src/main/cpp/JMaskEngine.cpp +81 -0
  13. package/android/src/main/cpp/JMaskEngine.hpp +52 -0
  14. package/android/src/main/cpp/JMorphEngine.cpp +132 -0
  15. package/android/src/main/cpp/JMorphEngine.hpp +54 -0
  16. package/android/src/main/cpp/JNitroInputWorklets.cpp +83 -0
  17. package/android/src/main/cpp/JNitroInputWorklets.hpp +40 -0
  18. package/android/src/main/cpp/JOutlineGeometry.cpp +58 -0
  19. package/android/src/main/cpp/JOutlineGeometry.hpp +55 -0
  20. package/android/src/main/cpp/cpp-adapter.cpp +19 -0
  21. package/android/src/main/java/com/margelo/nitro/nitroinput/AmountFormatter.kt +35 -0
  22. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroInputView.kt +730 -0
  23. package/android/src/main/java/com/margelo/nitro/nitroinput/MaskEngine.kt +50 -0
  24. package/android/src/main/java/com/margelo/nitro/nitroinput/MorphEngine.kt +47 -0
  25. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputPackage.kt +24 -0
  26. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputView.kt +2176 -0
  27. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputWorklets.kt +34 -0
  28. package/android/src/main/java/com/margelo/nitro/nitroinput/OutlineGeometry.kt +71 -0
  29. package/cpp/AmountFormatter.cpp +346 -0
  30. package/cpp/AmountFormatter.hpp +88 -0
  31. package/cpp/MaskEngine.cpp +596 -0
  32. package/cpp/MaskEngine.hpp +136 -0
  33. package/cpp/MorphEngine.cpp +904 -0
  34. package/cpp/MorphEngine.hpp +213 -0
  35. package/cpp/OutlineGeometry.cpp +159 -0
  36. package/cpp/OutlineGeometry.hpp +107 -0
  37. package/cpp/worklets/HybridNitroInputWorklets.cpp +30 -0
  38. package/cpp/worklets/HybridNitroInputWorklets.hpp +30 -0
  39. package/cpp/worklets/NitroInputWorkletsBridge.cpp +203 -0
  40. package/cpp/worklets/NitroInputWorkletsBridge.hpp +52 -0
  41. package/cpp/worklets/NitroInputWorkletsBridgeJSI.hpp +23 -0
  42. package/ios/HybridMorphInputView.swift +710 -0
  43. package/ios/NitroInputCommands.mm +66 -0
  44. package/ios/NitroInputView.swift +2600 -0
  45. package/lib/commonjs/nitrogen/generated/shared/json/NitroInputViewConfig.json +101 -0
  46. package/lib/commonjs/src/MorphInput.js +42 -0
  47. package/lib/commonjs/src/NitroInput.js +623 -0
  48. package/lib/commonjs/src/index.js +12 -0
  49. package/lib/commonjs/src/specs/NitroInput.nitro.js +2 -0
  50. package/lib/commonjs/src/specs/NitroInputWorklets.nitro.js +2 -0
  51. package/lib/commonjs/src/useNitroInputState.js +58 -0
  52. package/lib/commonjs/src/worklets.js +226 -0
  53. package/lib/module/nitrogen/generated/shared/json/NitroInputViewConfig.json +101 -0
  54. package/lib/module/package.json +1 -0
  55. package/lib/module/src/MorphInput.js +6 -0
  56. package/lib/module/src/NitroInput.js +584 -0
  57. package/lib/module/src/index.js +4 -0
  58. package/lib/module/src/specs/NitroInput.nitro.js +1 -0
  59. package/lib/module/src/specs/NitroInputWorklets.nitro.js +1 -0
  60. package/lib/module/src/useNitroInputState.js +55 -0
  61. package/lib/module/src/worklets.js +214 -0
  62. package/lib/typescript/src/MorphInput.d.ts +18 -0
  63. package/lib/typescript/src/NitroInput.d.ts +411 -0
  64. package/lib/typescript/src/index.d.ts +6 -0
  65. package/lib/typescript/src/specs/NitroInput.nitro.d.ts +390 -0
  66. package/lib/typescript/src/specs/NitroInputWorklets.nitro.d.ts +15 -0
  67. package/lib/typescript/src/useNitroInputState.d.ts +55 -0
  68. package/lib/typescript/src/worklets.d.ts +117 -0
  69. package/nitro.json +37 -0
  70. package/nitrogen/generated/.gitattributes +1 -0
  71. package/nitrogen/generated/android/NitroInput+autolinking.cmake +84 -0
  72. package/nitrogen/generated/android/NitroInput+autolinking.gradle +27 -0
  73. package/nitrogen/generated/android/NitroInputOnLoad.cpp +78 -0
  74. package/nitrogen/generated/android/NitroInputOnLoad.hpp +34 -0
  75. package/nitrogen/generated/android/c++/JFunc_void_bool.hpp +75 -0
  76. package/nitrogen/generated/android/c++/JFunc_void_double.hpp +75 -0
  77. package/nitrogen/generated/android/c++/JFunc_void_double_double.hpp +75 -0
  78. package/nitrogen/generated/android/c++/JFunc_void_std__string.hpp +76 -0
  79. package/nitrogen/generated/android/c++/JFunc_void_std__string_double.hpp +76 -0
  80. package/nitrogen/generated/android/c++/JFunc_void_std__string_std__string_std__string_bool.hpp +76 -0
  81. package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.cpp +1073 -0
  82. package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.hpp +254 -0
  83. package/nitrogen/generated/android/c++/JNitroInputAffixAlign.hpp +64 -0
  84. package/nitrogen/generated/android/c++/JNitroInputAutoCapitalize.hpp +64 -0
  85. package/nitrogen/generated/android/c++/JNitroInputEasing.hpp +67 -0
  86. package/nitrogen/generated/android/c++/JNitroInputEffect.hpp +61 -0
  87. package/nitrogen/generated/android/c++/JNitroInputKeyboardAppearance.hpp +61 -0
  88. package/nitrogen/generated/android/c++/JNitroInputKeyboardType.hpp +79 -0
  89. package/nitrogen/generated/android/c++/JNitroInputLabelBehavior.hpp +58 -0
  90. package/nitrogen/generated/android/c++/JNitroInputMode.hpp +61 -0
  91. package/nitrogen/generated/android/c++/JNitroInputNotation.hpp +65 -0
  92. package/nitrogen/generated/android/c++/JNitroInputReturnKeyType.hpp +70 -0
  93. package/nitrogen/generated/android/c++/JNitroInputSignPlacement.hpp +58 -0
  94. package/nitrogen/generated/android/c++/JNitroInputSubmitBehavior.hpp +61 -0
  95. package/nitrogen/generated/android/c++/JNitroInputTextAlign.hpp +64 -0
  96. package/nitrogen/generated/android/c++/JNitroInputTextAlignVertical.hpp +64 -0
  97. package/nitrogen/generated/android/c++/JNitroInputVariant.hpp +61 -0
  98. package/nitrogen/generated/android/c++/views/JHybridNitroInputViewStateUpdater.cpp +529 -0
  99. package/nitrogen/generated/android/c++/views/JHybridNitroInputViewStateUpdater.hpp +54 -0
  100. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/Func_void_bool.kt +78 -0
  101. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/Func_void_double.kt +78 -0
  102. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/Func_void_double_double.kt +78 -0
  103. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/Func_void_std__string.kt +78 -0
  104. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/Func_void_std__string_double.kt +78 -0
  105. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/Func_void_std__string_std__string_std__string_bool.kt +78 -0
  106. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroInputViewSpec.kt +711 -0
  107. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputAffixAlign.kt +25 -0
  108. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputAutoCapitalize.kt +25 -0
  109. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputEasing.kt +26 -0
  110. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputEffect.kt +24 -0
  111. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputKeyboardAppearance.kt +24 -0
  112. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputKeyboardType.kt +30 -0
  113. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputLabelBehavior.kt +23 -0
  114. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputMode.kt +24 -0
  115. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputNotation.kt +61 -0
  116. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputOnLoad.kt +35 -0
  117. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputReturnKeyType.kt +27 -0
  118. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputSignPlacement.kt +23 -0
  119. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputSubmitBehavior.kt +24 -0
  120. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputTextAlign.kt +25 -0
  121. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputTextAlignVertical.kt +25 -0
  122. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputVariant.kt +24 -0
  123. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/views/HybridNitroInputViewManager.kt +96 -0
  124. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/views/HybridNitroInputViewStateUpdater.kt +23 -0
  125. package/nitrogen/generated/ios/NitroInput+autolinking.rb +62 -0
  126. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Bridge.cpp +81 -0
  127. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Bridge.hpp +348 -0
  128. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Umbrella.hpp +92 -0
  129. package/nitrogen/generated/ios/NitroInputAutolinking.mm +43 -0
  130. package/nitrogen/generated/ios/NitroInputAutolinking.swift +26 -0
  131. package/nitrogen/generated/ios/c++/HybridNitroInputViewSpecSwift.cpp +11 -0
  132. package/nitrogen/generated/ios/c++/HybridNitroInputViewSpecSwift.hpp +769 -0
  133. package/nitrogen/generated/ios/c++/views/HybridNitroInputViewComponent.mm +690 -0
  134. package/nitrogen/generated/ios/swift/Func_void_bool.swift +46 -0
  135. package/nitrogen/generated/ios/swift/Func_void_double.swift +46 -0
  136. package/nitrogen/generated/ios/swift/Func_void_double_double.swift +46 -0
  137. package/nitrogen/generated/ios/swift/Func_void_std__string.swift +46 -0
  138. package/nitrogen/generated/ios/swift/Func_void_std__string_double.swift +46 -0
  139. package/nitrogen/generated/ios/swift/Func_void_std__string_std__string_std__string_bool.swift +46 -0
  140. package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec.swift +154 -0
  141. package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec_cxx.swift +1454 -0
  142. package/nitrogen/generated/ios/swift/NitroInputAffixAlign.swift +48 -0
  143. package/nitrogen/generated/ios/swift/NitroInputAutoCapitalize.swift +48 -0
  144. package/nitrogen/generated/ios/swift/NitroInputEasing.swift +52 -0
  145. package/nitrogen/generated/ios/swift/NitroInputEffect.swift +44 -0
  146. package/nitrogen/generated/ios/swift/NitroInputKeyboardAppearance.swift +44 -0
  147. package/nitrogen/generated/ios/swift/NitroInputKeyboardType.swift +68 -0
  148. package/nitrogen/generated/ios/swift/NitroInputLabelBehavior.swift +40 -0
  149. package/nitrogen/generated/ios/swift/NitroInputMode.swift +44 -0
  150. package/nitrogen/generated/ios/swift/NitroInputNotation.swift +39 -0
  151. package/nitrogen/generated/ios/swift/NitroInputReturnKeyType.swift +56 -0
  152. package/nitrogen/generated/ios/swift/NitroInputSignPlacement.swift +40 -0
  153. package/nitrogen/generated/ios/swift/NitroInputSubmitBehavior.swift +44 -0
  154. package/nitrogen/generated/ios/swift/NitroInputTextAlign.swift +48 -0
  155. package/nitrogen/generated/ios/swift/NitroInputTextAlignVertical.swift +48 -0
  156. package/nitrogen/generated/ios/swift/NitroInputVariant.swift +44 -0
  157. package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.cpp +213 -0
  158. package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.hpp +300 -0
  159. package/nitrogen/generated/shared/c++/HybridNitroInputWorkletsSpec.cpp +21 -0
  160. package/nitrogen/generated/shared/c++/HybridNitroInputWorkletsSpec.hpp +62 -0
  161. package/nitrogen/generated/shared/c++/NitroInputAffixAlign.hpp +84 -0
  162. package/nitrogen/generated/shared/c++/NitroInputAutoCapitalize.hpp +84 -0
  163. package/nitrogen/generated/shared/c++/NitroInputEasing.hpp +88 -0
  164. package/nitrogen/generated/shared/c++/NitroInputEffect.hpp +80 -0
  165. package/nitrogen/generated/shared/c++/NitroInputKeyboardAppearance.hpp +80 -0
  166. package/nitrogen/generated/shared/c++/NitroInputKeyboardType.hpp +104 -0
  167. package/nitrogen/generated/shared/c++/NitroInputLabelBehavior.hpp +76 -0
  168. package/nitrogen/generated/shared/c++/NitroInputMode.hpp +80 -0
  169. package/nitrogen/generated/shared/c++/NitroInputNotation.hpp +91 -0
  170. package/nitrogen/generated/shared/c++/NitroInputReturnKeyType.hpp +92 -0
  171. package/nitrogen/generated/shared/c++/NitroInputSignPlacement.hpp +76 -0
  172. package/nitrogen/generated/shared/c++/NitroInputSubmitBehavior.hpp +80 -0
  173. package/nitrogen/generated/shared/c++/NitroInputTextAlign.hpp +84 -0
  174. package/nitrogen/generated/shared/c++/NitroInputTextAlignVertical.hpp +84 -0
  175. package/nitrogen/generated/shared/c++/NitroInputVariant.hpp +80 -0
  176. package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.cpp +216 -0
  177. package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.hpp +374 -0
  178. package/nitrogen/generated/shared/json/NitroInputViewConfig.json +101 -0
  179. package/package.json +141 -0
  180. package/react-native.config.js +16 -0
  181. package/src/MorphInput.tsx +30 -0
  182. package/src/NitroInput.tsx +1364 -0
  183. package/src/index.ts +55 -0
  184. package/src/specs/NitroInput.nitro.ts +436 -0
  185. package/src/specs/NitroInputWorklets.nitro.ts +13 -0
  186. package/src/useNitroInputState.ts +101 -0
  187. package/src/worklets.ts +300 -0
@@ -0,0 +1,904 @@
1
+ //
2
+ // MorphEngine.cpp
3
+ // NitroInput
4
+ //
5
+
6
+ #include "MorphEngine.hpp"
7
+
8
+ #include <algorithm>
9
+ #include <cmath>
10
+ #include <utility>
11
+
12
+ namespace margelo::nitro::nitroinput {
13
+
14
+ namespace {
15
+
16
+ constexpr double kPi = 3.14159265358979323846;
17
+ /// Text glyphs scale to/from this while fading (Torph's `scale` option).
18
+ constexpr double kFadeScale = 0.95;
19
+ /// Opacity ramps, as fractions of the duration (Torph's shares).
20
+ constexpr double kTextEnterFadeFrom = 0.25;
21
+ constexpr double kTextEnterFadeTo = 0.75;
22
+ constexpr double kTextExitFadeTo = 0.25;
23
+ constexpr double kSlideEnterFadeTo = 0.25;
24
+ /// Larger: a digit that has already left is a hole in the number.
25
+ constexpr double kSlideExitFadeTo = 0.45;
26
+ /// A glyph interrupted on its way in regains full opacity within this share.
27
+ constexpr double kPersistFadeTo = 0.25;
28
+ /// Where characters moving becomes one thing swapped for another (Torph's
29
+ /// `GROUP_MIN`). A run this long with no survivor inside it has nothing near
30
+ /// enough to animate from, and sliding each glyph only smears it.
31
+ constexpr int kGroupMin = 6;
32
+ /// Deeper than a character's 0.95, so the run reads as receding, not settling.
33
+ constexpr double kGroupScale = 0.8;
34
+ constexpr double kGroupExitFadeTo = 0.45;
35
+ constexpr double kGroupEnterFadeTo = 0.35;
36
+
37
+ double clamp01(double v) {
38
+ return v < 0 ? 0 : (v > 1 ? 1 : v);
39
+ }
40
+
41
+ /// y of the cubic Bézier (x1, y1, x2, y2) at x, like CSS `cubic-bezier`.
42
+ double cubicBezier(double x1, double y1, double x2, double y2, double x) {
43
+ if (x <= 0) return 0;
44
+ if (x >= 1) return 1;
45
+ const auto sampleX = [&](double t) { return ((1 - 3 * x2 + 3 * x1) * t + (3 * x2 - 6 * x1)) * t * t + 3 * x1 * t; };
46
+ const auto sampleY = [&](double t) { return ((1 - 3 * y2 + 3 * y1) * t + (3 * y2 - 6 * y1)) * t * t + 3 * y1 * t; };
47
+ const auto slopeX = [&](double t) { return 3 * (1 - 3 * x2 + 3 * x1) * t * t + 2 * (3 * x2 - 6 * x1) * t + 3 * x1; };
48
+ double t = x;
49
+ for (int i = 0; i < 8; ++i) {
50
+ const double err = sampleX(t) - x;
51
+ if (std::fabs(err) < 1e-7) return sampleY(t);
52
+ const double slope = slopeX(t);
53
+ if (std::fabs(slope) < 1e-6) break;
54
+ t -= err / slope;
55
+ }
56
+ double lo = 0, hi = 1;
57
+ t = x;
58
+ while (hi - lo > 1e-7) {
59
+ if (sampleX(t) < x) lo = t; else hi = t;
60
+ t = (lo + hi) / 2;
61
+ }
62
+ return sampleY(t);
63
+ }
64
+
65
+ /// Step response of a damped spring, normalised so it has settled at t == 1
66
+ /// (the same curve as the rolling number's `spring` easing).
67
+ double spring(double t, double bounce) {
68
+ const double zeta = std::min(1.0, std::max(0.05, 1.0 - clamp01(bounce)));
69
+ const double omega = 3.0 * kPi;
70
+ const double k = zeta * omega;
71
+ if (zeta >= 0.999) {
72
+ return 1 - (1 + k * t) * std::exp(-k * t);
73
+ }
74
+ const double wd = omega * std::sqrt(1 - zeta * zeta);
75
+ return 1 - std::exp(-k * t) * (std::cos(wd * t) + (k / wd) * std::sin(wd * t));
76
+ }
77
+
78
+ /// Longest common subsequence as index pairs, walked forwards so ties go to
79
+ /// the earliest match (backwards, a repeated character flies across the text).
80
+ template <class Equal>
81
+ void lcsPairs(int m, int n, Equal equal, std::vector<std::pair<int, int>>& out) {
82
+ if (m == 0 || n == 0) return;
83
+ std::vector<int> dp(static_cast<size_t>((m + 1) * (n + 1)), 0);
84
+ const auto at = [&](int i, int j) -> int& { return dp[static_cast<size_t>(i * (n + 1) + j)]; };
85
+ for (int i = m - 1; i >= 0; --i) {
86
+ for (int j = n - 1; j >= 0; --j) {
87
+ at(i, j) = equal(i, j) ? at(i + 1, j + 1) + 1 : std::max(at(i + 1, j), at(i, j + 1));
88
+ }
89
+ }
90
+ int i = 0, j = 0;
91
+ while (i < m && j < n) {
92
+ if (equal(i, j)) {
93
+ out.emplace_back(i, j);
94
+ ++i;
95
+ ++j;
96
+ } else if (at(i + 1, j) >= at(i, j + 1)) {
97
+ ++i;
98
+ } else {
99
+ ++j;
100
+ }
101
+ }
102
+ }
103
+
104
+ double ramp(double p, double from, double to) {
105
+ if (to <= from) return p >= to ? 1 : 0;
106
+ return clamp01((p - from) / (to - from));
107
+ }
108
+
109
+ } // namespace
110
+
111
+ MorphEngine::MorphEngine() = default;
112
+
113
+ // MARK: - Configuration
114
+
115
+ void MorphEngine::setTiming(double durationSeconds, int easing, double bounce) {
116
+ duration_ = std::max(0.0, durationSeconds);
117
+ easing_ = easing;
118
+ bounce_ = bounce;
119
+ }
120
+
121
+ void MorphEngine::setEffect(int effect) {
122
+ effect_ = effect;
123
+ }
124
+
125
+ void MorphEngine::setReduceMotion(bool reduceMotion) {
126
+ reduceMotion_ = reduceMotion;
127
+ }
128
+
129
+ double MorphEngine::ease(double t) const {
130
+ t = clamp01(t);
131
+ switch (easing_) {
132
+ case 1: return 1 - std::pow(1 - t, 3);
133
+ case 2: return t < 0.5 ? 4 * t * t * t : 1 - std::pow(-2 * t + 2, 3) / 2;
134
+ case 3: return t;
135
+ case 4: return spring(t, bounce_);
136
+ default: return cubicBezier(0.19, 1, 0.22, 1, t);
137
+ }
138
+ }
139
+
140
+ bool MorphEngine::slides(int kind) const {
141
+ if (effect_ == 1) return true;
142
+ if (effect_ == 2) return false;
143
+ return kind != Text;
144
+ }
145
+
146
+ bool MorphEngine::same(const Input& in, const Slot& slot) const {
147
+ return in.character == slot.g.character && in.kind == slot.g.kind && in.role == slot.g.role &&
148
+ in.placeholder == slot.g.placeholder;
149
+ }
150
+
151
+ int MorphEngine::slotIndexOf(int64_t id) const {
152
+ for (size_t i = 0; i < slots_.size(); ++i) {
153
+ if (slots_[i].g.id == id) return static_cast<int>(i);
154
+ }
155
+ return -1;
156
+ }
157
+
158
+ // MARK: - Text
159
+
160
+ void MorphEngine::beginText() {
161
+ pending_.clear();
162
+ }
163
+
164
+ void MorphEngine::addGlyph(uint32_t character, int role, int kind, double width, bool placeholder) {
165
+ pending_.push_back(Input{character, role, kind, std::max(0.0, width), placeholder});
166
+ }
167
+
168
+ void MorphEngine::snapTo(const std::vector<Input>& inputs) {
169
+ slots_.clear();
170
+ slots_.reserve(inputs.size());
171
+ double x = 0;
172
+ for (const auto& in : inputs) {
173
+ Slot s;
174
+ s.g = Glyph{nextId_++, in.character, in.role, in.kind, in.width, in.placeholder, x, 0, 1, 1, false};
175
+ s.fromX = s.toX = x;
176
+ s.slide = slides(in.kind) && !in.placeholder;
177
+ slots_.push_back(s);
178
+ x += in.width;
179
+ }
180
+ contentWidth_ = targetWidth_ = widthFrom_ = x;
181
+ animating_ = false;
182
+ publish();
183
+ }
184
+
185
+ /// Text mode hands every character in as `Text`. A body that is a number in
186
+ /// disguise (a phone number, a date, an amount typed into a plain field: digits
187
+ /// and punctuation, no letters) gets the number treatment instead, so its
188
+ /// digits slide and its separators reflow like a formatted amount's.
189
+ static void classifyNumericBody(std::vector<MorphEngine::Input>& inputs) {
190
+ bool digits = false;
191
+ for (const auto& in : inputs) {
192
+ if (in.role != MorphEngine::Body) continue;
193
+ if (in.kind != MorphEngine::Text) return; // already classified (number mode)
194
+ const uint32_t c = in.character;
195
+ if (c >= '0' && c <= '9') {
196
+ digits = true;
197
+ } else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c > 0x7f) {
198
+ return; // real text
199
+ }
200
+ }
201
+ if (!digits) return;
202
+ for (auto& in : inputs) {
203
+ if (in.role != MorphEngine::Body) continue;
204
+ const uint32_t c = in.character;
205
+ in.kind = (c >= '0' && c <= '9') ? MorphEngine::Digit : MorphEngine::Separator;
206
+ }
207
+ // A lone '.' or ',' is the decimal point: the pivot the digits pair around,
208
+ // part of the typed sequence like them, not a grouping separator that
209
+ // reflows with the magnitude. As a separator it was re-paired from the
210
+ // units end and, since the integer count then included the fraction
211
+ // digits, every keystroke after it read as a reshape: the point left
212
+ // downwards and rose again in the very same place. The last such character
213
+ // is the candidate ("1,234.56" keeps its comma as grouping), and only when
214
+ // it occurs once: "192.168.0.1" and "21.09.2026" are structure.
215
+ int decimal = -1;
216
+ for (size_t i = 0; i < inputs.size(); ++i) {
217
+ if (inputs[i].role != MorphEngine::Body) continue;
218
+ if (inputs[i].character == '.' || inputs[i].character == ',') decimal = static_cast<int>(i);
219
+ }
220
+ if (decimal < 0) return;
221
+ int occurrences = 0;
222
+ for (const auto& in : inputs) {
223
+ if (in.role == MorphEngine::Body && in.character == inputs[static_cast<size_t>(decimal)].character) ++occurrences;
224
+ }
225
+ if (occurrences == 1) inputs[static_cast<size_t>(decimal)].kind = MorphEngine::Decimal;
226
+ }
227
+
228
+ void MorphEngine::commitText(int caretIndex, double now) {
229
+ now_ = now;
230
+ std::vector<Input> inputs;
231
+ inputs.swap(pending_);
232
+ classifyNumericBody(inputs);
233
+
234
+ // A placeholder is not a value: it is what the field shows instead of one.
235
+ // Replacing it is a change of state rather than a morph, so the zero standing
236
+ // in for an empty field does not roll into the digit that lands on it.
237
+ const bool fromPlaceholder =
238
+ std::any_of(slots_.begin(), slots_.end(), [](const Slot& s) { return !s.g.exiting && s.g.placeholder; });
239
+ if (!committed_ || duration_ <= 0 || reduceMotion_ || fromPlaceholder) {
240
+ snapTo(inputs);
241
+ committed_ = true;
242
+ return;
243
+ }
244
+
245
+ // Live (non-exiting) old glyphs and new glyphs, by role.
246
+ std::vector<int> oldByRole[3], newByRole[3];
247
+ for (size_t i = 0; i < slots_.size(); ++i) {
248
+ if (!slots_[i].g.exiting) oldByRole[std::clamp(slots_[i].g.role, 0, 2)].push_back(static_cast<int>(i));
249
+ }
250
+ for (size_t i = 0; i < inputs.size(); ++i) {
251
+ newByRole[std::clamp(inputs[i].role, 0, 2)].push_back(static_cast<int>(i));
252
+ }
253
+
254
+ // matchOfNew[new index] = old slot index, or -1.
255
+ std::vector<int> matchOfNew(inputs.size(), -1);
256
+ matchBySequence(inputs, oldByRole[Prefix], newByRole[Prefix], matchOfNew);
257
+ matchBody(inputs, oldByRole[Body], newByRole[Body], caretIndex, matchOfNew);
258
+ matchBySequence(inputs, oldByRole[Suffix], newByRole[Suffix], matchOfNew);
259
+
260
+ std::vector<bool> used(slots_.size(), false);
261
+ for (int m : matchOfNew) {
262
+ if (m >= 0) used[static_cast<size_t>(m)] = true;
263
+ }
264
+
265
+ // Targets of the new layout.
266
+ std::vector<double> targetX(inputs.size(), 0);
267
+ double x = 0;
268
+ for (size_t i = 0; i < inputs.size(); ++i) {
269
+ targetX[i] = x;
270
+ x += inputs[i].width;
271
+ }
272
+
273
+ // Nearest persisting neighbour in the new order (backward first), for entering glyphs.
274
+ const auto anchorForNew = [&](size_t index) -> int {
275
+ for (size_t j = index; j-- > 0;) {
276
+ if (matchOfNew[j] >= 0) return matchOfNew[j];
277
+ }
278
+ for (size_t j = index + 1; j < inputs.size(); ++j) {
279
+ if (matchOfNew[j] >= 0) return matchOfNew[j];
280
+ }
281
+ return -1;
282
+ };
283
+ // Nearest persisting neighbour in the old order (forward first), for exiting glyphs.
284
+ std::vector<int> oldLive;
285
+ for (size_t i = 0; i < slots_.size(); ++i) {
286
+ if (!slots_[i].g.exiting) oldLive.push_back(static_cast<int>(i));
287
+ }
288
+ const auto anchorForOld = [&](int slotIndex) -> int {
289
+ size_t pos = 0;
290
+ while (pos < oldLive.size() && oldLive[pos] != slotIndex) ++pos;
291
+ for (size_t j = pos + 1; j < oldLive.size(); ++j) {
292
+ if (used[static_cast<size_t>(oldLive[j])]) return oldLive[j];
293
+ }
294
+ for (size_t j = pos; j-- > 0;) {
295
+ if (used[static_cast<size_t>(oldLive[j])]) return oldLive[j];
296
+ }
297
+ return -1;
298
+ };
299
+
300
+ // A run of adjacent glyphs that are wholly replaced — no survivor inside it —
301
+ // recedes as one shape instead of each glyph sliding a line box on its own. A
302
+ // survivor breaks the run: it is right there to animate against.
303
+ const auto closeRun = [&](const auto& extent) {
304
+ if (runBuf_.size() >= static_cast<size_t>(kGroupMin)) {
305
+ double lo = 0, hi = 0;
306
+ for (size_t k = 0; k < runBuf_.size(); ++k) {
307
+ const auto [left, right] = extent(runBuf_[k]);
308
+ if (k == 0) { lo = left; hi = right; }
309
+ else { lo = std::min(lo, left); hi = std::max(hi, right); }
310
+ }
311
+ const double mid = (lo + hi) / 2;
312
+ for (size_t i : runBuf_) { groupFlag_[i] = 1; groupCentre_[i] = mid; }
313
+ }
314
+ runBuf_.clear();
315
+ };
316
+
317
+ // Old glyphs still on stage, in order; a run is measured where they sit now.
318
+ // One already leaving is not on stage at all, so it neither joins nor breaks.
319
+ groupFlag_.assign(slots_.size(), 0);
320
+ groupCentre_.assign(slots_.size(), 0.0);
321
+ runBuf_.clear();
322
+ const auto oldExtent = [&](size_t i) {
323
+ return std::pair<double, double>{slots_[i].g.x, slots_[i].g.x + slots_[i].g.width};
324
+ };
325
+ for (size_t i = 0; i < slots_.size(); ++i) {
326
+ if (slots_[i].g.exiting) continue;
327
+ if (used[i]) { closeRun(oldExtent); continue; }
328
+ runBuf_.push_back(i);
329
+ }
330
+ closeRun(oldExtent);
331
+
332
+ std::vector<Slot> next;
333
+ next.reserve(slots_.size() + inputs.size());
334
+
335
+ // Old glyphs that leave, and those already leaving, are drawn underneath the text.
336
+ for (size_t i = 0; i < slots_.size(); ++i) {
337
+ Slot s = slots_[i];
338
+ if (s.g.exiting) {
339
+ // Its anchor may be leaving now too: freeze where it is.
340
+ if (s.anchorId >= 0) {
341
+ const int a = slotIndexOf(s.anchorId);
342
+ if (a < 0 || !used[static_cast<size_t>(a)]) {
343
+ s.anchorId = -1;
344
+ s.fromX = s.g.x;
345
+ }
346
+ }
347
+ next.push_back(s);
348
+ continue;
349
+ }
350
+ if (used[i]) continue;
351
+ s.g.exiting = true;
352
+ s.entering = false;
353
+ s.start = now;
354
+ s.fromX = s.toX = s.g.x;
355
+ s.fromY = s.g.y;
356
+ // Everything leaves downwards (Torph): digits pass through the line box like
357
+ // an odometer, separators drop back to where they came in from.
358
+ s.toY = s.slide ? 1 : 0;
359
+ s.fromOpacity = s.g.opacity;
360
+ s.toOpacity = 0;
361
+ s.fadeFrom = 0;
362
+ s.fadeTo = s.slide ? kSlideExitFadeTo : kTextExitFadeTo;
363
+ s.fromScale = s.g.scale;
364
+ s.toScale = s.slide ? 1 : kFadeScale;
365
+ if (groupFlag_[i]) {
366
+ // The whole run recedes into itself: no slide, no anchor to ride.
367
+ s.grouped = true;
368
+ s.groupCentre = groupCentre_[i];
369
+ s.toY = s.fromY;
370
+ s.fromScale = s.g.scale;
371
+ s.toScale = kGroupScale;
372
+ s.fadeTo = kGroupExitFadeTo;
373
+ s.anchorId = -1;
374
+ next.push_back(s);
375
+ continue;
376
+ }
377
+ const int a = anchorForOld(static_cast<int>(i));
378
+ s.anchorId = a >= 0 ? slots_[static_cast<size_t>(a)].g.id : -1;
379
+ s.anchorBaseX = a >= 0 ? slots_[static_cast<size_t>(a)].g.x : 0;
380
+ next.push_back(s);
381
+ }
382
+
383
+ // Arriving glyphs, measured where the new layout puts them. The exit pass is
384
+ // done with the buffers by now, so they are reused rather than grown again.
385
+ groupFlag_.assign(inputs.size(), 0);
386
+ groupCentre_.assign(inputs.size(), 0.0);
387
+ runBuf_.clear();
388
+ const auto newExtent = [&](size_t i) {
389
+ return std::pair<double, double>{targetX[i], targetX[i] + inputs[i].width};
390
+ };
391
+ for (size_t i = 0; i < inputs.size(); ++i) {
392
+ if (matchOfNew[i] >= 0) { closeRun(newExtent); continue; }
393
+ runBuf_.push_back(i);
394
+ }
395
+ closeRun(newExtent);
396
+
397
+ for (size_t i = 0; i < inputs.size(); ++i) {
398
+ const Input& in = inputs[i];
399
+ const int m = matchOfNew[i];
400
+ if (m >= 0) {
401
+ Slot s = slots_[static_cast<size_t>(m)];
402
+ s.g.width = in.width;
403
+ s.entering = false;
404
+ s.slide = slides(in.kind) && !in.placeholder;
405
+ s.start = now;
406
+ s.fromX = s.g.x;
407
+ s.toX = targetX[i];
408
+ s.fromY = s.g.y;
409
+ s.toY = 0;
410
+ s.fromOpacity = s.g.opacity;
411
+ s.toOpacity = 1;
412
+ s.fadeFrom = 0;
413
+ s.fadeTo = kPersistFadeTo;
414
+ s.fromScale = s.g.scale;
415
+ s.toScale = 1;
416
+ s.anchorId = -1;
417
+ next.push_back(s);
418
+ } else {
419
+ Slot s;
420
+ const bool slide = slides(in.kind) && !in.placeholder;
421
+ s.slide = slide;
422
+ s.entering = true;
423
+ s.start = now;
424
+ s.fromX = s.toX = targetX[i];
425
+ s.fromY = slide ? ((in.kind == Separator || in.kind == Decimal) ? 1 : -1) : 0;
426
+ s.toY = 0;
427
+ s.fromOpacity = 0;
428
+ s.toOpacity = 1;
429
+ s.fadeFrom = slide ? 0 : kTextEnterFadeFrom;
430
+ s.fadeTo = slide ? kSlideEnterFadeTo : kTextEnterFadeTo;
431
+ s.fromScale = slide ? 1 : kFadeScale;
432
+ s.toScale = 1;
433
+ if (groupFlag_[i]) {
434
+ // The same gesture in reverse: the run comes forward out of its centre.
435
+ // Nothing to ride — the run is the whole event.
436
+ s.grouped = true;
437
+ s.groupCentre = groupCentre_[i];
438
+ s.fromY = s.toY = 0;
439
+ s.fromScale = kGroupScale;
440
+ s.fadeTo = kGroupEnterFadeTo;
441
+ } else {
442
+ const int a = anchorForNew(i);
443
+ s.anchorId = a >= 0 ? slots_[static_cast<size_t>(a)].g.id : -1;
444
+ // Rides along with the anchor's remaining travel: x = target + (anchor.x - anchor.target).
445
+ s.anchorBaseX = 0;
446
+ if (a >= 0) {
447
+ for (size_t j = 0; j < inputs.size(); ++j) {
448
+ if (matchOfNew[j] == a) {
449
+ s.anchorBaseX = targetX[j];
450
+ break;
451
+ }
452
+ }
453
+ }
454
+ }
455
+ s.g = Glyph{nextId_++, in.character, in.role, in.kind, in.width, in.placeholder,
456
+ s.fromX, s.fromY, 0, s.fromScale, false};
457
+ next.push_back(s);
458
+ }
459
+ }
460
+
461
+ slots_.swap(next);
462
+ widthFrom_ = contentWidth_;
463
+ targetWidth_ = x;
464
+ widthStart_ = now;
465
+ animating_ = true;
466
+ tick(now);
467
+ }
468
+
469
+ // MARK: - Matching
470
+
471
+ void MorphEngine::matchBySequence(const std::vector<Input>& inputs, const std::vector<int>& oldIdx,
472
+ const std::vector<int>& newIdx, std::vector<int>& matchOfNew) const {
473
+ std::vector<std::pair<int, int>> pairs;
474
+ lcsPairs(static_cast<int>(oldIdx.size()), static_cast<int>(newIdx.size()),
475
+ [&](int i, int j) { return same(inputs[static_cast<size_t>(newIdx[static_cast<size_t>(j)])], slots_[static_cast<size_t>(oldIdx[static_cast<size_t>(i)])]); },
476
+ pairs);
477
+ for (const auto& [i, j] : pairs) {
478
+ matchOfNew[static_cast<size_t>(newIdx[static_cast<size_t>(j)])] = oldIdx[static_cast<size_t>(i)];
479
+ }
480
+ }
481
+
482
+ void MorphEngine::matchBody(const std::vector<Input>& inputs, const std::vector<int>& oldBody,
483
+ const std::vector<int>& newBody, int caretIndex, std::vector<int>& matchOfNew) const {
484
+ if (caretIndex >= 0) {
485
+ matchByCaret(inputs, oldBody, newBody, caretIndex, matchOfNew);
486
+ return;
487
+ }
488
+ bool hasDigits = false;
489
+ for (int i : oldBody) hasDigits = hasDigits || slots_[static_cast<size_t>(i)].g.kind == Digit;
490
+ for (int i : newBody) hasDigits = hasDigits || inputs[static_cast<size_t>(i)].kind == Digit;
491
+ if (hasDigits) {
492
+ matchByPlace(inputs, oldBody, newBody, matchOfNew);
493
+ } else {
494
+ matchBySequence(inputs, oldBody, newBody, matchOfNew);
495
+ }
496
+ }
497
+
498
+ /// The caret in the new text says where the edit was; both sides of it map
499
+ /// across by position. Grouping separators are left out of that walk (they
500
+ /// reflow with the magnitude, not with the keystroke) and pair from the units
501
+ /// end instead, so the thousands comma stays the thousands comma.
502
+ void MorphEngine::matchByCaret(const std::vector<Input>& inputs, const std::vector<int>& oldBody,
503
+ const std::vector<int>& newBody, int caretIndex, std::vector<int>& matchOfNew) const {
504
+ std::vector<int> keptOld, keptNew, sepOld, sepNew; // positions within the body lists
505
+ for (size_t p = 0; p < oldBody.size(); ++p) {
506
+ (slots_[static_cast<size_t>(oldBody[p])].g.kind == Separator ? sepOld : keptOld).push_back(static_cast<int>(p));
507
+ }
508
+ for (size_t p = 0; p < newBody.size(); ++p) {
509
+ (inputs[static_cast<size_t>(newBody[p])].kind == Separator ? sepNew : keptNew).push_back(static_cast<int>(p));
510
+ }
511
+ const auto pairPositions = [&](int newPos, int oldPos) {
512
+ const int ni = newBody[static_cast<size_t>(newPos)];
513
+ const int oi = oldBody[static_cast<size_t>(oldPos)];
514
+ if (same(inputs[static_cast<size_t>(ni)], slots_[static_cast<size_t>(oi)])) matchOfNew[static_cast<size_t>(ni)] = oi;
515
+ };
516
+ const auto pairKept = [&](int i, int o) {
517
+ if (i < 0 || o < 0 || i >= static_cast<int>(keptNew.size()) || o >= static_cast<int>(keptOld.size())) return;
518
+ pairPositions(keptNew[static_cast<size_t>(i)], keptOld[static_cast<size_t>(o)]);
519
+ };
520
+
521
+ int keptCursor = 0;
522
+ while (keptCursor < static_cast<int>(keptNew.size()) && keptNew[static_cast<size_t>(keptCursor)] < caretIndex) ++keptCursor;
523
+ const int lenDiff = static_cast<int>(keptNew.size()) - static_cast<int>(keptOld.size());
524
+
525
+ if (lenDiff > 0) {
526
+ const int editStart = keptCursor - lenDiff;
527
+ for (int i = 0; i < editStart; ++i) pairKept(i, i);
528
+ for (int i = keptCursor; i < static_cast<int>(keptNew.size()); ++i) pairKept(i, i - lenDiff);
529
+ } else if (lenDiff < 0) {
530
+ for (int i = 0; i < keptCursor; ++i) pairKept(i, i);
531
+ for (int i = keptCursor; i < static_cast<int>(keptNew.size()); ++i) pairKept(i, i - lenDiff);
532
+ } else {
533
+ for (int i = 0; i < static_cast<int>(keptNew.size()); ++i) pairKept(i, i);
534
+ }
535
+
536
+ // Identical separators (grouping commas) pair from the units end so the
537
+ // thousands comma stays the thousands comma; a mask's mixed punctuation
538
+ // ("(555) 123-4567") pairs in order, as a subsequence.
539
+ bool uniform = true;
540
+ const auto sepChar = [&](const std::vector<int>& positions, const std::vector<int>& body, size_t i, bool old) {
541
+ const int index = body[static_cast<size_t>(positions[i])];
542
+ return old ? slots_[static_cast<size_t>(index)].g.character : inputs[static_cast<size_t>(index)].character;
543
+ };
544
+ for (size_t i = 1; i < sepOld.size() && uniform; ++i) uniform = sepChar(sepOld, oldBody, i, true) == sepChar(sepOld, oldBody, 0, true);
545
+ for (size_t i = 0; i < sepNew.size() && uniform; ++i) uniform = sepOld.empty() || sepChar(sepNew, newBody, i, false) == sepChar(sepOld, oldBody, 0, true);
546
+ // A grouping separator only holds its place while the integer columns hold
547
+ // theirs. Type a digit into them and every comma belongs a group further
548
+ // along; gliding it there would drag it sideways across the very digits that
549
+ // just carried, the two passing through each other. So it leaves downwards
550
+ // and a new one rises instead — the same reshape rule the place walk uses.
551
+ // A mask's mixed punctuation is structure, not grouping, and is left alone.
552
+ const auto integerDigits = [&](const std::vector<int>& body, bool old) {
553
+ int count = 0;
554
+ for (size_t p = 0; p < body.size(); ++p) {
555
+ const size_t index = static_cast<size_t>(body[p]);
556
+ const int kind = old ? slots_[index].g.kind : inputs[index].kind;
557
+ if (kind == Decimal) break;
558
+ if (kind == Digit) ++count;
559
+ }
560
+ return count;
561
+ };
562
+ bool carried = false;
563
+ for (size_t p = 0; p < newBody.size() && !carried; ++p) {
564
+ const size_t index = static_cast<size_t>(newBody[p]);
565
+ if (inputs[index].kind == Decimal) break;
566
+ if (inputs[index].kind == Digit && matchOfNew[index] >= 0) carried = true;
567
+ }
568
+ const bool reshaped = carried && integerDigits(oldBody, true) != integerDigits(newBody, false);
569
+ if (uniform) {
570
+ if (!reshaped) {
571
+ for (size_t k = 1; k <= sepOld.size() && k <= sepNew.size(); ++k) {
572
+ pairPositions(sepNew[sepNew.size() - k], sepOld[sepOld.size() - k]);
573
+ }
574
+ }
575
+ } else {
576
+ std::vector<std::pair<int, int>> pairs;
577
+ lcsPairs(static_cast<int>(sepOld.size()), static_cast<int>(sepNew.size()),
578
+ [&](int i, int j) {
579
+ return same(inputs[static_cast<size_t>(newBody[static_cast<size_t>(sepNew[static_cast<size_t>(j)])])],
580
+ slots_[static_cast<size_t>(oldBody[static_cast<size_t>(sepOld[static_cast<size_t>(i)])])]);
581
+ },
582
+ pairs);
583
+ for (const auto& [i, j] : pairs) pairPositions(sepNew[static_cast<size_t>(j)], sepOld[static_cast<size_t>(i)]);
584
+ }
585
+ }
586
+
587
+ /// Pairs digits by their distance from the decimal separator: a digit's
588
+ /// identity is its column. When the integer part gained or lost columns the
589
+ /// digits pair by subsequence from the units end instead, and the separators,
590
+ /// which would have to cross them, leave.
591
+ void MorphEngine::matchByPlace(const std::vector<Input>& inputs, const std::vector<int>& oldBody,
592
+ const std::vector<int>& newBody, std::vector<int>& matchOfNew) const {
593
+ const int n = static_cast<int>(oldBody.size());
594
+ const int m = static_cast<int>(newBody.size());
595
+ const auto oldSlot = [&](int p) -> const Slot& { return slots_[static_cast<size_t>(oldBody[static_cast<size_t>(p)])]; };
596
+ const auto newIn = [&](int p) -> const Input& { return inputs[static_cast<size_t>(newBody[static_cast<size_t>(p)])]; };
597
+ const auto pair = [&](int newPos, int oldPos) {
598
+ if (same(newIn(newPos), oldSlot(oldPos))) matchOfNew[static_cast<size_t>(newBody[static_cast<size_t>(newPos)])] = oldBody[static_cast<size_t>(oldPos)];
599
+ };
600
+
601
+ int start = 0;
602
+ while (start < n && start < m && oldSlot(start).g.kind != Digit && same(newIn(start), oldSlot(start))) {
603
+ pair(start, start);
604
+ ++start;
605
+ }
606
+ int oldEnd = n, newEnd = m;
607
+ while (oldEnd > start && newEnd > start && oldSlot(oldEnd - 1).g.kind != Digit && same(newIn(newEnd - 1), oldSlot(oldEnd - 1))) {
608
+ pair(newEnd - 1, oldEnd - 1);
609
+ --oldEnd;
610
+ --newEnd;
611
+ }
612
+
613
+ int oldPivot = oldEnd, newPivot = newEnd;
614
+ for (int i = oldEnd - 1; i >= start; --i) {
615
+ if (oldSlot(i).g.kind == Decimal) { oldPivot = i; break; }
616
+ }
617
+ for (int i = newEnd - 1; i >= start; --i) {
618
+ if (newIn(i).kind == Decimal) { newPivot = i; break; }
619
+ }
620
+
621
+ std::vector<int> oldInt, newInt;
622
+ for (int i = start; i < oldPivot; ++i) if (oldSlot(i).g.kind == Digit) oldInt.push_back(i);
623
+ for (int i = start; i < newPivot; ++i) if (newIn(i).kind == Digit) newInt.push_back(i);
624
+
625
+ // Past this the digits overlap into a smear and nothing should carry across.
626
+ constexpr int kMagnitudeJump = 3;
627
+ if (!oldInt.empty() && !newInt.empty() &&
628
+ std::abs(static_cast<int>(oldInt.size()) - static_cast<int>(newInt.size())) >= kMagnitudeJump) {
629
+ return;
630
+ }
631
+
632
+ bool reshaped = false;
633
+ if (oldInt.size() == newInt.size()) {
634
+ for (size_t k = 0; k < oldInt.size(); ++k) pair(newInt[k], oldInt[k]);
635
+ } else {
636
+ // Reversed, so the subsequence walk resolves its ties from the units end.
637
+ std::vector<std::pair<int, int>> pairs;
638
+ lcsPairs(static_cast<int>(oldInt.size()), static_cast<int>(newInt.size()),
639
+ [&](int i, int j) {
640
+ return same(newIn(newInt[newInt.size() - 1 - static_cast<size_t>(j)]), oldSlot(oldInt[oldInt.size() - 1 - static_cast<size_t>(i)]));
641
+ },
642
+ pairs);
643
+ for (const auto& [i, j] : pairs) {
644
+ pair(newInt[newInt.size() - 1 - static_cast<size_t>(j)], oldInt[oldInt.size() - 1 - static_cast<size_t>(i)]);
645
+ }
646
+ reshaped = !pairs.empty();
647
+ }
648
+
649
+ if (!reshaped) {
650
+ for (int k = 1; oldPivot - k >= start && newPivot - k >= start; ++k) {
651
+ if (oldSlot(oldPivot - k).g.kind != Digit) pair(newPivot - k, oldPivot - k);
652
+ }
653
+ }
654
+
655
+ if (oldPivot < oldEnd && newPivot < newEnd) {
656
+ pair(newPivot, oldPivot);
657
+ for (int k = 1; oldPivot + k < oldEnd && newPivot + k < newEnd; ++k) {
658
+ if (oldSlot(oldPivot + k).g.kind != Digit) pair(newPivot + k, oldPivot + k);
659
+ }
660
+ std::vector<int> oldFrac, newFrac;
661
+ for (int i = oldPivot + 1; i < oldEnd; ++i) if (oldSlot(i).g.kind == Digit) oldFrac.push_back(i);
662
+ for (int i = newPivot + 1; i < newEnd; ++i) if (newIn(i).kind == Digit) newFrac.push_back(i);
663
+ for (size_t k = 0; k < oldFrac.size() && k < newFrac.size(); ++k) pair(newFrac[k], oldFrac[k]);
664
+ }
665
+ }
666
+
667
+ // MARK: - Frames
668
+
669
+ bool MorphEngine::tick(double now) {
670
+ now_ = now;
671
+ if (!animating_) return false;
672
+ bool moving = false;
673
+ // A frame timed exactly `duration` after the start counts as finished (float slack).
674
+ const auto progress = [&](double start) { return duration_ > 0 ? clamp01((now - start + 1e-9) / duration_) : 1.0; };
675
+
676
+ const double wp = progress(widthStart_);
677
+ contentWidth_ = widthFrom_ + (targetWidth_ - widthFrom_) * ease(wp);
678
+ if (wp < 1) moving = true;
679
+
680
+ // Anchors first (glyphs that stay), then the glyphs riding along with them.
681
+ for (int pass = 0; pass < 2; ++pass) {
682
+ for (auto& s : slots_) {
683
+ const bool anchored = s.anchorId >= 0;
684
+ if ((pass == 0) == anchored) continue;
685
+ const double p = progress(s.start);
686
+ const double e = ease(p);
687
+ if (anchored) {
688
+ const int a = slotIndexOf(s.anchorId);
689
+ const double base = s.g.exiting ? s.fromX : s.toX;
690
+ if (a >= 0) {
691
+ s.g.x = base + (slots_[static_cast<size_t>(a)].g.x - s.anchorBaseX);
692
+ } else {
693
+ s.anchorId = -1;
694
+ s.fromX = s.toX = base;
695
+ s.g.x = base;
696
+ }
697
+ } else if (s.grouped) {
698
+ // One shared scale, expressed per glyph: `scale` is about a glyph's own
699
+ // centre, so put that centre where scaling the run about `groupCentre`
700
+ // would have carried it.
701
+ const double sc = s.fromScale + (s.toScale - s.fromScale) * e;
702
+ const double rest = s.toX + s.g.width / 2;
703
+ s.g.x = s.groupCentre + sc * (rest - s.groupCentre) - s.g.width / 2;
704
+ } else {
705
+ s.g.x = s.fromX + (s.toX - s.fromX) * e;
706
+ }
707
+ s.g.y = s.fromY + (s.toY - s.fromY) * e;
708
+ s.g.scale = s.fromScale + (s.toScale - s.fromScale) * e;
709
+ s.g.opacity = s.fromOpacity + (s.toOpacity - s.fromOpacity) * ramp(p, s.fadeFrom, s.fadeTo);
710
+ if (p < 1) moving = true;
711
+ }
712
+ }
713
+
714
+ slots_.erase(std::remove_if(slots_.begin(), slots_.end(),
715
+ [&](const Slot& s) { return s.g.exiting && progress(s.start) >= 1; }),
716
+ slots_.end());
717
+
718
+ animating_ = moving;
719
+ publish();
720
+ return moving;
721
+ }
722
+
723
+ bool MorphEngine::needsFrames() const {
724
+ return animating_;
725
+ }
726
+
727
+ // MARK: - Render state
728
+
729
+ int MorphEngine::bodyCount() const {
730
+ int count = 0;
731
+ for (const auto& s : slots_) {
732
+ if (!s.g.exiting && s.g.role == Body) ++count;
733
+ }
734
+ return count;
735
+ }
736
+
737
+ namespace {
738
+
739
+ /// The horizontal extent of one block of the run.
740
+ struct Block {
741
+ double start = 0;
742
+ double end = 0;
743
+ bool any = false;
744
+ void add(double x, double width) {
745
+ if (!any) {
746
+ start = x;
747
+ end = x + width;
748
+ any = true;
749
+ } else {
750
+ start = std::min(start, x);
751
+ end = std::max(end, x + width);
752
+ }
753
+ }
754
+ };
755
+
756
+ /// Whitespace an affix uses to keep its distance from the digits.
757
+ bool isSpace(uint32_t c) {
758
+ return c == 0x20 || c == 0xA0 || c == 0x2009 || c == 0x202F;
759
+ }
760
+
761
+ /// The run in six blocks: the prefix's ink and the space it ends with, a sign
762
+ /// laid out ahead of the prefix (`signPlacement: 'beforeAffix'` - a body
763
+ /// glyph, but outside the body's extent), the rest of the body, and the space
764
+ /// the suffix starts with and its ink. The spaces are blocks of their own so
765
+ /// that, mirrored, they stay against the digits rather than ending up on the
766
+ /// outside: " USD" after the number becomes "USD " before it.
767
+ struct Blocks {
768
+ Block prefix, prefixGap, sign, rest, suffixGap, suffix;
769
+ /// The extent of every prefix glyph, gap included.
770
+ Block wholePrefix;
771
+ /// Right edge of the prefix's last ink, left edge of the suffix's first.
772
+ double prefixInkEnd = 0;
773
+ double suffixInkStart = 0;
774
+ bool aheadOfPrefix(const MorphEngine::Glyph& g) const {
775
+ return wholePrefix.any && g.x + g.width <= wholePrefix.start + 1e-6;
776
+ }
777
+ bool prefixGapGlyph(const MorphEngine::Glyph& g) const {
778
+ return g.role == MorphEngine::Prefix && isSpace(g.character) && g.x >= prefixInkEnd - 1e-6;
779
+ }
780
+ bool suffixGapGlyph(const MorphEngine::Glyph& g) const {
781
+ return g.role == MorphEngine::Suffix && isSpace(g.character) && g.x + g.width <= suffixInkStart + 1e-6;
782
+ }
783
+ const Block& of(const MorphEngine::Glyph& g) const {
784
+ if (g.role == MorphEngine::Prefix) return prefixGapGlyph(g) ? prefixGap : prefix;
785
+ if (g.role == MorphEngine::Suffix) return suffixGapGlyph(g) ? suffixGap : suffix;
786
+ return aheadOfPrefix(g) ? sign : rest;
787
+ }
788
+ };
789
+
790
+ Blocks blocksOf(const std::vector<MorphEngine::Glyph>& glyphs) {
791
+ Blocks b;
792
+ bool prefixInk = false;
793
+ bool suffixInk = false;
794
+ for (const auto& g : glyphs) {
795
+ if (g.role == MorphEngine::Prefix) {
796
+ b.wholePrefix.add(g.x, g.width);
797
+ if (!isSpace(g.character)) {
798
+ b.prefixInkEnd = prefixInk ? std::max(b.prefixInkEnd, g.x + g.width) : g.x + g.width;
799
+ prefixInk = true;
800
+ }
801
+ } else if (g.role == MorphEngine::Suffix && !isSpace(g.character)) {
802
+ b.suffixInkStart = suffixInk ? std::min(b.suffixInkStart, g.x) : g.x;
803
+ suffixInk = true;
804
+ }
805
+ }
806
+ // An affix that is all space has no ink to be inside of: it is one block.
807
+ if (!prefixInk) b.prefixInkEnd = b.wholePrefix.any ? b.wholePrefix.end : 0;
808
+ if (!suffixInk) b.suffixInkStart = -1;
809
+ for (const auto& g : glyphs) {
810
+ if (g.role == MorphEngine::Prefix) {
811
+ (b.prefixGapGlyph(g) ? b.prefixGap : b.prefix).add(g.x, g.width);
812
+ } else if (g.role == MorphEngine::Suffix) {
813
+ (b.suffixGapGlyph(g) ? b.suffixGap : b.suffix).add(g.x, g.width);
814
+ } else if (b.aheadOfPrefix(g)) {
815
+ b.sign.add(g.x, g.width);
816
+ } else {
817
+ b.rest.add(g.x, g.width);
818
+ }
819
+ }
820
+ return b;
821
+ }
822
+
823
+ /// Where `x`, inside `block`, lands once the block is at its mirror image.
824
+ double mirrored(double x, const Block& block, double total) {
825
+ return total - block.end + (x - block.start);
826
+ }
827
+
828
+ } // namespace
829
+
830
+ // Under a right-to-left layout the prefix belongs at the start edge, which is
831
+ // the right, and the suffix at the end; the body stays a left-to-right run,
832
+ // because a number reads the same way in every script. So the run is mirrored
833
+ // block by block rather than glyph by glyph: each block moves to where its
834
+ // mirror image would be and keeps its own order inside. `slots_` stay
835
+ // left-to-right - the matching, the caret and the animation all reason there -
836
+ // and only the published frames move.
837
+ void MorphEngine::publish() {
838
+ glyphs_.clear();
839
+ glyphs_.reserve(slots_.size());
840
+ for (const auto& s : slots_) glyphs_.push_back(s.g);
841
+ caretBlocks_ = CaretBlocks{};
842
+ if (!rightToLeft_ || glyphs_.empty()) return;
843
+ const Blocks b = blocksOf(glyphs_);
844
+ const double total = contentWidth_;
845
+ for (auto& g : glyphs_) g.x = mirrored(g.x, b.of(g), total);
846
+ // The caret lives among the live glyphs alone - one on its way out is drawn
847
+ // but is not part of the text - so its blocks are measured over those, from
848
+ // the slots' left-to-right positions, and kept for `caretX`.
849
+ liveBuf_.clear();
850
+ for (const auto& s : slots_) {
851
+ if (!s.g.exiting) liveBuf_.push_back(s.g);
852
+ }
853
+ const Blocks live = blocksOf(liveBuf_);
854
+ caretBlocks_.sign = Extent{live.sign.start, live.sign.end, live.sign.any};
855
+ caretBlocks_.rest = Extent{live.rest.start, live.rest.end, live.rest.any};
856
+ }
857
+
858
+ void MorphEngine::setRightToLeft(bool rightToLeft) {
859
+ if (rightToLeft_ == rightToLeft) return;
860
+ rightToLeft_ = rightToLeft;
861
+ publish();
862
+ }
863
+
864
+ double MorphEngine::caretX(int index) const {
865
+ int seen = 0;
866
+ double afterPrefix = 0;
867
+ double afterLast = -1;
868
+ double x = -1;
869
+ for (const auto& s : slots_) {
870
+ if (s.g.exiting) continue;
871
+ if (s.g.role == Prefix) {
872
+ afterPrefix = s.g.x + s.g.width;
873
+ } else if (s.g.role == Body) {
874
+ if (seen == index && x < 0) x = s.g.x;
875
+ afterLast = s.g.x + s.g.width;
876
+ ++seen;
877
+ }
878
+ }
879
+ if (x < 0) x = afterLast >= 0 ? afterLast : afterPrefix;
880
+ if (!rightToLeft_) return x;
881
+ // The caret lives in the body's block - the sign's for index 0 when the sign
882
+ // is laid out ahead of the prefix - and moves with it. An empty body has no
883
+ // block, and its caret is a point: mirror the point. The blocks were
884
+ // measured when the frame was published (see `publish`).
885
+ const Extent& block = (index == 0 && caretBlocks_.sign.any) ? caretBlocks_.sign : caretBlocks_.rest;
886
+ if (!block.any) return contentWidth_ - x;
887
+ return contentWidth_ - block.end + (x - block.start);
888
+ }
889
+
890
+ void MorphEngine::reset() {
891
+ duration_ = 0.4;
892
+ easing_ = 0;
893
+ bounce_ = 0.15;
894
+ effect_ = 0;
895
+ pending_.clear();
896
+ slots_.clear();
897
+ glyphs_.clear();
898
+ caretBlocks_ = CaretBlocks{};
899
+ committed_ = false;
900
+ animating_ = false;
901
+ contentWidth_ = targetWidth_ = widthFrom_ = 0;
902
+ }
903
+
904
+ } // namespace margelo::nitro::nitroinput