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.
- package/CHANGELOG.md +63 -0
- package/LICENSE +21 -0
- package/NitroInput.podspec +54 -0
- package/README.md +524 -0
- package/android/CMakeLists.txt +52 -0
- package/android/build.gradle +158 -0
- package/android/fix-prefab.gradle +51 -0
- package/android/gradle.properties +4 -0
- package/android/src/main/AndroidManifest.xml +2 -0
- package/android/src/main/cpp/JAmountFormatter.cpp +70 -0
- package/android/src/main/cpp/JAmountFormatter.hpp +45 -0
- package/android/src/main/cpp/JMaskEngine.cpp +81 -0
- package/android/src/main/cpp/JMaskEngine.hpp +52 -0
- package/android/src/main/cpp/JMorphEngine.cpp +132 -0
- package/android/src/main/cpp/JMorphEngine.hpp +54 -0
- package/android/src/main/cpp/JNitroInputWorklets.cpp +83 -0
- package/android/src/main/cpp/JNitroInputWorklets.hpp +40 -0
- package/android/src/main/cpp/JOutlineGeometry.cpp +58 -0
- package/android/src/main/cpp/JOutlineGeometry.hpp +55 -0
- package/android/src/main/cpp/cpp-adapter.cpp +19 -0
- package/android/src/main/java/com/margelo/nitro/nitroinput/AmountFormatter.kt +35 -0
- package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroInputView.kt +730 -0
- package/android/src/main/java/com/margelo/nitro/nitroinput/MaskEngine.kt +50 -0
- package/android/src/main/java/com/margelo/nitro/nitroinput/MorphEngine.kt +47 -0
- package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputPackage.kt +24 -0
- package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputView.kt +2176 -0
- package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputWorklets.kt +34 -0
- package/android/src/main/java/com/margelo/nitro/nitroinput/OutlineGeometry.kt +71 -0
- package/cpp/AmountFormatter.cpp +346 -0
- package/cpp/AmountFormatter.hpp +88 -0
- package/cpp/MaskEngine.cpp +596 -0
- package/cpp/MaskEngine.hpp +136 -0
- package/cpp/MorphEngine.cpp +904 -0
- package/cpp/MorphEngine.hpp +213 -0
- package/cpp/OutlineGeometry.cpp +159 -0
- package/cpp/OutlineGeometry.hpp +107 -0
- package/cpp/worklets/HybridNitroInputWorklets.cpp +30 -0
- package/cpp/worklets/HybridNitroInputWorklets.hpp +30 -0
- package/cpp/worklets/NitroInputWorkletsBridge.cpp +203 -0
- package/cpp/worklets/NitroInputWorkletsBridge.hpp +52 -0
- package/cpp/worklets/NitroInputWorkletsBridgeJSI.hpp +23 -0
- package/ios/HybridMorphInputView.swift +710 -0
- package/ios/NitroInputCommands.mm +66 -0
- package/ios/NitroInputView.swift +2600 -0
- package/lib/commonjs/nitrogen/generated/shared/json/NitroInputViewConfig.json +101 -0
- package/lib/commonjs/src/MorphInput.js +42 -0
- package/lib/commonjs/src/NitroInput.js +623 -0
- package/lib/commonjs/src/index.js +12 -0
- package/lib/commonjs/src/specs/NitroInput.nitro.js +2 -0
- package/lib/commonjs/src/specs/NitroInputWorklets.nitro.js +2 -0
- package/lib/commonjs/src/useNitroInputState.js +58 -0
- package/lib/commonjs/src/worklets.js +226 -0
- package/lib/module/nitrogen/generated/shared/json/NitroInputViewConfig.json +101 -0
- package/lib/module/package.json +1 -0
- package/lib/module/src/MorphInput.js +6 -0
- package/lib/module/src/NitroInput.js +584 -0
- package/lib/module/src/index.js +4 -0
- package/lib/module/src/specs/NitroInput.nitro.js +1 -0
- package/lib/module/src/specs/NitroInputWorklets.nitro.js +1 -0
- package/lib/module/src/useNitroInputState.js +55 -0
- package/lib/module/src/worklets.js +214 -0
- package/lib/typescript/src/MorphInput.d.ts +18 -0
- package/lib/typescript/src/NitroInput.d.ts +411 -0
- package/lib/typescript/src/index.d.ts +6 -0
- package/lib/typescript/src/specs/NitroInput.nitro.d.ts +390 -0
- package/lib/typescript/src/specs/NitroInputWorklets.nitro.d.ts +15 -0
- package/lib/typescript/src/useNitroInputState.d.ts +55 -0
- package/lib/typescript/src/worklets.d.ts +117 -0
- package/nitro.json +37 -0
- package/nitrogen/generated/.gitattributes +1 -0
- package/nitrogen/generated/android/NitroInput+autolinking.cmake +84 -0
- package/nitrogen/generated/android/NitroInput+autolinking.gradle +27 -0
- package/nitrogen/generated/android/NitroInputOnLoad.cpp +78 -0
- package/nitrogen/generated/android/NitroInputOnLoad.hpp +34 -0
- package/nitrogen/generated/android/c++/JFunc_void_bool.hpp +75 -0
- package/nitrogen/generated/android/c++/JFunc_void_double.hpp +75 -0
- package/nitrogen/generated/android/c++/JFunc_void_double_double.hpp +75 -0
- package/nitrogen/generated/android/c++/JFunc_void_std__string.hpp +76 -0
- package/nitrogen/generated/android/c++/JFunc_void_std__string_double.hpp +76 -0
- package/nitrogen/generated/android/c++/JFunc_void_std__string_std__string_std__string_bool.hpp +76 -0
- package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.cpp +1073 -0
- package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.hpp +254 -0
- package/nitrogen/generated/android/c++/JNitroInputAffixAlign.hpp +64 -0
- package/nitrogen/generated/android/c++/JNitroInputAutoCapitalize.hpp +64 -0
- package/nitrogen/generated/android/c++/JNitroInputEasing.hpp +67 -0
- package/nitrogen/generated/android/c++/JNitroInputEffect.hpp +61 -0
- package/nitrogen/generated/android/c++/JNitroInputKeyboardAppearance.hpp +61 -0
- package/nitrogen/generated/android/c++/JNitroInputKeyboardType.hpp +79 -0
- package/nitrogen/generated/android/c++/JNitroInputLabelBehavior.hpp +58 -0
- package/nitrogen/generated/android/c++/JNitroInputMode.hpp +61 -0
- package/nitrogen/generated/android/c++/JNitroInputNotation.hpp +65 -0
- package/nitrogen/generated/android/c++/JNitroInputReturnKeyType.hpp +70 -0
- package/nitrogen/generated/android/c++/JNitroInputSignPlacement.hpp +58 -0
- package/nitrogen/generated/android/c++/JNitroInputSubmitBehavior.hpp +61 -0
- package/nitrogen/generated/android/c++/JNitroInputTextAlign.hpp +64 -0
- package/nitrogen/generated/android/c++/JNitroInputTextAlignVertical.hpp +64 -0
- package/nitrogen/generated/android/c++/JNitroInputVariant.hpp +61 -0
- package/nitrogen/generated/android/c++/views/JHybridNitroInputViewStateUpdater.cpp +529 -0
- package/nitrogen/generated/android/c++/views/JHybridNitroInputViewStateUpdater.hpp +54 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/Func_void_bool.kt +78 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/Func_void_double.kt +78 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/Func_void_double_double.kt +78 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/Func_void_std__string.kt +78 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/Func_void_std__string_double.kt +78 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/Func_void_std__string_std__string_std__string_bool.kt +78 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroInputViewSpec.kt +711 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputAffixAlign.kt +25 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputAutoCapitalize.kt +25 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputEasing.kt +26 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputEffect.kt +24 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputKeyboardAppearance.kt +24 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputKeyboardType.kt +30 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputLabelBehavior.kt +23 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputMode.kt +24 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputNotation.kt +61 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputOnLoad.kt +35 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputReturnKeyType.kt +27 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputSignPlacement.kt +23 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputSubmitBehavior.kt +24 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputTextAlign.kt +25 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputTextAlignVertical.kt +25 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputVariant.kt +24 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/views/HybridNitroInputViewManager.kt +96 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/views/HybridNitroInputViewStateUpdater.kt +23 -0
- package/nitrogen/generated/ios/NitroInput+autolinking.rb +62 -0
- package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Bridge.cpp +81 -0
- package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Bridge.hpp +348 -0
- package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Umbrella.hpp +92 -0
- package/nitrogen/generated/ios/NitroInputAutolinking.mm +43 -0
- package/nitrogen/generated/ios/NitroInputAutolinking.swift +26 -0
- package/nitrogen/generated/ios/c++/HybridNitroInputViewSpecSwift.cpp +11 -0
- package/nitrogen/generated/ios/c++/HybridNitroInputViewSpecSwift.hpp +769 -0
- package/nitrogen/generated/ios/c++/views/HybridNitroInputViewComponent.mm +690 -0
- package/nitrogen/generated/ios/swift/Func_void_bool.swift +46 -0
- package/nitrogen/generated/ios/swift/Func_void_double.swift +46 -0
- package/nitrogen/generated/ios/swift/Func_void_double_double.swift +46 -0
- package/nitrogen/generated/ios/swift/Func_void_std__string.swift +46 -0
- package/nitrogen/generated/ios/swift/Func_void_std__string_double.swift +46 -0
- package/nitrogen/generated/ios/swift/Func_void_std__string_std__string_std__string_bool.swift +46 -0
- package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec.swift +154 -0
- package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec_cxx.swift +1454 -0
- package/nitrogen/generated/ios/swift/NitroInputAffixAlign.swift +48 -0
- package/nitrogen/generated/ios/swift/NitroInputAutoCapitalize.swift +48 -0
- package/nitrogen/generated/ios/swift/NitroInputEasing.swift +52 -0
- package/nitrogen/generated/ios/swift/NitroInputEffect.swift +44 -0
- package/nitrogen/generated/ios/swift/NitroInputKeyboardAppearance.swift +44 -0
- package/nitrogen/generated/ios/swift/NitroInputKeyboardType.swift +68 -0
- package/nitrogen/generated/ios/swift/NitroInputLabelBehavior.swift +40 -0
- package/nitrogen/generated/ios/swift/NitroInputMode.swift +44 -0
- package/nitrogen/generated/ios/swift/NitroInputNotation.swift +39 -0
- package/nitrogen/generated/ios/swift/NitroInputReturnKeyType.swift +56 -0
- package/nitrogen/generated/ios/swift/NitroInputSignPlacement.swift +40 -0
- package/nitrogen/generated/ios/swift/NitroInputSubmitBehavior.swift +44 -0
- package/nitrogen/generated/ios/swift/NitroInputTextAlign.swift +48 -0
- package/nitrogen/generated/ios/swift/NitroInputTextAlignVertical.swift +48 -0
- package/nitrogen/generated/ios/swift/NitroInputVariant.swift +44 -0
- package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.cpp +213 -0
- package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.hpp +300 -0
- package/nitrogen/generated/shared/c++/HybridNitroInputWorkletsSpec.cpp +21 -0
- package/nitrogen/generated/shared/c++/HybridNitroInputWorkletsSpec.hpp +62 -0
- package/nitrogen/generated/shared/c++/NitroInputAffixAlign.hpp +84 -0
- package/nitrogen/generated/shared/c++/NitroInputAutoCapitalize.hpp +84 -0
- package/nitrogen/generated/shared/c++/NitroInputEasing.hpp +88 -0
- package/nitrogen/generated/shared/c++/NitroInputEffect.hpp +80 -0
- package/nitrogen/generated/shared/c++/NitroInputKeyboardAppearance.hpp +80 -0
- package/nitrogen/generated/shared/c++/NitroInputKeyboardType.hpp +104 -0
- package/nitrogen/generated/shared/c++/NitroInputLabelBehavior.hpp +76 -0
- package/nitrogen/generated/shared/c++/NitroInputMode.hpp +80 -0
- package/nitrogen/generated/shared/c++/NitroInputNotation.hpp +91 -0
- package/nitrogen/generated/shared/c++/NitroInputReturnKeyType.hpp +92 -0
- package/nitrogen/generated/shared/c++/NitroInputSignPlacement.hpp +76 -0
- package/nitrogen/generated/shared/c++/NitroInputSubmitBehavior.hpp +80 -0
- package/nitrogen/generated/shared/c++/NitroInputTextAlign.hpp +84 -0
- package/nitrogen/generated/shared/c++/NitroInputTextAlignVertical.hpp +84 -0
- package/nitrogen/generated/shared/c++/NitroInputVariant.hpp +80 -0
- package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.cpp +216 -0
- package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.hpp +374 -0
- package/nitrogen/generated/shared/json/NitroInputViewConfig.json +101 -0
- package/package.json +141 -0
- package/react-native.config.js +16 -0
- package/src/MorphInput.tsx +30 -0
- package/src/NitroInput.tsx +1364 -0
- package/src/index.ts +55 -0
- package/src/specs/NitroInput.nitro.ts +436 -0
- package/src/specs/NitroInputWorklets.nitro.ts +13 -0
- package/src/useNitroInputState.ts +101 -0
- package/src/worklets.ts +300 -0
|
@@ -0,0 +1,2600 @@
|
|
|
1
|
+
//
|
|
2
|
+
// NitroInputView.swift
|
|
3
|
+
// NitroInput
|
|
4
|
+
//
|
|
5
|
+
// A single-line input whose text morphs as it changes. The behaviour (which
|
|
6
|
+
// glyph is which across an edit, where every glyph is on its way, opacity,
|
|
7
|
+
// slide, scale) lives in the shared C++ `MorphEngine`; the number formatting
|
|
8
|
+
// in `AmountFormatter`. This view owns:
|
|
9
|
+
//
|
|
10
|
+
// - a hidden system `UITextField` filling the bounds that provides keyboard,
|
|
11
|
+
// editing, selection, the paste menu and accessibility. Its text is drawn
|
|
12
|
+
// invisible and its caret hidden; its font, insets (prefix / suffix widths)
|
|
13
|
+
// and alignment mirror ours so its selection geometry matches ours at rest,
|
|
14
|
+
// and taps map through the engine's glyph positions (`closestPosition(to:)`).
|
|
15
|
+
// - an overlay of CALayers: one pre-rasterized image per engine glyph, moved
|
|
16
|
+
// by a display link while the engine says something is animating, plus our
|
|
17
|
+
// own blinking caret that follows the engine's caret position.
|
|
18
|
+
//
|
|
19
|
+
|
|
20
|
+
import CoreText
|
|
21
|
+
import UIKit
|
|
22
|
+
|
|
23
|
+
final class NitroInputView: UIView {
|
|
24
|
+
|
|
25
|
+
private typealias Engine = margelo.nitro.nitroinput.MorphEngine
|
|
26
|
+
private typealias AmountFormatter = margelo.nitro.nitroinput.AmountFormatter
|
|
27
|
+
private typealias MaskEngine = margelo.nitro.nitroinput.MaskEngine
|
|
28
|
+
private typealias Outline = margelo.nitro.nitroinput.OutlineGeometry
|
|
29
|
+
|
|
30
|
+
// Engine roles / kinds (plain ints so the unscoped C++ enums need no bridging).
|
|
31
|
+
private enum Role { static let prefix: Int32 = 0, body: Int32 = 1, suffix: Int32 = 2 }
|
|
32
|
+
private enum Kind { static let text: Int32 = 0 }
|
|
33
|
+
|
|
34
|
+
// MARK: - Configuration
|
|
35
|
+
|
|
36
|
+
enum Mode: Equatable {
|
|
37
|
+
case text, number, mask
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/// A caller-defined slot character for `mask`.
|
|
41
|
+
struct MaskNotation: Equatable {
|
|
42
|
+
var character: String
|
|
43
|
+
var characterSet: String
|
|
44
|
+
var isOptional: Bool
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
struct Format: Equatable {
|
|
48
|
+
var mode: Mode = .text
|
|
49
|
+
/// Mask mode: the pattern, e.g. "+1 ([000]) [000]-[0000]".
|
|
50
|
+
var mask: String = ""
|
|
51
|
+
var maskNotations: [MaskNotation] = []
|
|
52
|
+
var maskAutocomplete: Bool = true
|
|
53
|
+
var maskAutoSkip: Bool = false
|
|
54
|
+
var fractionDigits: Int = 2
|
|
55
|
+
var maxIntegerDigits: Int = 15
|
|
56
|
+
var groupingSeparator: String = ","
|
|
57
|
+
var decimalSeparator: String = "."
|
|
58
|
+
var prefix: String = ""
|
|
59
|
+
var suffix: String = ""
|
|
60
|
+
/// Where a negative amount's sign sits relative to `prefix`.
|
|
61
|
+
var signPlacement: SignPlacement = .beforeAffix
|
|
62
|
+
var placeholder: String = ""
|
|
63
|
+
/// Text mode only; 0 = unlimited.
|
|
64
|
+
var maxLength: Int = 0
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
enum TextAlignVertical: Equatable { case auto, top, center, bottom }
|
|
68
|
+
|
|
69
|
+
enum AffixAlign {
|
|
70
|
+
case baseline, center, top, bottom
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/// Where a negative amount's sign sits relative to the prefix.
|
|
74
|
+
enum SignPlacement: Equatable { case beforeAffix, afterAffix }
|
|
75
|
+
|
|
76
|
+
/// What the return key does, as React Native's `TextInput` has it on iOS.
|
|
77
|
+
enum SubmitBehavior: Equatable {
|
|
78
|
+
/// Fires `onSubmitEditing` and keeps focus, so a form can move on itself.
|
|
79
|
+
case submit
|
|
80
|
+
/// Fires `onSubmitEditing` and dismisses the keyboard.
|
|
81
|
+
case blurAndSubmit
|
|
82
|
+
/// Inserts a line break on a wrapping field; on a single line it neither
|
|
83
|
+
/// submits nor blurs.
|
|
84
|
+
case newline
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
enum Variant: Equatable { case none, outlined, filled }
|
|
88
|
+
enum LabelBehavior: Equatable { case float, always }
|
|
89
|
+
|
|
90
|
+
/// The frame the view draws for itself: the outline (or fill) and the
|
|
91
|
+
/// floating label. Separate from `Format` because it changes independently.
|
|
92
|
+
struct Frame: Equatable {
|
|
93
|
+
var variant: Variant = .none
|
|
94
|
+
var label: String = ""
|
|
95
|
+
var labelBehavior: LabelBehavior = .float
|
|
96
|
+
var labelColor: UIColor? = nil
|
|
97
|
+
var labelFocusedColor: UIColor? = nil
|
|
98
|
+
var labelFontSize: CGFloat = 0
|
|
99
|
+
var strokeColor: UIColor? = nil
|
|
100
|
+
var focusedStrokeColor: UIColor? = nil
|
|
101
|
+
var strokeWidth: CGFloat = 1
|
|
102
|
+
var cornerRadius: CGFloat = 8
|
|
103
|
+
var fillColor: UIColor? = nil
|
|
104
|
+
|
|
105
|
+
var draws: Bool { variant != .none }
|
|
106
|
+
var hasLabel: Bool { draws && !label.isEmpty }
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
struct Typography: Hashable {
|
|
110
|
+
var fontSize: CGFloat = 32
|
|
111
|
+
/// Line box height in points; 0 uses the font's own.
|
|
112
|
+
var lineHeight: CGFloat = 0
|
|
113
|
+
var prefixFontSize: CGFloat? = nil
|
|
114
|
+
var suffixFontSize: CGFloat? = nil
|
|
115
|
+
var fontWeight: CGFloat = 400
|
|
116
|
+
var fontFamily: String? = nil
|
|
117
|
+
var color: UIColor = .label
|
|
118
|
+
var placeholderColor: UIColor = .placeholderText
|
|
119
|
+
var prefixAlign: AffixAlign = .baseline
|
|
120
|
+
var suffixAlign: AffixAlign = .baseline
|
|
121
|
+
var adjustsFontSizeToFit: Bool = false
|
|
122
|
+
var minimumFontScale: CGFloat = 0.5
|
|
123
|
+
var allowFontScaling: Bool = false
|
|
124
|
+
var maxFontSizeMultiplier: CGFloat = 0
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
struct Timing: Equatable {
|
|
128
|
+
var duration: TimeInterval = 0.4
|
|
129
|
+
/// 0 expo, 1 easeOut, 2 easeInOut, 3 linear, 4 spring.
|
|
130
|
+
var easing: Int32 = 0
|
|
131
|
+
var bounce: Double = 0.15
|
|
132
|
+
/// 0 auto, 1 slide, 2 fade.
|
|
133
|
+
var effect: Int32 = 0
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/// Everything the hidden system field is configured with.
|
|
137
|
+
struct Traits: Equatable {
|
|
138
|
+
var keyboardType: UIKeyboardType = .default
|
|
139
|
+
var returnKeyType: UIReturnKeyType = .default
|
|
140
|
+
var autocapitalization: UITextAutocapitalizationType = .sentences
|
|
141
|
+
var autocorrect: Bool = true
|
|
142
|
+
var editable: Bool = true
|
|
143
|
+
var autoFocus: Bool = false
|
|
144
|
+
/// Wrapping field. Always plain and always text - the JS side drops
|
|
145
|
+
/// `morph` and any non-text mode first - so the glyph engine, which lays
|
|
146
|
+
/// one run out on one baseline, never has to deal with a wrapped one.
|
|
147
|
+
var multiline: Bool = false
|
|
148
|
+
/// Lines before it scrolls; 0 grows with the content.
|
|
149
|
+
var numberOfLines: Int = 0
|
|
150
|
+
var textAlignVertical: TextAlignVertical = .auto
|
|
151
|
+
var scrollEnabled: Bool = true
|
|
152
|
+
var caretHidden: Bool = false
|
|
153
|
+
var caretColor: UIColor? = nil
|
|
154
|
+
var selectionColor: UIColor? = nil
|
|
155
|
+
var submitBehavior: SubmitBehavior = .blurAndSubmit
|
|
156
|
+
var secureTextEntry: Bool = false
|
|
157
|
+
var keyboardAppearance: UIKeyboardAppearance = .default
|
|
158
|
+
var textContentType: UITextContentType? = nil
|
|
159
|
+
var enablesReturnKeyAutomatically: Bool = false
|
|
160
|
+
var showSoftInputOnFocus: Bool = true
|
|
161
|
+
var selectTextOnFocus: Bool = false
|
|
162
|
+
var clearTextOnFocus: Bool = false
|
|
163
|
+
var contextMenuHidden: Bool = false
|
|
164
|
+
var spellCheck: Bool = true
|
|
165
|
+
/// `testID` and `accessibilityLabel`, forwarded from JS so the hidden
|
|
166
|
+
/// field — the element VoiceOver and e2e tools see — carries them.
|
|
167
|
+
var testID: String? = nil
|
|
168
|
+
var accessibilityLabel: String? = nil
|
|
169
|
+
/// `NitroInput`: let the system field draw its own text and skip the
|
|
170
|
+
/// overlay, the glyph engine and the custom caret entirely.
|
|
171
|
+
var plain: Bool = false
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
enum Alignment {
|
|
175
|
+
/// The start edge of the layout direction: left in a left-to-right app,
|
|
176
|
+
/// right in a right-to-left one. What `TextInput` does with no `textAlign`.
|
|
177
|
+
case auto
|
|
178
|
+
/// Absolute, whatever the layout direction.
|
|
179
|
+
case left, center, right
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/// Why the text changed; decides which JS callbacks fire.
|
|
183
|
+
enum ChangeReason {
|
|
184
|
+
/// The user typed, pasted or deleted.
|
|
185
|
+
case user
|
|
186
|
+
/// `clear()`, `setText()`, `setValue()`.
|
|
187
|
+
case method
|
|
188
|
+
/// The `text` prop.
|
|
189
|
+
case prop
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
var format = Format() {
|
|
193
|
+
didSet {
|
|
194
|
+
guard format != oldValue else { return }
|
|
195
|
+
applyFormat(previous: oldValue)
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
var inputFrame = Frame() {
|
|
200
|
+
didSet {
|
|
201
|
+
guard inputFrame != oldValue else { return }
|
|
202
|
+
applyFrame()
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
var typography = Typography() {
|
|
207
|
+
didSet {
|
|
208
|
+
guard typography != oldValue else { return }
|
|
209
|
+
rebuildFonts()
|
|
210
|
+
if inputFrame.draws { layoutFrame(animated: false) }
|
|
211
|
+
// A multiline box is `lineHeight` tall per line, so its height follows
|
|
212
|
+
// the line box even when the text itself has not changed.
|
|
213
|
+
if typography.lineHeight != oldValue.lineHeight { reportIntrinsicSize() }
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
var timing = Timing() {
|
|
218
|
+
didSet {
|
|
219
|
+
guard timing != oldValue else { return }
|
|
220
|
+
engine.setTiming(max(0, timing.duration), timing.easing, timing.bounce)
|
|
221
|
+
engine.setEffect(timing.effect)
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
var traits = Traits() {
|
|
226
|
+
didSet {
|
|
227
|
+
guard traits != oldValue else { return }
|
|
228
|
+
applyTraits(previous: oldValue)
|
|
229
|
+
// Nothing else re-measures when a field turns multiline or changes how
|
|
230
|
+
// many lines it may be: the text is unchanged, so no edit comes through
|
|
231
|
+
// to carry a new height out with it.
|
|
232
|
+
if traits.multiline != oldValue.multiline
|
|
233
|
+
|| traits.numberOfLines != oldValue.numberOfLines
|
|
234
|
+
|| traits.scrollEnabled != oldValue.scrollEnabled {
|
|
235
|
+
reportIntrinsicSize()
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/// Ids of worklets registered from JS (0 = none), run synchronously on the
|
|
241
|
+
/// UI thread through `NitroInputWorkletsBridge` while an edit is handled.
|
|
242
|
+
struct Worklets: Equatable {
|
|
243
|
+
var transform = 0
|
|
244
|
+
var onChangeText = 0
|
|
245
|
+
var onChangeValue = 0
|
|
246
|
+
var onFocusChange = 0
|
|
247
|
+
var onSelectionChange = 0
|
|
248
|
+
var onSubmitEditing = 0
|
|
249
|
+
var onEndEditing = 0
|
|
250
|
+
var onKeyPress = 0
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
var worklets = Worklets()
|
|
254
|
+
|
|
255
|
+
var alignment: Alignment = .auto {
|
|
256
|
+
didSet {
|
|
257
|
+
guard alignment != oldValue else { return }
|
|
258
|
+
field.textAlignment = textAlignment(for: alignment)
|
|
259
|
+
render()
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/// The layout direction this view is in. Fabric sets the host view's
|
|
264
|
+
/// `semanticContentAttribute` from Yoga's resolved direction, and
|
|
265
|
+
/// `effectiveUserInterfaceLayoutDirection` walks up the superview chain to it.
|
|
266
|
+
var isRTL: Bool { effectiveUserInterfaceLayoutDirection == .rightToLeft }
|
|
267
|
+
|
|
268
|
+
/// `.auto` resolved against the layout direction; the rest are already absolute.
|
|
269
|
+
private var resolvedAlignment: Alignment {
|
|
270
|
+
alignment == .auto ? (isRTL ? .right : .left) : alignment
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/// The direction the alignment was last resolved against. It is only knowable
|
|
274
|
+
/// with a superview chain, and a view moved into a subtree with the other
|
|
275
|
+
/// direction has to re-resolve.
|
|
276
|
+
private var resolvedForRTL = false
|
|
277
|
+
|
|
278
|
+
/// Called after every text change with the text, its numeric value (NaN in
|
|
279
|
+
/// text mode / when empty), the native event count and why it changed.
|
|
280
|
+
var onTextChange: ((String, Double, Int, ChangeReason) -> Void)?
|
|
281
|
+
/// Mask mode: formatted, extracted, tail placeholder, complete.
|
|
282
|
+
var onMaskChange: ((String, String, String, Bool) -> Void)?
|
|
283
|
+
var onFocusChange: ((Bool) -> Void)?
|
|
284
|
+
var onSubmit: ((String) -> Void)?
|
|
285
|
+
var onEndEditing: ((String) -> Void)?
|
|
286
|
+
var onSelectionChange: ((Int, Int) -> Void)?
|
|
287
|
+
var onKeyPress: ((String) -> Void)?
|
|
288
|
+
/// Called with the settled (target) intrinsic size whenever it changes.
|
|
289
|
+
var onIntrinsicSizeChange: ((CGSize) -> Void)?
|
|
290
|
+
|
|
291
|
+
/// The field's current (formatted) text.
|
|
292
|
+
/// Whichever backing view is currently the editor: the text view when the
|
|
293
|
+
/// field wraps, the text field otherwise.
|
|
294
|
+
fileprivate var editor: UIView {
|
|
295
|
+
if traits.multiline, didBuildTextView { return textView }
|
|
296
|
+
return field
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/// The text, from whichever backing view is showing. A multiline field is
|
|
300
|
+
/// drawn by the text view, so that is where its text lives.
|
|
301
|
+
var text: String {
|
|
302
|
+
if traits.multiline, didBuildTextView { return textView.text ?? "" }
|
|
303
|
+
return field.text ?? ""
|
|
304
|
+
}
|
|
305
|
+
/// Numeric value of the text: NaN in text mode or when there are no digits.
|
|
306
|
+
var value: Double {
|
|
307
|
+
guard format.mode == .number else { return .nan }
|
|
308
|
+
return formatter.value(std.string(text))
|
|
309
|
+
}
|
|
310
|
+
/// Incremented on every native text change JS has not caused itself.
|
|
311
|
+
private(set) var eventCount = 0
|
|
312
|
+
|
|
313
|
+
// MARK: - Fonts
|
|
314
|
+
|
|
315
|
+
fileprivate enum GlyphRole {
|
|
316
|
+
case body, prefix, suffix
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/// One glyph in one role, as the caches key it. A value type rather than a
|
|
320
|
+
/// concatenated string: a lookup on the frame path must not allocate.
|
|
321
|
+
fileprivate struct GlyphKey: Hashable {
|
|
322
|
+
let text: String
|
|
323
|
+
let role: GlyphRole
|
|
324
|
+
let placeholder: Bool
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/// Body / prefix / suffix fonts with per-glyph caches (advance widths, ink
|
|
328
|
+
/// metrics and pre-rasterized images in the text or placeholder colour).
|
|
329
|
+
fileprivate final class FontSet {
|
|
330
|
+
let body: UIFont
|
|
331
|
+
let prefix: UIFont
|
|
332
|
+
let suffix: UIFont
|
|
333
|
+
/// The text and placeholder colours resolved for the view's traits: the
|
|
334
|
+
/// glyph images bake them in, and `.label` / `.placeholderText` are
|
|
335
|
+
/// dynamic (see `traitCollectionDidChange`).
|
|
336
|
+
let color: UIColor
|
|
337
|
+
let placeholderColor: UIColor
|
|
338
|
+
let prefixAlign: AffixAlign
|
|
339
|
+
let suffixAlign: AffixAlign
|
|
340
|
+
/// Height of the line box (the body font's line height).
|
|
341
|
+
let lineHeight: CGFloat
|
|
342
|
+
/// Pixel density the glyph images are rendered at.
|
|
343
|
+
let renderScale: CGFloat
|
|
344
|
+
private var glyphCache: [GlyphKey: NSAttributedString] = [:]
|
|
345
|
+
private var widthCache: [GlyphKey: CGFloat] = [:]
|
|
346
|
+
private var imageCache: [GlyphKey: UIImage] = [:]
|
|
347
|
+
private var inkDescentCache: [GlyphKey: CGFloat] = [:]
|
|
348
|
+
|
|
349
|
+
/// What a shared font set is a pure function of: the typography, the
|
|
350
|
+
/// colours it resolves to under the view's appearance, and the display
|
|
351
|
+
/// density. Two views that look alike under the same appearance on the
|
|
352
|
+
/// same kind of screen share one; a light one and a dark one do not.
|
|
353
|
+
private struct SharedKey: Hashable {
|
|
354
|
+
let typography: Typography
|
|
355
|
+
let color: UIColor
|
|
356
|
+
let placeholderColor: UIColor
|
|
357
|
+
let scale: CGFloat
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/// Font sets are immutable for a given key and their caches are pure
|
|
361
|
+
/// functions of it, so views that look alike share one. Without this every
|
|
362
|
+
/// field builds its own three `UIFont`s and re-rasterizes the same glyphs:
|
|
363
|
+
/// 20 identical fields did the work 20 times, and each field did it twice
|
|
364
|
+
/// over (once for the defaults in `init`, once when the real typography
|
|
365
|
+
/// arrived). Main-thread only, like the rest of the view.
|
|
366
|
+
private static var shared: [SharedKey: FontSet] = [:]
|
|
367
|
+
private static var sharedOrder: [SharedKey] = []
|
|
368
|
+
|
|
369
|
+
static func shared(for t: Typography, traits: UITraitCollection) -> FontSet {
|
|
370
|
+
let key = SharedKey(typography: t,
|
|
371
|
+
color: t.color.resolvedColor(with: traits),
|
|
372
|
+
placeholderColor: t.placeholderColor.resolvedColor(with: traits),
|
|
373
|
+
scale: max(1, traits.displayScale))
|
|
374
|
+
if let hit = shared[key] { return hit }
|
|
375
|
+
let made = FontSet(t, traits: traits)
|
|
376
|
+
shared[key] = made
|
|
377
|
+
sharedOrder.append(key)
|
|
378
|
+
// A screen rarely uses many distinct typographies; keep the newest few
|
|
379
|
+
// so the caches cannot grow without bound. The sets an appearance switch
|
|
380
|
+
// leaves behind age out the same way.
|
|
381
|
+
if sharedOrder.count > 12 {
|
|
382
|
+
let evicted = sharedOrder.removeFirst()
|
|
383
|
+
shared.removeValue(forKey: evicted)
|
|
384
|
+
}
|
|
385
|
+
return made
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
init(_ t: Typography, traits: UITraitCollection) {
|
|
389
|
+
// The view's own display, not the main screen's (deprecated, and absent on visionOS).
|
|
390
|
+
renderScale = max(1, traits.displayScale)
|
|
391
|
+
let scale = NitroInputView.systemFontMultiplier(t)
|
|
392
|
+
body = NitroInputView.makeFont(size: t.fontSize * scale, weight: t.fontWeight, family: t.fontFamily)
|
|
393
|
+
prefix = NitroInputView.makeFont(size: (t.prefixFontSize ?? t.fontSize) * scale, weight: t.fontWeight, family: t.fontFamily)
|
|
394
|
+
suffix = NitroInputView.makeFont(size: (t.suffixFontSize ?? t.fontSize) * scale, weight: t.fontWeight, family: t.fontFamily)
|
|
395
|
+
color = t.color.resolvedColor(with: traits)
|
|
396
|
+
placeholderColor = t.placeholderColor.resolvedColor(with: traits)
|
|
397
|
+
prefixAlign = t.prefixAlign
|
|
398
|
+
suffixAlign = t.suffixAlign
|
|
399
|
+
lineHeight = ceil(body.lineHeight)
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
func font(for role: GlyphRole) -> UIFont {
|
|
403
|
+
switch role {
|
|
404
|
+
case .body: return body
|
|
405
|
+
case .prefix: return prefix
|
|
406
|
+
case .suffix: return suffix
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
func attributed(_ text: String, role: GlyphRole, placeholder: Bool = false) -> NSAttributedString {
|
|
411
|
+
let key = GlyphKey(text: text, role: role, placeholder: placeholder)
|
|
412
|
+
if let cached = glyphCache[key] { return cached }
|
|
413
|
+
let string = NSAttributedString(string: text, attributes: [
|
|
414
|
+
.font: font(for: role),
|
|
415
|
+
.foregroundColor: placeholder ? placeholderColor : color,
|
|
416
|
+
.kern: 0,
|
|
417
|
+
])
|
|
418
|
+
glyphCache[key] = string
|
|
419
|
+
return string
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/// Advance width of `text` in the role's font, in points.
|
|
423
|
+
func width(of text: String, role: GlyphRole) -> CGFloat {
|
|
424
|
+
let key = GlyphKey(text: text, role: role, placeholder: false)
|
|
425
|
+
if let cached = widthCache[key] { return cached }
|
|
426
|
+
let width = attributed(text, role: role).size().width
|
|
427
|
+
widthCache[key] = width
|
|
428
|
+
return width
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/// The glyph rasterized once (colour baked in, at screen density): a frame
|
|
432
|
+
/// only moves layers, the main thread never redraws a bitmap.
|
|
433
|
+
func image(_ text: String, role: GlyphRole, placeholder: Bool) -> UIImage? {
|
|
434
|
+
let key = GlyphKey(text: text, role: role, placeholder: placeholder)
|
|
435
|
+
if let cached = imageCache[key] { return cached }
|
|
436
|
+
let string = attributed(text, role: role, placeholder: placeholder)
|
|
437
|
+
let size = string.size()
|
|
438
|
+
guard size.width > 0, size.height > 0 else { return nil }
|
|
439
|
+
let format = UIGraphicsImageRendererFormat()
|
|
440
|
+
format.scale = renderScale
|
|
441
|
+
format.opaque = false
|
|
442
|
+
let bounds = CGSize(width: ceil(size.width), height: ceil(size.height))
|
|
443
|
+
let image = UIGraphicsImageRenderer(size: bounds, format: format).image { _ in
|
|
444
|
+
string.draw(at: .zero)
|
|
445
|
+
}
|
|
446
|
+
imageCache[key] = image
|
|
447
|
+
return image
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/// How far `text`'s ink hangs below the baseline (0 for digits and capitals).
|
|
451
|
+
func inkDescent(_ text: String, role: GlyphRole) -> CGFloat {
|
|
452
|
+
let key = GlyphKey(text: text, role: role, placeholder: false)
|
|
453
|
+
if let cached = inkDescentCache[key] { return cached }
|
|
454
|
+
let line = CTLineCreateWithAttributedString(attributed(text, role: role))
|
|
455
|
+
let bounds = CTLineGetImageBounds(line, nil)
|
|
456
|
+
let descent = bounds.isNull ? 0 : max(0, -bounds.minY)
|
|
457
|
+
inkDescentCache[key] = descent
|
|
458
|
+
return descent
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/// Top of the glyph's line box for `role` drawing `text`, given the top of the body line box.
|
|
462
|
+
func top(for role: GlyphRole, text: String, lineTop: CGFloat) -> CGFloat {
|
|
463
|
+
guard role != .body else { return lineTop }
|
|
464
|
+
let f = font(for: role)
|
|
465
|
+
switch role == .prefix ? prefixAlign : suffixAlign {
|
|
466
|
+
case .baseline:
|
|
467
|
+
return lineTop + (body.ascender - f.ascender)
|
|
468
|
+
case .center:
|
|
469
|
+
return lineTop + (body.lineHeight - f.lineHeight) / 2
|
|
470
|
+
case .top:
|
|
471
|
+
return lineTop + (body.ascender - body.capHeight) - (f.ascender - f.capHeight)
|
|
472
|
+
case .bottom:
|
|
473
|
+
// Pin the bottom of the ink, not of the line boxes: the digits' ink ends
|
|
474
|
+
// on the baseline, so "USD" sits on it too instead of hanging down to
|
|
475
|
+
// where a comma's tail reaches.
|
|
476
|
+
let affixBaseline = lineTop + body.ascender + inkDescent("0123456789", role: .body) - inkDescent(text, role: role)
|
|
477
|
+
return affixBaseline - f.ascender
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// MARK: - State
|
|
483
|
+
|
|
484
|
+
private var engine = Engine()
|
|
485
|
+
private var formatter = AmountFormatter()
|
|
486
|
+
private var maskEngine = MaskEngine()
|
|
487
|
+
/// The outline / fill. Stroke-only, so the notch is a hole rather than a mask.
|
|
488
|
+
private lazy var frameLayer: CAShapeLayer = {
|
|
489
|
+
let shape = CAShapeLayer()
|
|
490
|
+
shape.fillColor = nil
|
|
491
|
+
shape.lineCap = .round
|
|
492
|
+
layer.insertSublayer(shape, at: 0)
|
|
493
|
+
return shape
|
|
494
|
+
}()
|
|
495
|
+
/// `filled`: the bottom rule. A plain layer - it is a rectangle, so it needs
|
|
496
|
+
/// no path, and Core Animation can tween its frame and colour directly.
|
|
497
|
+
private lazy var underlineLayer: CALayer = {
|
|
498
|
+
let rule = CALayer()
|
|
499
|
+
layer.insertSublayer(rule, at: 1)
|
|
500
|
+
return rule
|
|
501
|
+
}()
|
|
502
|
+
private lazy var labelLayer: CATextLayer = {
|
|
503
|
+
let text = CATextLayer()
|
|
504
|
+
text.contentsScale = max(1, traitCollection.displayScale)
|
|
505
|
+
text.anchorPoint = CGPoint(x: 0, y: 0.5)
|
|
506
|
+
text.alignmentMode = .left
|
|
507
|
+
layer.addSublayer(text)
|
|
508
|
+
return text
|
|
509
|
+
}()
|
|
510
|
+
private var didBuildFrameLayers = false
|
|
511
|
+
/// False until the frame has been laid out once, so the first pass settles
|
|
512
|
+
/// into place rather than animating from nothing.
|
|
513
|
+
private var didLayOutFrame = false
|
|
514
|
+
/// 0 = label resting inside the field, 1 = floated into the notch.
|
|
515
|
+
fileprivate var labelProgress: CGFloat = 0
|
|
516
|
+
/// What the frame layers were last built from. Laying out mutates sublayers,
|
|
517
|
+
/// which marks the view for layout again; without this the pass repeats
|
|
518
|
+
/// forever. It also keeps text measurement off the common layout path.
|
|
519
|
+
fileprivate struct FrameSnapshot: Equatable {
|
|
520
|
+
var bounds: CGRect = .null
|
|
521
|
+
var progress: CGFloat = -1
|
|
522
|
+
var stroke: CGFloat = -1
|
|
523
|
+
var focused = false
|
|
524
|
+
var label = ""
|
|
525
|
+
var fontSize: CGFloat = 0
|
|
526
|
+
var frame = Frame()
|
|
527
|
+
}
|
|
528
|
+
fileprivate var lastFrameSnapshot = FrameSnapshot()
|
|
529
|
+
fileprivate lazy var fonts = FontSet.shared(for: Typography(), traits: traitCollection)
|
|
530
|
+
private var fontScale: CGFloat = 1
|
|
531
|
+
/// Horizontal offset (in view points) when the content is wider than the
|
|
532
|
+
/// view: it follows the caret like a UITextField's own scrolling does.
|
|
533
|
+
private var scrollX: CGFloat = 0
|
|
534
|
+
private var displayLink: CADisplayLink?
|
|
535
|
+
private var lastReportedSize: CGSize = .zero
|
|
536
|
+
/// A narrower settled size waiting for the current morph to finish before it is reported.
|
|
537
|
+
private var pendingSizeReport = false
|
|
538
|
+
private var didAutoFocus = false
|
|
539
|
+
/// Set while this view writes the field's text itself, so the change handler
|
|
540
|
+
/// can tell a programmatic set from a user edit.
|
|
541
|
+
private var isSettingText = false
|
|
542
|
+
|
|
543
|
+
fileprivate let field = HiddenTextField()
|
|
544
|
+
/// Built the first time `multiline` is set, so a single-line field never
|
|
545
|
+
/// pays for it.
|
|
546
|
+
fileprivate lazy var textView: HiddenTextView = {
|
|
547
|
+
let view = HiddenTextView()
|
|
548
|
+
view.owner = self
|
|
549
|
+
view.delegate = self
|
|
550
|
+
view.backgroundColor = .clear
|
|
551
|
+
view.textContainer.lineFragmentPadding = 0
|
|
552
|
+
view.textContainerInset = .zero
|
|
553
|
+
view.contentInsetAdjustmentBehavior = .never
|
|
554
|
+
view.isHidden = true
|
|
555
|
+
insertSubview(view, aboveSubview: field)
|
|
556
|
+
return view
|
|
557
|
+
}()
|
|
558
|
+
/// True once `textView` has been built; reading the lazy var would build it.
|
|
559
|
+
private var didBuildTextView = false
|
|
560
|
+
/// The width the multiline height was last measured against.
|
|
561
|
+
private var lastMeasuredWidth: CGFloat = 0
|
|
562
|
+
/// Scaled and aligned container for the content (font space).
|
|
563
|
+
private let contentLayer = CALayer()
|
|
564
|
+
/// Clips glyphs to the line box, extended sideways so glyphs sliding in the
|
|
565
|
+
/// margins are not cut; its mask fades the top and bottom edges.
|
|
566
|
+
private let clipLayer = CALayer()
|
|
567
|
+
private let edgeMask = CAGradientLayer()
|
|
568
|
+
private let caretLayer = CALayer()
|
|
569
|
+
/// One layer per live engine glyph id, with what it was rasterized for.
|
|
570
|
+
/// `topOffset` is the affix's baseline correction (`FontSet.top` with the
|
|
571
|
+
/// line top at 0), a pure function of the role and text, so a frame neither
|
|
572
|
+
/// rebuilds the text from the code point nor measures ink.
|
|
573
|
+
private struct GlyphEntry {
|
|
574
|
+
let layer: CALayer
|
|
575
|
+
let topOffset: CGFloat
|
|
576
|
+
/// The render pass that last saw this glyph; one a pass missed has left.
|
|
577
|
+
var generation: UInt
|
|
578
|
+
}
|
|
579
|
+
private var glyphLayers: [Int64: GlyphEntry] = [:]
|
|
580
|
+
private var renderGeneration: UInt = 0
|
|
581
|
+
/// Where the content box sits in the bounds, as of the last render.
|
|
582
|
+
private var placement: (origin: CGPoint, scale: CGFloat) = (.zero, 1)
|
|
583
|
+
/// Last selection handed to `onSelectionChange`, so it only fires on a move.
|
|
584
|
+
private var lastReportedSelection: (Int, Int)?
|
|
585
|
+
|
|
586
|
+
// MARK: - Lifecycle
|
|
587
|
+
|
|
588
|
+
override init(frame: CGRect) {
|
|
589
|
+
super.init(frame: frame)
|
|
590
|
+
isOpaque = false
|
|
591
|
+
backgroundColor = .clear
|
|
592
|
+
clipsToBounds = false
|
|
593
|
+
|
|
594
|
+
field.owner = self
|
|
595
|
+
field.delegate = self
|
|
596
|
+
field.borderStyle = .none
|
|
597
|
+
field.backgroundColor = .clear
|
|
598
|
+
field.textColor = .clear
|
|
599
|
+
field.adjustsFontSizeToFitWidth = false
|
|
600
|
+
field.clearButtonMode = .never
|
|
601
|
+
field.addTarget(self, action: #selector(fieldEditingChanged), for: .editingChanged)
|
|
602
|
+
addSubview(field)
|
|
603
|
+
|
|
604
|
+
contentLayer.anchorPoint = .zero
|
|
605
|
+
contentLayer.contentsScale = fonts.renderScale
|
|
606
|
+
layer.addSublayer(contentLayer)
|
|
607
|
+
|
|
608
|
+
clipLayer.anchorPoint = .zero
|
|
609
|
+
clipLayer.masksToBounds = true
|
|
610
|
+
edgeMask.startPoint = CGPoint(x: 0.5, y: 0)
|
|
611
|
+
edgeMask.endPoint = CGPoint(x: 0.5, y: 1)
|
|
612
|
+
edgeMask.colors = [UIColor.clear.cgColor, UIColor.black.cgColor, UIColor.black.cgColor, UIColor.clear.cgColor]
|
|
613
|
+
clipLayer.mask = edgeMask
|
|
614
|
+
contentLayer.addSublayer(clipLayer)
|
|
615
|
+
|
|
616
|
+
caretLayer.cornerRadius = 1
|
|
617
|
+
caretLayer.isHidden = true
|
|
618
|
+
contentLayer.addSublayer(caretLayer)
|
|
619
|
+
|
|
620
|
+
engine.setTiming(timing.duration, timing.easing, timing.bounce)
|
|
621
|
+
engine.setEffect(timing.effect)
|
|
622
|
+
formatter.setFormat(Int32(format.fractionDigits), Int32(format.maxIntegerDigits),
|
|
623
|
+
std.string(format.groupingSeparator), std.string(format.decimalSeparator))
|
|
624
|
+
applyFonts()
|
|
625
|
+
applyTraits(previous: traits)
|
|
626
|
+
|
|
627
|
+
NotificationCenter.default.addObserver(
|
|
628
|
+
self, selector: #selector(contentSizeCategoryDidChange),
|
|
629
|
+
name: UIContentSizeCategory.didChangeNotification, object: nil
|
|
630
|
+
)
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
@available(*, unavailable)
|
|
634
|
+
required init?(coder: NSCoder) {
|
|
635
|
+
fatalError("init(coder:) is not supported")
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
deinit {
|
|
639
|
+
displayLink?.invalidate()
|
|
640
|
+
NotificationCenter.default.removeObserver(self)
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/// React Native's `testID` lands on this view; the field is what tools and
|
|
644
|
+
/// VoiceOver interact with, so it carries the identifier.
|
|
645
|
+
override var accessibilityIdentifier: String? {
|
|
646
|
+
didSet { field.accessibilityIdentifier = accessibilityIdentifier }
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/// Fabric applies `testID`, `accessibilityLabel` and the react tag to the
|
|
650
|
+
/// *component view* that hosts this one, not to this view, so they are copied
|
|
651
|
+
/// down to the hidden field — it is the element VoiceOver and e2e tools see.
|
|
652
|
+
/// The react tag also has to sit on this view: react-native-keyboard-controller
|
|
653
|
+
/// reports the focused input as `firstResponder.superview.tag`, and this view
|
|
654
|
+
/// is the field's superview.
|
|
655
|
+
private func syncAccessibilityFromHost() {
|
|
656
|
+
guard let host = superview else { return }
|
|
657
|
+
if tag != host.tag { tag = host.tag }
|
|
658
|
+
// `traits.testID` is the explicit prop; the host's own identifier is the
|
|
659
|
+
// fallback for a caller that set it natively.
|
|
660
|
+
let identifier = traits.testID ?? accessibilityIdentifier ?? host.accessibilityIdentifier
|
|
661
|
+
if field.accessibilityIdentifier != identifier { field.accessibilityIdentifier = identifier }
|
|
662
|
+
// A floating label is the field's visible name, but it is drawn in a layer
|
|
663
|
+
// - VoiceOver cannot see it. Without this a field whose only name is its
|
|
664
|
+
// `label` is announced as an unnamed text field. An explicit
|
|
665
|
+
// `accessibilityLabel` still wins.
|
|
666
|
+
let label = traits.accessibilityLabel ?? host.accessibilityLabel
|
|
667
|
+
?? (inputFrame.hasLabel ? inputFrame.label : nil)
|
|
668
|
+
if field.accessibilityLabel != label { field.accessibilityLabel = label }
|
|
669
|
+
let hint = host.accessibilityHint
|
|
670
|
+
if field.accessibilityHint != hint { field.accessibilityHint = hint }
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/// Gives the field UIKit's own placeholder so an *empty* field still has an
|
|
674
|
+
/// accessibility value (VoiceOver reads it, e2e tools can find it). It is
|
|
675
|
+
/// drawn in clear: the overlay already draws the placeholder glyphs itself.
|
|
676
|
+
fileprivate func syncAccessibilityPlaceholder() {
|
|
677
|
+
let placeholder = effectivePlaceholder
|
|
678
|
+
// Drawn for real in plain mode; in morph mode the overlay draws it and the
|
|
679
|
+
// field's own copy exists only so an empty field still has an
|
|
680
|
+
// accessibility value, hence clear.
|
|
681
|
+
let color = traits.plain ? typography.placeholderColor : UIColor.clear
|
|
682
|
+
let unchanged = field.attributedPlaceholder?.string == placeholder
|
|
683
|
+
&& field.attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor == color
|
|
684
|
+
guard !unchanged || placeholder.isEmpty != (field.attributedPlaceholder == nil) else { return }
|
|
685
|
+
field.attributedPlaceholder = placeholder.isEmpty
|
|
686
|
+
? nil
|
|
687
|
+
: NSAttributedString(string: placeholder, attributes: [.foregroundColor: color])
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
override func didMoveToSuperview() {
|
|
691
|
+
super.didMoveToSuperview()
|
|
692
|
+
syncAccessibilityFromHost()
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
override func layoutSubviews() {
|
|
696
|
+
super.layoutSubviews()
|
|
697
|
+
// `.auto` alignment is resolved against the layout direction, which is only
|
|
698
|
+
// known once there is a superview chain to walk.
|
|
699
|
+
if isRTL != resolvedForRTL {
|
|
700
|
+
resolvedForRTL = isRTL
|
|
701
|
+
applyLayoutDirection()
|
|
702
|
+
}
|
|
703
|
+
field.frame = bounds
|
|
704
|
+
if didBuildTextView { textView.frame = bounds }
|
|
705
|
+
// Where the text wraps - and so how tall the box is - depends on the width,
|
|
706
|
+
// and layout is the first thing to know it. Measuring from inside the pass
|
|
707
|
+
// would re-enter it, so the report goes out after this one lands.
|
|
708
|
+
if traits.multiline, bounds.width != lastMeasuredWidth {
|
|
709
|
+
lastMeasuredWidth = bounds.width
|
|
710
|
+
DispatchQueue.main.async { [weak self] in self?.reportIntrinsicSize() }
|
|
711
|
+
}
|
|
712
|
+
// UIKit makes the field first responder - and lays us out for the keyboard
|
|
713
|
+
// - before it calls the delegate, so this pass is usually the first to see
|
|
714
|
+
// the label needing to float. If it committed the move without animating,
|
|
715
|
+
// `textFieldDidBeginEditing` would arrive to find nothing left to change
|
|
716
|
+
// and the label would snap. Layout animates a progress change too; an
|
|
717
|
+
// ordinary layout does not change progress, so nothing animates then. Only
|
|
718
|
+
// the very first pass is silent, so a field mounted focused starts settled.
|
|
719
|
+
if wantsFrameDrawing { layoutFrame(animated: didLayOutFrame) }
|
|
720
|
+
// Props are applied after the view is mounted, so the host's identifier and
|
|
721
|
+
// tag are only reliable once it has been laid out.
|
|
722
|
+
syncAccessibilityFromHost()
|
|
723
|
+
// The shrink-to-fit scale and alignment depend on the bounds.
|
|
724
|
+
render()
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/// Re-applies everything that was resolved against the layout direction:
|
|
728
|
+
/// `.auto` alignment, which edge the affixes sit at (the engine mirrors them
|
|
729
|
+
/// in the overlay, `leftView` / `rightView` swap in a plain field), and the
|
|
730
|
+
/// frame's label, which `layoutFrame` places at the start edge.
|
|
731
|
+
private func applyLayoutDirection() {
|
|
732
|
+
engine.setRightToLeft(isRTL)
|
|
733
|
+
field.textAlignment = traits.plain ? textAlignment(for: alignment) : .left
|
|
734
|
+
if didBuildTextView {
|
|
735
|
+
textView.textAlignment = textAlignment(for: alignment)
|
|
736
|
+
applyTextViewTypography()
|
|
737
|
+
}
|
|
738
|
+
updateFieldInsets()
|
|
739
|
+
render()
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
override func didMoveToWindow() {
|
|
743
|
+
super.didMoveToWindow()
|
|
744
|
+
syncAccessibilityFromHost()
|
|
745
|
+
// The fonts were built against whatever traits the view had when it was
|
|
746
|
+
// made; the window's are the ones that count.
|
|
747
|
+
if window != nil { syncWithTraits(appearanceChanged: false) }
|
|
748
|
+
maybeAutoFocus()
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
|
|
752
|
+
super.traitCollectionDidChange(previousTraitCollection)
|
|
753
|
+
let appearanceChanged = previousTraitCollection.map { traitCollection.hasDifferentColorAppearance(comparedTo: $0) } ?? true
|
|
754
|
+
syncWithTraits(appearanceChanged: appearanceChanged)
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
/// Everything drawn through Core Animation bakes the view's traits in: the
|
|
758
|
+
/// glyph images carry the resolved text colour and the pixel density, and
|
|
759
|
+
/// the frame's stroke, fill and label are `CGColor`s. A light/dark switch
|
|
760
|
+
/// (`.label`, `.separator` and the rest are dynamic) or a move to another
|
|
761
|
+
/// display rebuilds them, settled rather than animated: the field has not
|
|
762
|
+
/// changed, only what it is drawn with.
|
|
763
|
+
private func syncWithTraits(appearanceChanged: Bool) {
|
|
764
|
+
let scale = max(1, traitCollection.displayScale)
|
|
765
|
+
let fontsStale = scale != fonts.renderScale
|
|
766
|
+
|| typography.color.resolvedColor(with: traitCollection) != fonts.color
|
|
767
|
+
|| typography.placeholderColor.resolvedColor(with: traitCollection) != fonts.placeholderColor
|
|
768
|
+
guard fontsStale || appearanceChanged else { return }
|
|
769
|
+
if scale != contentLayer.contentsScale {
|
|
770
|
+
contentLayer.contentsScale = scale
|
|
771
|
+
if didBuildFrameLayers { labelLayer.contentsScale = scale }
|
|
772
|
+
}
|
|
773
|
+
if fontsStale { rebuildFonts() }
|
|
774
|
+
// The frame's colours are resolved as it is laid out, and an unchanged
|
|
775
|
+
// geometry would be skipped: forget the last one so this pass redraws.
|
|
776
|
+
lastFrameSnapshot = FrameSnapshot()
|
|
777
|
+
if wantsFrameDrawing { layoutFrame(animated: false) }
|
|
778
|
+
updateCaret()
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
/// `autoFocus`, taken **synchronously** as soon as the view has a window and
|
|
782
|
+
/// the prop has arrived — whichever of the two happens last.
|
|
783
|
+
///
|
|
784
|
+
/// Pushing a screen blurs the field on the screen being covered, and iOS
|
|
785
|
+
/// starts animating the keyboard away as soon as nothing is first responder.
|
|
786
|
+
/// Claiming it in the same runloop turn beats that: UIKit swaps the keyboard
|
|
787
|
+
/// in place, so a different keyboard type appears with no dismiss and
|
|
788
|
+
/// re-present. That is what React Native's own `TextInput` does. Deferring by
|
|
789
|
+
/// even one turn loses the race and costs a full hide plus show animation.
|
|
790
|
+
/// If UIKit declines — the view is in a window but not ready to accept first
|
|
791
|
+
/// responder yet — retry next turn, which is correct, just not seamless.
|
|
792
|
+
private func maybeAutoFocus() {
|
|
793
|
+
guard window != nil, traits.autoFocus, traits.editable, !didAutoFocus else { return }
|
|
794
|
+
didAutoFocus = true
|
|
795
|
+
if editor.becomeFirstResponder() { return }
|
|
796
|
+
DispatchQueue.main.async { [weak self] in
|
|
797
|
+
guard let self, self.window != nil else { return }
|
|
798
|
+
self.editor.becomeFirstResponder()
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
@objc private func contentSizeCategoryDidChange() {
|
|
803
|
+
guard typography.allowFontScaling else { return }
|
|
804
|
+
rebuildFonts()
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
func stopAnimation() {
|
|
808
|
+
stopDisplayLink()
|
|
809
|
+
stopBlink()
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
/// Returns the view to its pristine state so Fabric can reuse it for a new
|
|
813
|
+
/// element (`RecyclableView`). Props are re-applied by Nitro afterwards.
|
|
814
|
+
func resetForRecycle() {
|
|
815
|
+
worklets = Worklets()
|
|
816
|
+
if editor.isFirstResponder { editor.resignFirstResponder() }
|
|
817
|
+
stopDisplayLink()
|
|
818
|
+
stopBlink()
|
|
819
|
+
engine.reset()
|
|
820
|
+
fontScale = 1
|
|
821
|
+
lastReportedSize = .zero
|
|
822
|
+
lastReportedSelection = nil
|
|
823
|
+
pendingSizeReport = false
|
|
824
|
+
didAutoFocus = false
|
|
825
|
+
eventCount = 0
|
|
826
|
+
isSettingText = true
|
|
827
|
+
field.text = ""
|
|
828
|
+
isSettingText = false
|
|
829
|
+
inputFrame = Frame()
|
|
830
|
+
labelProgress = 0
|
|
831
|
+
lastFrameSnapshot = FrameSnapshot()
|
|
832
|
+
format = Format()
|
|
833
|
+
typography = Typography()
|
|
834
|
+
timing = Timing()
|
|
835
|
+
traits = Traits()
|
|
836
|
+
alignment = .auto
|
|
837
|
+
// `onTextChange`, `onFocusChange`, `onSubmit` and `onIntrinsicSizeChange`
|
|
838
|
+
// are the hybrid's wiring, not the element's props: they stay across
|
|
839
|
+
// recycling (the hybrid clears its own callback props).
|
|
840
|
+
clearGlyphLayers()
|
|
841
|
+
caretLayer.isHidden = true
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
// MARK: - Public API
|
|
845
|
+
|
|
846
|
+
func focus() {
|
|
847
|
+
guard traits.editable else { return }
|
|
848
|
+
editor.becomeFirstResponder()
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
func blur() {
|
|
852
|
+
editor.resignFirstResponder()
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
/// Moves the caret/selection to `start`..`end`, in code points.
|
|
856
|
+
func setSelection(start: Int, end: Int) {
|
|
857
|
+
let count = text.unicodeScalars.count
|
|
858
|
+
let lower = min(max(0, start), count)
|
|
859
|
+
let upper = min(max(lower, end), count)
|
|
860
|
+
guard let from = field.position(from: field.beginningOfDocument, offset: utf16Offset(ofCodePoint: lower)),
|
|
861
|
+
let to = field.position(from: field.beginningOfDocument, offset: utf16Offset(ofCodePoint: upper)),
|
|
862
|
+
let range = field.textRange(from: from, to: to) else { return }
|
|
863
|
+
guard field.selectedTextRange != range else { return }
|
|
864
|
+
field.selectedTextRange = range
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
/// UITextField works in UTF-16; the props and callbacks speak code points.
|
|
868
|
+
private func utf16Offset(ofCodePoint index: Int) -> Int {
|
|
869
|
+
guard index > 0 else { return 0 }
|
|
870
|
+
let scalars = Array(text.unicodeScalars)
|
|
871
|
+
let slice = scalars.prefix(min(index, scalars.count))
|
|
872
|
+
return String(String.UnicodeScalarView(slice)).utf16.count
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
/// Replaces the text (formatted in number mode, truncated to `maxLength` in
|
|
876
|
+
/// text mode), caret at the end. Returns false when nothing changed.
|
|
877
|
+
@discardableResult
|
|
878
|
+
func setText(_ newText: String, reason: ChangeReason) -> Bool {
|
|
879
|
+
var normalized = normalized(newText)
|
|
880
|
+
if worklets.transform != 0 {
|
|
881
|
+
let count = normalized.unicodeScalars.count
|
|
882
|
+
let (selStart, selEnd) = selectionCodePoints()
|
|
883
|
+
let result = margelo.nitro.nitroinput.nitroinputworklets.runTransform(
|
|
884
|
+
Int32(worklets.transform), std.string(normalized), std.string(text), Int32(count), Int32(count), Int32(selStart), Int32(selEnd))
|
|
885
|
+
if result.applied { normalized = String(result.text) }
|
|
886
|
+
}
|
|
887
|
+
// The first application always commits so the engine has the (possibly
|
|
888
|
+
// empty) text and its placeholder to draw.
|
|
889
|
+
let changed = normalized != text
|
|
890
|
+
guard changed || !engine.hasText() else { return false }
|
|
891
|
+
isSettingText = true
|
|
892
|
+
if traits.multiline, didBuildTextView {
|
|
893
|
+
// Multiline holds its own text; the formatter is single-line by
|
|
894
|
+
// definition, so `normalized` is just the text itself here.
|
|
895
|
+
if textView.text != normalized { textView.text = normalized }
|
|
896
|
+
applyTextViewTypography()
|
|
897
|
+
}
|
|
898
|
+
field.text = normalized
|
|
899
|
+
field.selectedTextRange = field.textRange(from: field.endOfDocument, to: field.endOfDocument)
|
|
900
|
+
isSettingText = false
|
|
901
|
+
textDidChange(caret: -1, reason: reason, changed: changed)
|
|
902
|
+
return true
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
func setValue(_ value: Double, reason: ChangeReason) {
|
|
906
|
+
let formatted = value.isFinite ? String(formatter.format(value)) : ""
|
|
907
|
+
setText(formatted, reason: reason)
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
func clear(reason: ChangeReason) {
|
|
911
|
+
setText("", reason: reason)
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
/// Re-sends the last reported intrinsic size (e.g. after a listener was attached).
|
|
915
|
+
func resendIntrinsicSize() {
|
|
916
|
+
guard lastReportedSize != .zero else { return }
|
|
917
|
+
onIntrinsicSizeChange?(lastReportedSize)
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
private func normalized(_ raw: String) -> String {
|
|
921
|
+
switch format.mode {
|
|
922
|
+
case .number:
|
|
923
|
+
return String(formatter.normalize(std.string(raw)).text)
|
|
924
|
+
case .mask:
|
|
925
|
+
let count = Int32(raw.unicodeScalars.count)
|
|
926
|
+
let result = maskEngine.apply(std.string(raw), count, true, format.maskAutocomplete, false)
|
|
927
|
+
return String(result.formattedText)
|
|
928
|
+
case .text:
|
|
929
|
+
return Self.truncated(raw, to: format.maxLength)
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
private static func truncated(_ text: String, to maxLength: Int) -> String {
|
|
934
|
+
guard maxLength > 0, text.unicodeScalars.count > maxLength else { return text }
|
|
935
|
+
var view = String.UnicodeScalarView()
|
|
936
|
+
view.append(contentsOf: text.unicodeScalars.prefix(maxLength))
|
|
937
|
+
return String(view)
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
// MARK: - Configuration application
|
|
941
|
+
|
|
942
|
+
private func applyFormat(previous: Format) {
|
|
943
|
+
if format.mode == .number {
|
|
944
|
+
formatter.setFormat(Int32(max(0, format.fractionDigits)), Int32(max(1, format.maxIntegerDigits)),
|
|
945
|
+
std.string(format.groupingSeparator), std.string(format.decimalSeparator))
|
|
946
|
+
}
|
|
947
|
+
if format.mode == .mask, format.mask != previous.mask || format.maskNotations != previous.maskNotations
|
|
948
|
+
|| previous.mode != .mask {
|
|
949
|
+
maskEngine.clearNotations()
|
|
950
|
+
for notation in format.maskNotations {
|
|
951
|
+
maskEngine.addNotation(std.string(notation.character), std.string(notation.characterSet),
|
|
952
|
+
notation.isOptional)
|
|
953
|
+
}
|
|
954
|
+
// A bad pattern leaves the engine inactive; the field then behaves as
|
|
955
|
+
// plain text rather than refusing every keystroke.
|
|
956
|
+
_ = maskEngine.setFormat(std.string(format.mask))
|
|
957
|
+
}
|
|
958
|
+
updateFieldInsets()
|
|
959
|
+
syncAccessibilityPlaceholder()
|
|
960
|
+
// A changed formatter or mode reformats what is in the field.
|
|
961
|
+
let formatChanged = format.mode != previous.mode || format.fractionDigits != previous.fractionDigits
|
|
962
|
+
|| format.maxIntegerDigits != previous.maxIntegerDigits || format.groupingSeparator != previous.groupingSeparator
|
|
963
|
+
|| format.decimalSeparator != previous.decimalSeparator || format.maxLength != previous.maxLength
|
|
964
|
+
|| format.mask != previous.mask || format.maskNotations != previous.maskNotations
|
|
965
|
+
if formatChanged {
|
|
966
|
+
let normalizedText = normalized(text)
|
|
967
|
+
if normalizedText != text {
|
|
968
|
+
isSettingText = true
|
|
969
|
+
field.text = normalizedText
|
|
970
|
+
isSettingText = false
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
applyKeyboardTraitsForMode()
|
|
974
|
+
// A plain field has nothing in the engine and still has a width to report.
|
|
975
|
+
if engine.hasText() || traits.plain {
|
|
976
|
+
feedEngine(caret: -1)
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
private func rebuildFonts() {
|
|
981
|
+
fonts = FontSet.shared(for: typography, traits: traitCollection)
|
|
982
|
+
fontScale = 1
|
|
983
|
+
// Every cached glyph image belongs to the old font set.
|
|
984
|
+
clearGlyphLayers()
|
|
985
|
+
applyFonts()
|
|
986
|
+
if engine.hasText() || traits.plain {
|
|
987
|
+
feedEngine(caret: -1)
|
|
988
|
+
} else {
|
|
989
|
+
render()
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
private func applyFonts() {
|
|
994
|
+
field.font = fonts.body
|
|
995
|
+
var attributes = field.defaultTextAttributes
|
|
996
|
+
attributes[.kern] = 0
|
|
997
|
+
attributes[.font] = fonts.body
|
|
998
|
+
attributes[.foregroundColor] = traits.plain ? typography.color : UIColor.clear
|
|
999
|
+
field.defaultTextAttributes = attributes
|
|
1000
|
+
updateFieldInsets()
|
|
1001
|
+
applyTextViewTypography()
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
/// In morph mode the overlay draws the prefix and suffix, so the field only
|
|
1005
|
+
/// has to reserve the space. In `plain` mode nothing is drawing them, so the
|
|
1006
|
+
/// field carries them itself as its left/right accessory views — UIKit insets
|
|
1007
|
+
/// the text for those on its own.
|
|
1008
|
+
private func updateFieldInsets() {
|
|
1009
|
+
// A floated label sits half above the top edge, so the text starts lower.
|
|
1010
|
+
field.topInset = frameTopInset
|
|
1011
|
+
let side = frameSideInset
|
|
1012
|
+
// The prefix sits at the start edge and the suffix at the end. UIKit never
|
|
1013
|
+
// mirrors `leftView` / `rightView`, so under a right-to-left layout the
|
|
1014
|
+
// two accessories - and the room the overlay keeps for them - swap sides.
|
|
1015
|
+
let rtl = isRTL
|
|
1016
|
+
if traits.plain {
|
|
1017
|
+
field.leftInset = side
|
|
1018
|
+
field.rightInset = side
|
|
1019
|
+
let prefixLabel = affixLabel(format.prefix, role: .prefix,
|
|
1020
|
+
reusing: (rtl ? field.rightView : field.leftView) as? UILabel)
|
|
1021
|
+
let suffixLabel = affixLabel(format.suffix, role: .suffix,
|
|
1022
|
+
reusing: (rtl ? field.leftView : field.rightView) as? UILabel)
|
|
1023
|
+
field.leftView = rtl ? suffixLabel : prefixLabel
|
|
1024
|
+
field.rightView = rtl ? prefixLabel : suffixLabel
|
|
1025
|
+
field.leftViewMode = field.leftView == nil ? .never : .always
|
|
1026
|
+
field.rightViewMode = field.rightView == nil ? .never : .always
|
|
1027
|
+
} else {
|
|
1028
|
+
field.leftView = nil
|
|
1029
|
+
field.rightView = nil
|
|
1030
|
+
field.leftViewMode = .never
|
|
1031
|
+
field.rightViewMode = .never
|
|
1032
|
+
let prefixRoom = affixWidth(format.prefix, role: .prefix)
|
|
1033
|
+
let suffixRoom = affixWidth(format.suffix, role: .suffix)
|
|
1034
|
+
field.leftInset = side + (rtl ? suffixRoom : prefixRoom)
|
|
1035
|
+
field.rightInset = side + (rtl ? prefixRoom : suffixRoom)
|
|
1036
|
+
}
|
|
1037
|
+
field.setNeedsLayout()
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
private func affixLabel(_ affix: String, role: GlyphRole, reusing existing: UILabel?) -> UILabel? {
|
|
1041
|
+
guard !affix.isEmpty else { return nil }
|
|
1042
|
+
let label = existing ?? UILabel()
|
|
1043
|
+
label.font = fonts.font(for: role)
|
|
1044
|
+
label.textColor = typography.color
|
|
1045
|
+
if label.text != affix { label.text = affix }
|
|
1046
|
+
label.sizeToFit()
|
|
1047
|
+
return label
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
private func affixWidth(_ affix: String, role: GlyphRole) -> CGFloat {
|
|
1051
|
+
affix.unicodeScalars.reduce(CGFloat(0)) { $0 + fonts.width(of: String($1), role: role) }
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
/// Swaps which backing view is showing, and mirrors onto the text view the
|
|
1055
|
+
/// settings that matter to it. Everything the single-line path does is left
|
|
1056
|
+
/// alone: a field that never sets `multiline` never builds the text view and
|
|
1057
|
+
/// never takes this branch.
|
|
1058
|
+
private func applyMultiline() {
|
|
1059
|
+
guard traits.multiline || didBuildTextView else { return }
|
|
1060
|
+
didBuildTextView = true
|
|
1061
|
+
let on = traits.multiline
|
|
1062
|
+
textView.isHidden = !on
|
|
1063
|
+
textView.isUserInteractionEnabled = on && traits.editable
|
|
1064
|
+
field.isHidden = on
|
|
1065
|
+
field.isUserInteractionEnabled = !on && traits.editable
|
|
1066
|
+
guard on else { return }
|
|
1067
|
+
|
|
1068
|
+
textView.frame = bounds
|
|
1069
|
+
textView.keyboardType = traits.keyboardType
|
|
1070
|
+
textView.returnKeyType = traits.returnKeyType
|
|
1071
|
+
textView.autocapitalizationType = traits.autocapitalization
|
|
1072
|
+
textView.autocorrectionType = traits.autocorrect ? .yes : .no
|
|
1073
|
+
textView.spellCheckingType = traits.spellCheck ? .yes : .no
|
|
1074
|
+
textView.isEditable = traits.editable
|
|
1075
|
+
textView.isSelectable = true
|
|
1076
|
+
textView.keyboardAppearance = traits.keyboardAppearance
|
|
1077
|
+
textView.textContentType = traits.textContentType
|
|
1078
|
+
textView.isSecureTextEntry = traits.secureTextEntry
|
|
1079
|
+
textView.showSoftInputOnFocus = traits.showSoftInputOnFocus
|
|
1080
|
+
textView.tintColor = traits.caretColor ?? traits.selectionColor
|
|
1081
|
+
textView.hidesNativeCaret = traits.caretHidden
|
|
1082
|
+
textView.isScrollEnabled = traits.scrollEnabled
|
|
1083
|
+
textView.textAlignment = textAlignment(for: alignment)
|
|
1084
|
+
textView.inputAccessoryView = field.inputAccessoryView
|
|
1085
|
+
applyTextViewTypography()
|
|
1086
|
+
// `multiline` forces plain on the JS side, so the overlay is already off;
|
|
1087
|
+
// the text view carries the real text from here on.
|
|
1088
|
+
if textView.text != text { textView.text = text }
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
/// Font, colour, and the line box. `UITextView` stacks any extra leading
|
|
1092
|
+
/// above the line, so the glyphs are pushed back down by half of it -
|
|
1093
|
+
/// including when the line box is *tighter* than the font, which is the case
|
|
1094
|
+
/// `RCTApplyBaselineOffsetForRange` returns early on.
|
|
1095
|
+
private func applyTextViewTypography() {
|
|
1096
|
+
guard didBuildTextView else { return }
|
|
1097
|
+
let font = fonts.font(for: .body)
|
|
1098
|
+
textView.font = font
|
|
1099
|
+
textView.textColor = typography.color
|
|
1100
|
+
textView.placeholder = effectivePlaceholder
|
|
1101
|
+
textView.placeholderColor = typography.placeholderColor
|
|
1102
|
+
|
|
1103
|
+
var attributes: [NSAttributedString.Key: Any] = [.font: font]
|
|
1104
|
+
attributes[.foregroundColor] = typography.color
|
|
1105
|
+
let style = NSMutableParagraphStyle()
|
|
1106
|
+
style.alignment = textAlignment(for: alignment)
|
|
1107
|
+
if typography.lineHeight > 0 {
|
|
1108
|
+
// TextKit gives a line fragment one ascent, and it is the font's however
|
|
1109
|
+
// tall the fragment is told to be, so neither direction centres itself.
|
|
1110
|
+
let extra = typography.lineHeight - font.lineHeight
|
|
1111
|
+
if extra >= 0 {
|
|
1112
|
+
// Looser: `maximumLineHeight` would make the fragment taller and leave
|
|
1113
|
+
// the glyphs sitting at the top of it. Putting the room *between* the
|
|
1114
|
+
// lines instead keeps the pitch exactly `lineHeight`, and half of it
|
|
1115
|
+
// above the first line (`lineBoxPadding`) centres every glyph in its
|
|
1116
|
+
// own box.
|
|
1117
|
+
style.lineSpacing = extra
|
|
1118
|
+
} else {
|
|
1119
|
+
// Tighter - the case `RCTApplyBaselineOffsetForRange` returns early on,
|
|
1120
|
+
// which is why a compressed `lineHeight` rides off-centre on a
|
|
1121
|
+
// `TextInput`. Compressing the fragment clips it from the top (TextKit
|
|
1122
|
+
// keeps the descender and drops the baseline to `lineHeight` less it),
|
|
1123
|
+
// so the text rides high by half of what was taken away. `.baselineOffset`
|
|
1124
|
+
// is the wrong lever for it: it comes out of the fragment TextKit just
|
|
1125
|
+
// sized, which drags the pitch down with it - 14 measured 12 - so the
|
|
1126
|
+
// correction goes on the container inset, where the pitch cannot see it.
|
|
1127
|
+
style.minimumLineHeight = typography.lineHeight
|
|
1128
|
+
style.maximumLineHeight = typography.lineHeight
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
attributes[.paragraphStyle] = style
|
|
1132
|
+
textView.typingAttributes = attributes
|
|
1133
|
+
if !textView.text.isEmpty {
|
|
1134
|
+
let selected = textView.selectedRange
|
|
1135
|
+
textView.attributedText = NSAttributedString(string: textView.text, attributes: attributes)
|
|
1136
|
+
textView.selectedRange = selected
|
|
1137
|
+
}
|
|
1138
|
+
applyTextViewInsets()
|
|
1139
|
+
textView.setNeedsDisplay()
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
/// How far the text as a whole has to come down to sit in the middle of its
|
|
1143
|
+
/// line boxes. Loose: the first line needs the room the others got below them
|
|
1144
|
+
/// as `lineSpacing`. Tight: it has to make up what compressing the fragment
|
|
1145
|
+
/// clipped off the top. Both are the same for every line, so one inset does
|
|
1146
|
+
/// it - and both are half the difference, which is why the sign does not
|
|
1147
|
+
/// reach this far. What differs is where the other half goes, which is
|
|
1148
|
+
/// `lineBoxTrailing`.
|
|
1149
|
+
private var lineBoxPadding: CGFloat {
|
|
1150
|
+
guard typography.lineHeight > 0 else { return 0 }
|
|
1151
|
+
return abs(typography.lineHeight - fonts.font(for: .body).lineHeight) / 2
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
/// The other half: room *added* below a loose box, room *taken back* from a
|
|
1155
|
+
/// tight one - so the text view's content is exactly the height the field
|
|
1156
|
+
/// reports either way, and a box showing all its lines cannot be scrolled.
|
|
1157
|
+
private var lineBoxTrailing: CGFloat {
|
|
1158
|
+
guard typography.lineHeight > 0 else { return 0 }
|
|
1159
|
+
return typography.lineHeight >= fonts.font(for: .body).lineHeight ? lineBoxPadding : -lineBoxPadding
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
/// The room a framed multiline field keeps above and below its text. It has
|
|
1163
|
+
/// to carry its own: the single-line path is centred inside whatever height
|
|
1164
|
+
/// the caller gives it, whereas this one reports its own height, so nothing
|
|
1165
|
+
/// else is going to put space between the text and the stroke.
|
|
1166
|
+
private var frameVerticalInset: (top: CGFloat, bottom: CGFloat) {
|
|
1167
|
+
guard inputFrame.draws else { return (0, 0) }
|
|
1168
|
+
// Not `frameSideInset`: that is `max(16, cornerRadius + 8)` because the
|
|
1169
|
+
// *label* has to clear the corner curve, which is a horizontal problem.
|
|
1170
|
+
// The text sits in the middle of the box, nowhere near a corner, so a
|
|
1171
|
+
// rounder frame must not make the field taller. Material's outlined field
|
|
1172
|
+
// pads 16 either way whatever its radius.
|
|
1173
|
+
let side = Self.framePadding
|
|
1174
|
+
// An outlined field's floated label straddles the top stroke, so half of it
|
|
1175
|
+
// hangs back into the box. `frameTopInset` discounts that on purpose - a
|
|
1176
|
+
// single line is centred, far below it - but a multiline field's first line
|
|
1177
|
+
// starts at the top, exactly where the label is, so here it has to be paid.
|
|
1178
|
+
let overhang = inputFrame.hasLabel && inputFrame.variant != .filled ? floatedLabelSize / 2 : 0
|
|
1179
|
+
return (side + frameTopInset + overhang, side)
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
/// A framed multiline field has to carry its own padding. The single-line
|
|
1183
|
+
/// path never needed one: it is centred inside whatever height the caller
|
|
1184
|
+
/// gives it, whereas this one reports its own height, so nothing else is
|
|
1185
|
+
/// going to put room between the text and the stroke.
|
|
1186
|
+
private func applyTextViewInsets() {
|
|
1187
|
+
guard didBuildTextView else { return }
|
|
1188
|
+
let frame = frameVerticalInset
|
|
1189
|
+
textView.textContainerInset = UIEdgeInsets(top: frame.top + lineBoxPadding,
|
|
1190
|
+
left: frameSideInset,
|
|
1191
|
+
bottom: frame.bottom + lineBoxTrailing,
|
|
1192
|
+
right: frameSideInset)
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
private func applyTraits(previous: Traits) {
|
|
1196
|
+
applyMultiline()
|
|
1197
|
+
field.keyboardType = traits.keyboardType
|
|
1198
|
+
field.returnKeyType = traits.returnKeyType
|
|
1199
|
+
field.isEnabled = traits.editable
|
|
1200
|
+
field.isUserInteractionEnabled = traits.editable
|
|
1201
|
+
// `tintColor` is both the caret and the selection on a UITextField. The
|
|
1202
|
+
// overlay draws its own caret, so only `plain` has a caret colour to honour
|
|
1203
|
+
// here — and `caretColor` wins over `selectionColor` when both are set.
|
|
1204
|
+
field.tintColor = traits.plain ? (traits.caretColor ?? traits.selectionColor) : traits.selectionColor
|
|
1205
|
+
field.keyboardAppearance = traits.keyboardAppearance
|
|
1206
|
+
field.enablesReturnKeyAutomatically = traits.enablesReturnKeyAutomatically
|
|
1207
|
+
field.textContentType = traits.textContentType
|
|
1208
|
+
// UIKit would draw its own bullets; the overlay masks the glyphs instead
|
|
1209
|
+
// (see `glyphs()`), so the field itself only needs the secure *behaviour*
|
|
1210
|
+
// — no autocorrect, no dictation, no screenshot of the text.
|
|
1211
|
+
if field.isSecureTextEntry != traits.secureTextEntry {
|
|
1212
|
+
field.isSecureTextEntry = traits.secureTextEntry
|
|
1213
|
+
// The mask changes what is drawn, not what is stored.
|
|
1214
|
+
if engine.hasText() || traits.plain { feedEngine(caret: -1) }
|
|
1215
|
+
}
|
|
1216
|
+
applyPlain(wasPlain: previous.plain)
|
|
1217
|
+
syncAccessibilityFromHost()
|
|
1218
|
+
field.showSoftInputOnFocus = traits.showSoftInputOnFocus
|
|
1219
|
+
field.contextMenuHidden = traits.contextMenuHidden
|
|
1220
|
+
if !traits.editable, editor.isFirstResponder {
|
|
1221
|
+
editor.resignFirstResponder()
|
|
1222
|
+
}
|
|
1223
|
+
applyKeyboardTraitsForMode()
|
|
1224
|
+
maybeAutoFocus()
|
|
1225
|
+
updateCaret()
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
/// Switches between "hidden field + overlay" and "the field draws itself".
|
|
1229
|
+
private func applyPlain(wasPlain: Bool) {
|
|
1230
|
+
let plain = traits.plain
|
|
1231
|
+
defer { syncAccessibilityPlaceholder() }
|
|
1232
|
+
field.hidesNativeCaret = !plain || traits.caretHidden
|
|
1233
|
+
if plain {
|
|
1234
|
+
stopDisplayLink()
|
|
1235
|
+
stopBlink()
|
|
1236
|
+
caretLayer.isHidden = true
|
|
1237
|
+
if contentLayer.superlayer != nil { contentLayer.removeFromSuperlayer() }
|
|
1238
|
+
clearGlyphLayers()
|
|
1239
|
+
engine.reset()
|
|
1240
|
+
field.textColor = typography.color
|
|
1241
|
+
field.textAlignment = textAlignment(for: alignment)
|
|
1242
|
+
field.adjustsFontSizeToFitWidth = typography.adjustsFontSizeToFit
|
|
1243
|
+
field.minimumFontSize = typography.adjustsFontSizeToFit
|
|
1244
|
+
? typography.fontSize * typography.minimumFontScale
|
|
1245
|
+
: 0
|
|
1246
|
+
} else {
|
|
1247
|
+
if contentLayer.superlayer == nil { layer.addSublayer(contentLayer) }
|
|
1248
|
+
field.textColor = .clear
|
|
1249
|
+
field.textAlignment = .left
|
|
1250
|
+
field.adjustsFontSizeToFitWidth = false
|
|
1251
|
+
}
|
|
1252
|
+
// The overlay used to paint the glyphs in the text colour; the field's own
|
|
1253
|
+
// attributes carry it now, so they have to be re-applied either way.
|
|
1254
|
+
var attributes = field.defaultTextAttributes
|
|
1255
|
+
attributes[.foregroundColor] = plain ? typography.color : UIColor.clear
|
|
1256
|
+
field.defaultTextAttributes = attributes
|
|
1257
|
+
updateFieldInsets()
|
|
1258
|
+
// Turning plain on tore the overlay down and reset the engine, so on the
|
|
1259
|
+
// way back it has nothing to draw until the next edit: hand it the text.
|
|
1260
|
+
if wasPlain, !plain, !engine.hasText() {
|
|
1261
|
+
feedEngine(caret: -1)
|
|
1262
|
+
}
|
|
1263
|
+
// Turning it on: the width now comes from the field, not the engine.
|
|
1264
|
+
if plain { reportIntrinsicSize() }
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
private func textAlignment(for alignment: Alignment) -> NSTextAlignment {
|
|
1268
|
+
switch alignment {
|
|
1269
|
+
case .auto: return isRTL ? .right : .left
|
|
1270
|
+
case .left: return .left
|
|
1271
|
+
case .center: return .center
|
|
1272
|
+
case .right: return .right
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
private func applyKeyboardTraitsForMode() {
|
|
1277
|
+
// A mask decides every character, so the keyboard must not second-guess it:
|
|
1278
|
+
// autocorrect would fight `shouldChangeCharactersIn` over the replacement.
|
|
1279
|
+
if format.mode == .number || format.mode == .mask {
|
|
1280
|
+
field.autocapitalizationType = .none
|
|
1281
|
+
field.autocorrectionType = .no
|
|
1282
|
+
field.spellCheckingType = .no
|
|
1283
|
+
field.smartInsertDeleteType = .no
|
|
1284
|
+
field.smartQuotesType = .no
|
|
1285
|
+
field.smartDashesType = .no
|
|
1286
|
+
} else {
|
|
1287
|
+
field.autocapitalizationType = traits.autocapitalization
|
|
1288
|
+
field.autocorrectionType = traits.autocorrect ? .default : .no
|
|
1289
|
+
field.spellCheckingType = traits.spellCheck ? .default : .no
|
|
1290
|
+
field.smartInsertDeleteType = .default
|
|
1291
|
+
field.smartQuotesType = .default
|
|
1292
|
+
field.smartDashesType = .default
|
|
1293
|
+
}
|
|
1294
|
+
if editor.isFirstResponder {
|
|
1295
|
+
editor.reloadInputViews()
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1299
|
+
// MARK: - Text flow
|
|
1300
|
+
|
|
1301
|
+
/// Every change to the field's text ends up here: the engine is fed the new
|
|
1302
|
+
/// glyph list and the change is reported.
|
|
1303
|
+
/// `changed` is false only for the first, unchanged application of the
|
|
1304
|
+
/// `text` prop (the engine still needs feeding); a keystroke always changes.
|
|
1305
|
+
private func textDidChange(caret: Int, reason: ChangeReason, changed: Bool = true) {
|
|
1306
|
+
feedEngine(caret: caret)
|
|
1307
|
+
if reason != .prop {
|
|
1308
|
+
eventCount += 1
|
|
1309
|
+
// Worklet callbacks run synchronously on the UI thread, before JS hears of the change.
|
|
1310
|
+
if worklets.onChangeText != 0 {
|
|
1311
|
+
margelo.nitro.nitroinput.nitroinputworklets.runChangeText(Int32(worklets.onChangeText), std.string(text))
|
|
1312
|
+
}
|
|
1313
|
+
if worklets.onChangeValue != 0, format.mode == .number {
|
|
1314
|
+
margelo.nitro.nitroinput.nitroinputworklets.runChangeValue(Int32(worklets.onChangeValue), value)
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
if format.mode == .mask, changed, let onMaskChange {
|
|
1318
|
+
// Derived from the settled text so every route reports the same thing:
|
|
1319
|
+
// a keystroke, `setText`, a prop change or a transform worklet. Not the
|
|
1320
|
+
// untouched text at mount, which Android doesn't report either.
|
|
1321
|
+
let result = maskEngine.apply(std.string(text), Int32(text.unicodeScalars.count), true,
|
|
1322
|
+
format.maskAutocomplete, false)
|
|
1323
|
+
onMaskChange(text, String(result.extractedValue), String(result.tailPlaceholder), result.complete)
|
|
1324
|
+
}
|
|
1325
|
+
if wantsFrameDrawing { layoutFrame(animated: reason != .prop) }
|
|
1326
|
+
onTextChange?(text, value, eventCount, reason)
|
|
1327
|
+
}
|
|
1328
|
+
|
|
1329
|
+
/// The current selection as code point offsets.
|
|
1330
|
+
private func selectionCodePoints() -> (Int, Int) {
|
|
1331
|
+
let count = text.unicodeScalars.count
|
|
1332
|
+
guard let range = field.selectedTextRange else { return (count, count) }
|
|
1333
|
+
let start = Self.codePointOffset(in: text, utf16: field.offset(from: field.beginningOfDocument, to: range.start))
|
|
1334
|
+
let end = Self.codePointOffset(in: text, utf16: field.offset(from: field.beginningOfDocument, to: range.end))
|
|
1335
|
+
return (start, end)
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
/// Hands the engine the current text as glyphs (prefix, body or placeholder,
|
|
1339
|
+
/// suffix) with their advance widths and commits it.
|
|
1340
|
+
fileprivate func feedEngine(caret: Int) {
|
|
1341
|
+
// Plain mode has no overlay to feed: the field draws its own text. Its
|
|
1342
|
+
// width still has to reach React for `autoWidth`, and this is the one
|
|
1343
|
+
// place every text, font, affix and placeholder change comes through.
|
|
1344
|
+
guard !traits.plain else { reportIntrinsicSize(); return }
|
|
1345
|
+
engine.setReduceMotion(UIAccessibility.isReduceMotionEnabled)
|
|
1346
|
+
engine.beginText()
|
|
1347
|
+
// `secureTextEntry` masks what the overlay draws: the hidden field keeps
|
|
1348
|
+
// the real text (UIKit needs it for editing and autofill), but every glyph
|
|
1349
|
+
// the user sees is a bullet.
|
|
1350
|
+
let body = traits.secureTextEntry
|
|
1351
|
+
? String(repeating: "\u{2022}", count: text.unicodeScalars.count)
|
|
1352
|
+
: text
|
|
1353
|
+
let showPlaceholder = body.isEmpty && !effectivePlaceholder.isEmpty
|
|
1354
|
+
let bodyText = showPlaceholder ? effectivePlaceholder : body
|
|
1355
|
+
let numberKinds = format.mode == .number
|
|
1356
|
+
|
|
1357
|
+
// A negative amount reads "-$1,234.56", not "$-1,234.56": the sign belongs
|
|
1358
|
+
// to the amount, not to the digits after the symbol. It stays a *body*
|
|
1359
|
+
// glyph - it is part of the text, and the caret counts body glyphs in the
|
|
1360
|
+
// order they are added - and is only laid out ahead of the prefix.
|
|
1361
|
+
var rest = Array(bodyText.unicodeScalars)
|
|
1362
|
+
let sign: Unicode.Scalar? =
|
|
1363
|
+
format.signPlacement == .beforeAffix && !showPlaceholder && !format.prefix.isEmpty
|
|
1364
|
+
&& rest.first.map(Self.isSign) == true
|
|
1365
|
+
? rest.removeFirst()
|
|
1366
|
+
: nil
|
|
1367
|
+
if let sign {
|
|
1368
|
+
let kind = numberKinds ? formatter.kindOf(sign.value) : Kind.text
|
|
1369
|
+
engine.addGlyph(sign.value, Role.body, kind, Double(fonts.width(of: String(sign), role: .body)), false)
|
|
1370
|
+
}
|
|
1371
|
+
for scalar in format.prefix.unicodeScalars {
|
|
1372
|
+
engine.addGlyph(scalar.value, Role.prefix, Kind.text, Double(fonts.width(of: String(scalar), role: .prefix)), false)
|
|
1373
|
+
}
|
|
1374
|
+
for scalar in rest {
|
|
1375
|
+
let kind = numberKinds ? formatter.kindOf(scalar.value) : Kind.text
|
|
1376
|
+
engine.addGlyph(scalar.value, Role.body, kind, Double(fonts.width(of: String(scalar), role: .body)), showPlaceholder)
|
|
1377
|
+
}
|
|
1378
|
+
for scalar in format.suffix.unicodeScalars {
|
|
1379
|
+
engine.addGlyph(scalar.value, Role.suffix, Kind.text, Double(fonts.width(of: String(scalar), role: .suffix)), false)
|
|
1380
|
+
}
|
|
1381
|
+
engine.commitText(Int32(caret), CACurrentMediaTime())
|
|
1382
|
+
reportIntrinsicSize()
|
|
1383
|
+
updateDisplayLinkNeed()
|
|
1384
|
+
render()
|
|
1385
|
+
updateCaret(restartBlink: true)
|
|
1386
|
+
}
|
|
1387
|
+
|
|
1388
|
+
@objc private func fieldEditingChanged() {
|
|
1389
|
+
guard !isSettingText else { return }
|
|
1390
|
+
// Text mode: the field edited itself; number mode edits never reach here
|
|
1391
|
+
// (the delegate applies them and returns false).
|
|
1392
|
+
textDidChange(caret: caretCodePointIndex(), reason: .user)
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
/// The selection start in code points (the engine's caret index).
|
|
1396
|
+
private func caretCodePointIndex() -> Int {
|
|
1397
|
+
guard let range = field.selectedTextRange else { return text.unicodeScalars.count }
|
|
1398
|
+
let utf16 = field.offset(from: field.beginningOfDocument, to: range.start)
|
|
1399
|
+
return Self.codePointOffset(in: text, utf16: utf16)
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
// MARK: - Offsets (UTF-16 ↔ code points)
|
|
1403
|
+
|
|
1404
|
+
/// A leading minus, in either the keyboard's spelling or the typographic one.
|
|
1405
|
+
static func isSign(_ scalar: Unicode.Scalar) -> Bool {
|
|
1406
|
+
scalar == "-" || scalar.value == 0x2212
|
|
1407
|
+
}
|
|
1408
|
+
|
|
1409
|
+
static func codePointOffset(in string: String, utf16 offset: Int) -> Int {
|
|
1410
|
+
let utf16 = string.utf16
|
|
1411
|
+
let clamped = min(max(0, offset), utf16.count)
|
|
1412
|
+
let index = utf16.index(utf16.startIndex, offsetBy: clamped)
|
|
1413
|
+
let scalars = string.unicodeScalars
|
|
1414
|
+
let scalarIndex = index.samePosition(in: scalars) ?? scalars.index(before: min(index, scalars.endIndex))
|
|
1415
|
+
return scalars.distance(from: scalars.startIndex, to: scalarIndex)
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1418
|
+
static func utf16Offset(in string: String, codePoint offset: Int) -> Int {
|
|
1419
|
+
let scalars = string.unicodeScalars
|
|
1420
|
+
let clamped = min(max(0, offset), scalars.count)
|
|
1421
|
+
let index = scalars.index(scalars.startIndex, offsetBy: clamped)
|
|
1422
|
+
return string.utf16.distance(from: string.utf16.startIndex, to: index)
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
// MARK: - Display link
|
|
1426
|
+
|
|
1427
|
+
fileprivate func step(_ link: CADisplayLink) {
|
|
1428
|
+
_ = engine.tick(CACurrentMediaTime())
|
|
1429
|
+
if pendingSizeReport, !engine.needsFrames() {
|
|
1430
|
+
reportIntrinsicSize()
|
|
1431
|
+
}
|
|
1432
|
+
updateDisplayLinkNeed()
|
|
1433
|
+
// `render()` places the caret along with the glyphs; whether it shows is
|
|
1434
|
+
// decided by the focus and selection callbacks, never by a frame.
|
|
1435
|
+
render()
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
private func updateDisplayLinkNeed() {
|
|
1439
|
+
if engine.needsFrames() {
|
|
1440
|
+
startDisplayLink()
|
|
1441
|
+
} else {
|
|
1442
|
+
stopDisplayLink()
|
|
1443
|
+
}
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
private func startDisplayLink() {
|
|
1447
|
+
guard displayLink == nil else { return }
|
|
1448
|
+
let proxy = DisplayLinkProxy(target: self)
|
|
1449
|
+
let link = CADisplayLink(target: proxy, selector: #selector(DisplayLinkProxy.tick(_:)))
|
|
1450
|
+
link.add(to: .main, forMode: .common)
|
|
1451
|
+
displayLink = link
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1454
|
+
private func stopDisplayLink() {
|
|
1455
|
+
displayLink?.invalidate()
|
|
1456
|
+
displayLink = nil
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
private final class DisplayLinkProxy: NSObject {
|
|
1460
|
+
weak var target: NitroInputView?
|
|
1461
|
+
init(target: NitroInputView) { self.target = target }
|
|
1462
|
+
@objc func tick(_ link: CADisplayLink) { target?.step(link) }
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
// MARK: - Typography helpers
|
|
1466
|
+
|
|
1467
|
+
private func updateFontScale(contentWidth: CGFloat) {
|
|
1468
|
+
var scale: CGFloat = 1
|
|
1469
|
+
if typography.adjustsFontSizeToFit, bounds.width > 0, contentWidth > bounds.width {
|
|
1470
|
+
scale = max(min(1, typography.minimumFontScale), bounds.width / contentWidth)
|
|
1471
|
+
}
|
|
1472
|
+
fontScale = scale
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
/// Dynamic Type multiplier for `allowFontScaling`, capped by `maxFontSizeMultiplier`.
|
|
1476
|
+
private static func systemFontMultiplier(_ t: Typography) -> CGFloat {
|
|
1477
|
+
guard t.allowFontScaling else { return 1 }
|
|
1478
|
+
let multiplier = UIFontMetrics(forTextStyle: .body).scaledValue(for: 100) / 100
|
|
1479
|
+
if t.maxFontSizeMultiplier > 0 {
|
|
1480
|
+
return min(multiplier, t.maxFontSizeMultiplier)
|
|
1481
|
+
}
|
|
1482
|
+
return multiplier
|
|
1483
|
+
}
|
|
1484
|
+
|
|
1485
|
+
private static func makeFont(size: CGFloat, weight: CGFloat, family: String?) -> UIFont {
|
|
1486
|
+
let uiWeight = uiWeight(weight)
|
|
1487
|
+
let traits: [UIFontDescriptor.TraitKey: Any] = [.weight: uiWeight]
|
|
1488
|
+
var base: UIFont
|
|
1489
|
+
if let family, !family.isEmpty, let named = UIFont(name: family, size: size) {
|
|
1490
|
+
let descriptor = named.fontDescriptor.addingAttributes([.traits: traits])
|
|
1491
|
+
base = UIFont(descriptor: descriptor, size: size)
|
|
1492
|
+
} else if let family, !family.isEmpty, !UIFont.fontNames(forFamilyName: family).isEmpty {
|
|
1493
|
+
let descriptor = UIFontDescriptor(fontAttributes: [.family: family, .traits: traits])
|
|
1494
|
+
base = UIFont(descriptor: descriptor, size: size)
|
|
1495
|
+
} else {
|
|
1496
|
+
base = UIFont.systemFont(ofSize: size, weight: uiWeight)
|
|
1497
|
+
}
|
|
1498
|
+
// Tabular digits: a column keeps its width while its digit morphs.
|
|
1499
|
+
let feature: [UIFontDescriptor.FeatureKey: Int] = [.type: kNumberSpacingType, .selector: kMonospacedNumbersSelector]
|
|
1500
|
+
let descriptor = base.fontDescriptor.addingAttributes([.featureSettings: [feature]])
|
|
1501
|
+
return UIFont(descriptor: descriptor, size: size)
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
private static func uiWeight(_ w: CGFloat) -> UIFont.Weight {
|
|
1505
|
+
switch w {
|
|
1506
|
+
case ..<150: return .ultraLight
|
|
1507
|
+
case ..<250: return .thin
|
|
1508
|
+
case ..<350: return .light
|
|
1509
|
+
case ..<450: return .regular
|
|
1510
|
+
case ..<550: return .medium
|
|
1511
|
+
case ..<650: return .semibold
|
|
1512
|
+
case ..<750: return .bold
|
|
1513
|
+
case ..<850: return .heavy
|
|
1514
|
+
default: return .black
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
|
|
1519
|
+
// MARK: - Intrinsic size
|
|
1520
|
+
|
|
1521
|
+
/// One line, or - wrapping - as tall as the text is, capped by
|
|
1522
|
+
/// `numberOfLines`. Asking for `numberOfLines` x the line box and getting
|
|
1523
|
+
/// exactly that is the contract; the platforms differ on what they measure,
|
|
1524
|
+
/// so neither is trusted with it.
|
|
1525
|
+
/// The height one line occupies: the explicit `lineHeight` when there is one,
|
|
1526
|
+
/// the font's own otherwise.
|
|
1527
|
+
private var lineBoxHeight: CGFloat {
|
|
1528
|
+
typography.lineHeight > 0 ? typography.lineHeight : fonts.lineHeight
|
|
1529
|
+
}
|
|
1530
|
+
|
|
1531
|
+
private func intrinsicHeight() -> CGFloat {
|
|
1532
|
+
guard traits.multiline else { return fonts.lineHeight }
|
|
1533
|
+
let line = lineBoxHeight
|
|
1534
|
+
// Only the frame's room is on top of the text. The rest of the text view's
|
|
1535
|
+
// inset is `lineBoxPadding`, which is the *first* line's share of the
|
|
1536
|
+
// leading - already inside the `lineHeight` each line is billed for.
|
|
1537
|
+
let framePadding = frameVerticalInset.top + frameVerticalInset.bottom
|
|
1538
|
+
// Before the first layout pass the width is 0, and `sizeThatFits` against
|
|
1539
|
+
// it wraps every word onto its own line. `numberOfLines` is the better
|
|
1540
|
+
// answer until there is a real width to wrap against.
|
|
1541
|
+
guard didBuildTextView, bounds.width > 1 else {
|
|
1542
|
+
return framePadding + line * CGFloat(max(1, traits.numberOfLines))
|
|
1543
|
+
}
|
|
1544
|
+
// `sizeThatFits` reports the insets too, and a loose line box spends its
|
|
1545
|
+
// last line's leading on the bottom inset rather than on the line - so the
|
|
1546
|
+
// count comes from the text alone, and the height is rebuilt from it.
|
|
1547
|
+
let inset = textView.textContainerInset
|
|
1548
|
+
let used = textView.sizeThatFits(CGSize(width: max(1, bounds.width),
|
|
1549
|
+
height: .greatestFiniteMagnitude)).height
|
|
1550
|
+
- inset.top - inset.bottom
|
|
1551
|
+
let lines = max(1, Int((used / line).rounded(.up)))
|
|
1552
|
+
// `numberOfLines` pins the box, it does not cap a growing one: asking for
|
|
1553
|
+
// n lines and getting exactly n is the contract, and it is what Android's
|
|
1554
|
+
// `intrinsicHeightPx` reports.
|
|
1555
|
+
let capped = traits.numberOfLines > 0 ? traits.numberOfLines : lines
|
|
1556
|
+
return framePadding + line * CGFloat(capped)
|
|
1557
|
+
}
|
|
1558
|
+
|
|
1559
|
+
/// The width the content asks for: the engine's layout in morph mode; in
|
|
1560
|
+
/// plain mode, which never feeds the engine, the text (or the placeholder)
|
|
1561
|
+
/// and the affixes measured with the same fonts the field draws them in.
|
|
1562
|
+
private func contentWidth() -> CGFloat {
|
|
1563
|
+
guard traits.plain else { return CGFloat(engine.targetWidth()) }
|
|
1564
|
+
let body = text.isEmpty
|
|
1565
|
+
? effectivePlaceholder
|
|
1566
|
+
: traits.secureTextEntry ? String(repeating: "\u{2022}", count: text.unicodeScalars.count) : text
|
|
1567
|
+
return fonts.width(of: format.prefix, role: .prefix)
|
|
1568
|
+
+ fonts.width(of: body, role: .body)
|
|
1569
|
+
+ fonts.width(of: format.suffix, role: .suffix)
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
private func reportIntrinsicSize() {
|
|
1573
|
+
let size = CGSize(width: ceil(contentWidth() + 2), height: intrinsicHeight())
|
|
1574
|
+
guard abs(size.width - lastReportedSize.width) > 0.01 || abs(size.height - lastReportedSize.height) > 0.01 else {
|
|
1575
|
+
pendingSizeReport = false
|
|
1576
|
+
return
|
|
1577
|
+
}
|
|
1578
|
+
// Growing: report right away so React widens the box before the new glyph
|
|
1579
|
+
// has fully arrived (the view is not clipped meanwhile). Shrinking mid-morph:
|
|
1580
|
+
// keep the wider box until the morph has finished, otherwise
|
|
1581
|
+
// adjustsFontSizeToFit would squeeze the moving glyphs into the smaller box.
|
|
1582
|
+
if lastReportedSize != .zero, size.width < lastReportedSize.width, engine.isAnimating() {
|
|
1583
|
+
pendingSizeReport = true
|
|
1584
|
+
return
|
|
1585
|
+
}
|
|
1586
|
+
pendingSizeReport = false
|
|
1587
|
+
lastReportedSize = size
|
|
1588
|
+
onIntrinsicSizeChange?(size)
|
|
1589
|
+
}
|
|
1590
|
+
|
|
1591
|
+
// MARK: - Rendering
|
|
1592
|
+
|
|
1593
|
+
private func clearGlyphLayers() {
|
|
1594
|
+
for entry in glyphLayers.values {
|
|
1595
|
+
entry.layer.removeFromSuperlayer()
|
|
1596
|
+
}
|
|
1597
|
+
glyphLayers = [:]
|
|
1598
|
+
}
|
|
1599
|
+
|
|
1600
|
+
private static func glyphRole(_ role: Int32) -> GlyphRole {
|
|
1601
|
+
switch role {
|
|
1602
|
+
case Role.prefix: return .prefix
|
|
1603
|
+
case Role.suffix: return .suffix
|
|
1604
|
+
default: return .body
|
|
1605
|
+
}
|
|
1606
|
+
}
|
|
1607
|
+
|
|
1608
|
+
private static func glyphText(_ character: UInt32) -> String {
|
|
1609
|
+
guard let scalar = Unicode.Scalar(character) else { return " " }
|
|
1610
|
+
return String(scalar)
|
|
1611
|
+
}
|
|
1612
|
+
|
|
1613
|
+
private func contentPlacement(total: CGFloat, lineHeight: CGFloat) -> (origin: CGPoint, scale: CGFloat) {
|
|
1614
|
+
let fit = fontScale
|
|
1615
|
+
let shown = total * fit
|
|
1616
|
+
// An outlined or filled frame reserves room at the sides for its stroke
|
|
1617
|
+
// and at the top for the floated label; the glyphs lay out inside that.
|
|
1618
|
+
let side = frameSideInset
|
|
1619
|
+
let top = frameTopInset
|
|
1620
|
+
let boxWidth = max(0, bounds.width - side * 2)
|
|
1621
|
+
let originX: CGFloat
|
|
1622
|
+
if boxWidth > 0, shown > boxWidth + 0.5 {
|
|
1623
|
+
// Wider than the view (no shrink-to-fit, or its floor reached): scroll
|
|
1624
|
+
// horizontally so the caret stays in view while editing; at rest show
|
|
1625
|
+
// the start (the end for right-aligned content).
|
|
1626
|
+
let maxScroll = shown - boxWidth
|
|
1627
|
+
if field.isFirstResponder {
|
|
1628
|
+
let margin: CGFloat = 2
|
|
1629
|
+
let caretOnScreen = CGFloat(engine.caretX(caretBodyIndex())) * fit - scrollX
|
|
1630
|
+
if caretOnScreen > boxWidth - margin {
|
|
1631
|
+
scrollX += caretOnScreen - (boxWidth - margin)
|
|
1632
|
+
} else if caretOnScreen < margin {
|
|
1633
|
+
scrollX -= margin - caretOnScreen
|
|
1634
|
+
}
|
|
1635
|
+
} else {
|
|
1636
|
+
scrollX = resolvedAlignment == .right ? maxScroll : 0
|
|
1637
|
+
}
|
|
1638
|
+
scrollX = min(max(0, scrollX), maxScroll)
|
|
1639
|
+
originX = side - scrollX
|
|
1640
|
+
} else {
|
|
1641
|
+
scrollX = 0
|
|
1642
|
+
switch resolvedAlignment {
|
|
1643
|
+
case .auto, .left: originX = side
|
|
1644
|
+
case .center: originX = side + (boxWidth - shown) / 2
|
|
1645
|
+
case .right: originX = side + boxWidth - shown
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
let originY = top + (bounds.height - top - lineHeight * fit) / 2
|
|
1649
|
+
return (CGPoint(x: originX, y: originY), fit)
|
|
1650
|
+
}
|
|
1651
|
+
|
|
1652
|
+
/// Whether the content is wider than the view, so a caret move may need to scroll it.
|
|
1653
|
+
private var contentOverflows: Bool {
|
|
1654
|
+
bounds.width > 0 && CGFloat(engine.contentWidth()) * fontScale > bounds.width + 0.5
|
|
1655
|
+
}
|
|
1656
|
+
|
|
1657
|
+
private func render() {
|
|
1658
|
+
guard !traits.plain else { return }
|
|
1659
|
+
let fonts = self.fonts
|
|
1660
|
+
let lineHeight = fonts.lineHeight
|
|
1661
|
+
let contentWidth = CGFloat(engine.contentWidth())
|
|
1662
|
+
updateFontScale(contentWidth: contentWidth)
|
|
1663
|
+
placement = contentPlacement(total: contentWidth, lineHeight: lineHeight)
|
|
1664
|
+
|
|
1665
|
+
CATransaction.begin()
|
|
1666
|
+
CATransaction.setDisableActions(true)
|
|
1667
|
+
defer { CATransaction.commit() }
|
|
1668
|
+
|
|
1669
|
+
contentLayer.bounds = CGRect(x: 0, y: 0, width: max(contentWidth, 1), height: lineHeight)
|
|
1670
|
+
contentLayer.position = placement.origin
|
|
1671
|
+
contentLayer.transform = placement.scale == 1 ? CATransform3DIdentity : CATransform3DMakeScale(placement.scale, placement.scale, 1)
|
|
1672
|
+
|
|
1673
|
+
// The clip box extends one line height to each side so glyphs at the edges
|
|
1674
|
+
// are not cut while they slide, and a soft band (0.15 em, Torph's) above and
|
|
1675
|
+
// below the line box: the box itself stays fully opaque (a comma's tail
|
|
1676
|
+
// reaches its bottom edge), glyphs dissolve in the bands as they pass through.
|
|
1677
|
+
// When the content is wider than the view it is clipped to the view's
|
|
1678
|
+
// edges instead (scrolled like a UITextField), in content coordinates.
|
|
1679
|
+
let band = min(lineHeight / 3, 0.15 * fonts.body.pointSize)
|
|
1680
|
+
let clipLeft: CGFloat
|
|
1681
|
+
let clipRight: CGFloat
|
|
1682
|
+
if scrollX > 0 || (bounds.width > 0 && contentWidth * placement.scale > bounds.width + 0.5) {
|
|
1683
|
+
clipLeft = scrollX / max(placement.scale, 0.0001)
|
|
1684
|
+
clipRight = (scrollX + bounds.width) / max(placement.scale, 0.0001)
|
|
1685
|
+
} else {
|
|
1686
|
+
clipLeft = -lineHeight
|
|
1687
|
+
clipRight = max(contentWidth, 1) + lineHeight
|
|
1688
|
+
}
|
|
1689
|
+
let pad = -clipLeft
|
|
1690
|
+
clipLayer.frame = CGRect(x: clipLeft, y: -band, width: max(clipRight - clipLeft, 1), height: lineHeight + 2 * band)
|
|
1691
|
+
edgeMask.frame = clipLayer.bounds
|
|
1692
|
+
let fade = band / max(lineHeight + 2 * band, 1)
|
|
1693
|
+
edgeMask.locations = [0, NSNumber(value: Double(fade)), NSNumber(value: Double(1 - fade)), 1]
|
|
1694
|
+
|
|
1695
|
+
// A frame allocates nothing once every glyph has its layer: each entry is
|
|
1696
|
+
// stamped with this pass's generation rather than collected into a set,
|
|
1697
|
+
// and only a pass that has more layers than the engine has glyphs goes
|
|
1698
|
+
// looking for the ones that left.
|
|
1699
|
+
renderGeneration &+= 1
|
|
1700
|
+
let generation = renderGeneration
|
|
1701
|
+
let count = Int(engine.glyphCount())
|
|
1702
|
+
for i in 0..<count {
|
|
1703
|
+
let g = engine.glyphAt(Int32(i))
|
|
1704
|
+
let glyphLayer: CALayer
|
|
1705
|
+
let topOffset: CGFloat
|
|
1706
|
+
if let index = glyphLayers.index(forKey: g.id) {
|
|
1707
|
+
glyphLayers.values[index].generation = generation
|
|
1708
|
+
glyphLayer = glyphLayers.values[index].layer
|
|
1709
|
+
topOffset = glyphLayers.values[index].topOffset
|
|
1710
|
+
} else {
|
|
1711
|
+
let role = Self.glyphRole(g.role)
|
|
1712
|
+
let text = Self.glyphText(g.character)
|
|
1713
|
+
glyphLayer = CALayer()
|
|
1714
|
+
glyphLayer.contentsScale = fonts.renderScale
|
|
1715
|
+
if let image = fonts.image(text, role: role, placeholder: g.placeholder) {
|
|
1716
|
+
glyphLayer.contents = image.cgImage
|
|
1717
|
+
glyphLayer.bounds = CGRect(origin: .zero, size: image.size)
|
|
1718
|
+
}
|
|
1719
|
+
clipLayer.addSublayer(glyphLayer)
|
|
1720
|
+
topOffset = fonts.top(for: role, text: text, lineTop: 0)
|
|
1721
|
+
glyphLayers[g.id] = GlyphEntry(layer: glyphLayer, topOffset: topOffset, generation: generation)
|
|
1722
|
+
}
|
|
1723
|
+
let size = glyphLayer.bounds.size
|
|
1724
|
+
let top = band + topOffset + CGFloat(g.y) * lineHeight
|
|
1725
|
+
glyphLayer.position = CGPoint(x: pad + CGFloat(g.x) + size.width / 2, y: top + size.height / 2)
|
|
1726
|
+
glyphLayer.opacity = Float(min(1, max(0, g.opacity)))
|
|
1727
|
+
let scale = CGFloat(g.scale)
|
|
1728
|
+
glyphLayer.transform = abs(scale - 1) < 0.0001 ? CATransform3DIdentity : CATransform3DMakeScale(scale, scale, 1)
|
|
1729
|
+
}
|
|
1730
|
+
if glyphLayers.count != count {
|
|
1731
|
+
// Collecting the leavers allocates, but only on the frame they leave.
|
|
1732
|
+
let gone = glyphLayers.filter { $0.value.generation != generation }
|
|
1733
|
+
for (id, entry) in gone {
|
|
1734
|
+
entry.layer.removeFromSuperlayer()
|
|
1735
|
+
glyphLayers[id] = nil
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
positionCaret()
|
|
1739
|
+
}
|
|
1740
|
+
|
|
1741
|
+
// MARK: - Caret
|
|
1742
|
+
|
|
1743
|
+
/// Whether our caret should be drawn: focused, not hidden, empty selection.
|
|
1744
|
+
private var wantsCaret: Bool {
|
|
1745
|
+
guard field.isFirstResponder, !traits.caretHidden else { return false }
|
|
1746
|
+
guard let range = field.selectedTextRange else { return false }
|
|
1747
|
+
return range.isEmpty
|
|
1748
|
+
}
|
|
1749
|
+
|
|
1750
|
+
private func caretBodyIndex() -> Int32 {
|
|
1751
|
+
let index = caretCodePointIndex()
|
|
1752
|
+
return Int32(min(max(0, index), Int(engine.bodyCount())))
|
|
1753
|
+
}
|
|
1754
|
+
|
|
1755
|
+
private func positionCaret() {
|
|
1756
|
+
let lineHeight = fonts.lineHeight
|
|
1757
|
+
let height = lineHeight * 0.9
|
|
1758
|
+
let x = CGFloat(engine.caretX(caretBodyIndex()))
|
|
1759
|
+
caretLayer.bounds = CGRect(x: 0, y: 0, width: 2, height: height)
|
|
1760
|
+
caretLayer.position = CGPoint(x: x, y: lineHeight / 2)
|
|
1761
|
+
}
|
|
1762
|
+
|
|
1763
|
+
fileprivate func updateCaret(restartBlink: Bool = false) {
|
|
1764
|
+
// The system caret is the real one in plain mode.
|
|
1765
|
+
guard !traits.plain else { return }
|
|
1766
|
+
let visible = wantsCaret
|
|
1767
|
+
CATransaction.begin()
|
|
1768
|
+
CATransaction.setDisableActions(true)
|
|
1769
|
+
caretLayer.backgroundColor = (traits.caretColor ?? tintColor ?? .systemBlue).resolvedColor(with: traitCollection).cgColor
|
|
1770
|
+
positionCaret()
|
|
1771
|
+
caretLayer.isHidden = !visible
|
|
1772
|
+
CATransaction.commit()
|
|
1773
|
+
if visible {
|
|
1774
|
+
if restartBlink || caretLayer.animation(forKey: "blink") == nil {
|
|
1775
|
+
startBlink()
|
|
1776
|
+
}
|
|
1777
|
+
} else {
|
|
1778
|
+
stopBlink()
|
|
1779
|
+
}
|
|
1780
|
+
}
|
|
1781
|
+
|
|
1782
|
+
private func startBlink() {
|
|
1783
|
+
caretLayer.removeAnimation(forKey: "blink")
|
|
1784
|
+
let blink = CAKeyframeAnimation(keyPath: "opacity")
|
|
1785
|
+
blink.values = [1, 1, 0, 0]
|
|
1786
|
+
blink.keyTimes = [0, 0.5, 0.5, 1]
|
|
1787
|
+
blink.duration = 1
|
|
1788
|
+
blink.repeatCount = .infinity
|
|
1789
|
+
blink.calculationMode = .discrete
|
|
1790
|
+
// Stay solid for a moment after the caret moved, like the system caret.
|
|
1791
|
+
blink.beginTime = CACurrentMediaTime() + 0.35
|
|
1792
|
+
blink.fillMode = .backwards
|
|
1793
|
+
caretLayer.add(blink, forKey: "blink")
|
|
1794
|
+
}
|
|
1795
|
+
|
|
1796
|
+
private func stopBlink() {
|
|
1797
|
+
caretLayer.removeAnimation(forKey: "blink")
|
|
1798
|
+
}
|
|
1799
|
+
|
|
1800
|
+
// MARK: - Tap → caret
|
|
1801
|
+
|
|
1802
|
+
/// The text position nearest to `point` (in this view's coordinates), going
|
|
1803
|
+
/// through the engine's glyph boundaries so taps stay right while the content
|
|
1804
|
+
/// is scaled or mid-morph. `nil` when there is no overlay: a plain field
|
|
1805
|
+
/// draws its own text, and the engine holds no glyphs for it, so UIKit's own
|
|
1806
|
+
/// mapping is the right one. (Going through the engine there found a single
|
|
1807
|
+
/// boundary and put every tap at index 0.)
|
|
1808
|
+
fileprivate func closestTextPosition(to point: CGPoint) -> UITextPosition? {
|
|
1809
|
+
guard !traits.plain, engine.hasText() else { return nil }
|
|
1810
|
+
let bodyCount = Int(engine.bodyCount())
|
|
1811
|
+
let textCount = text.unicodeScalars.count
|
|
1812
|
+
let contentX = (point.x - placement.origin.x) / max(placement.scale, 0.0001)
|
|
1813
|
+
var best = 0
|
|
1814
|
+
var bestDistance = CGFloat.greatestFiniteMagnitude
|
|
1815
|
+
for index in 0...bodyCount {
|
|
1816
|
+
let distance = abs(CGFloat(engine.caretX(Int32(index))) - contentX)
|
|
1817
|
+
if distance < bestDistance {
|
|
1818
|
+
bestDistance = distance
|
|
1819
|
+
best = index
|
|
1820
|
+
}
|
|
1821
|
+
}
|
|
1822
|
+
let codePoint = min(best, textCount)
|
|
1823
|
+
let utf16 = Self.utf16Offset(in: text, codePoint: codePoint)
|
|
1824
|
+
return field.position(from: field.beginningOfDocument, offset: utf16)
|
|
1825
|
+
}
|
|
1826
|
+
|
|
1827
|
+
// MARK: - Hidden field
|
|
1828
|
+
|
|
1829
|
+
/// The system field: invisible text, no caret, our insets, our hit mapping.
|
|
1830
|
+
/**
|
|
1831
|
+
A `UITextField` cannot wrap - there is no flag for it - so a multiline field
|
|
1832
|
+
is a `UITextView` instead, the same split React Native makes between
|
|
1833
|
+
`RCTUITextField` and `RCTUITextView`. It is created only when it is needed
|
|
1834
|
+
and the single-line path is left exactly as it was.
|
|
1835
|
+
|
|
1836
|
+
`UITextView` has no placeholder of its own, so this draws one.
|
|
1837
|
+
*/
|
|
1838
|
+
fileprivate final class HiddenTextView: UITextView {
|
|
1839
|
+
weak var owner: NitroInputView?
|
|
1840
|
+
var placeholder: String = "" { didSet { setNeedsDisplay() } }
|
|
1841
|
+
var placeholderColor: UIColor = .placeholderText { didSet { setNeedsDisplay() } }
|
|
1842
|
+
|
|
1843
|
+
var showSoftInputOnFocus: Bool = true {
|
|
1844
|
+
didSet {
|
|
1845
|
+
guard showSoftInputOnFocus != oldValue else { return }
|
|
1846
|
+
inputView = showSoftInputOnFocus ? nil : UIView(frame: .zero)
|
|
1847
|
+
if isFirstResponder { reloadInputViews() }
|
|
1848
|
+
}
|
|
1849
|
+
}
|
|
1850
|
+
|
|
1851
|
+
override var text: String! {
|
|
1852
|
+
didSet { setNeedsDisplay() }
|
|
1853
|
+
}
|
|
1854
|
+
|
|
1855
|
+
override func caretRect(for position: UITextPosition) -> CGRect {
|
|
1856
|
+
let rect = super.caretRect(for: position)
|
|
1857
|
+
guard hidesNativeCaret else { return rect }
|
|
1858
|
+
return CGRect(origin: rect.origin, size: .zero)
|
|
1859
|
+
}
|
|
1860
|
+
|
|
1861
|
+
var hidesNativeCaret = false {
|
|
1862
|
+
didSet { if hidesNativeCaret != oldValue { setNeedsDisplay() } }
|
|
1863
|
+
}
|
|
1864
|
+
|
|
1865
|
+
/// Set while a paste is applied: a pasted line break is text and goes in,
|
|
1866
|
+
/// only the return key's is taken as one (`shouldChangeTextIn`).
|
|
1867
|
+
private(set) var isPasting = false
|
|
1868
|
+
|
|
1869
|
+
override func paste(_ sender: Any?) {
|
|
1870
|
+
isPasting = true
|
|
1871
|
+
super.paste(sender)
|
|
1872
|
+
isPasting = false
|
|
1873
|
+
}
|
|
1874
|
+
|
|
1875
|
+
/// The placeholder sits exactly where the first line of text will, so it
|
|
1876
|
+
/// has to respect the same container inset and line fragment padding.
|
|
1877
|
+
override func draw(_ rect: CGRect) {
|
|
1878
|
+
super.draw(rect)
|
|
1879
|
+
guard text.isEmpty, !placeholder.isEmpty else { return }
|
|
1880
|
+
var attributes: [NSAttributedString.Key: Any] = [
|
|
1881
|
+
.font: font ?? UIFont.systemFont(ofSize: UIFont.systemFontSize),
|
|
1882
|
+
.foregroundColor: placeholderColor,
|
|
1883
|
+
]
|
|
1884
|
+
if let style = typingAttributes[.paragraphStyle] { attributes[.paragraphStyle] = style }
|
|
1885
|
+
if let offset = typingAttributes[.baselineOffset] { attributes[.baselineOffset] = offset }
|
|
1886
|
+
let origin = CGPoint(
|
|
1887
|
+
x: textContainerInset.left + textContainer.lineFragmentPadding,
|
|
1888
|
+
y: textContainerInset.top
|
|
1889
|
+
)
|
|
1890
|
+
let width = bounds.width - origin.x - textContainerInset.right - textContainer.lineFragmentPadding
|
|
1891
|
+
(placeholder as NSString).draw(
|
|
1892
|
+
in: CGRect(x: origin.x, y: origin.y, width: max(0, width), height: bounds.height - origin.y),
|
|
1893
|
+
withAttributes: attributes
|
|
1894
|
+
)
|
|
1895
|
+
}
|
|
1896
|
+
}
|
|
1897
|
+
|
|
1898
|
+
fileprivate final class HiddenTextField: UITextField {
|
|
1899
|
+
weak var owner: NitroInputView?
|
|
1900
|
+
var leftInset: CGFloat = 0
|
|
1901
|
+
var rightInset: CGFloat = 0
|
|
1902
|
+
/// Room for a floated label sitting on the top edge.
|
|
1903
|
+
var topInset: CGFloat = 0
|
|
1904
|
+
/// `showSoftInputOnFocus: false` keeps focus and the caret but shows no
|
|
1905
|
+
/// keyboard, for a field driven by an in-app keypad.
|
|
1906
|
+
var showSoftInputOnFocus: Bool = true {
|
|
1907
|
+
didSet {
|
|
1908
|
+
guard showSoftInputOnFocus != oldValue else { return }
|
|
1909
|
+
// An empty input view is how UIKit is told "no keyboard".
|
|
1910
|
+
inputView = showSoftInputOnFocus ? nil : UIView(frame: .zero)
|
|
1911
|
+
if isFirstResponder { reloadInputViews() }
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1914
|
+
/// `contextMenuHidden`: suppresses the Cut/Copy/Paste menu.
|
|
1915
|
+
var contextMenuHidden: Bool = false
|
|
1916
|
+
/// The morph overlay draws its own caret, so the field's is collapsed away.
|
|
1917
|
+
/// In `plain` mode there is no overlay and the system caret is the caret.
|
|
1918
|
+
var hidesNativeCaret: Bool = true
|
|
1919
|
+
|
|
1920
|
+
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
|
|
1921
|
+
if contextMenuHidden { return false }
|
|
1922
|
+
return super.canPerformAction(action, withSender: sender)
|
|
1923
|
+
}
|
|
1924
|
+
|
|
1925
|
+
/// UIKit's paste controller puts the selection back where the pasted text
|
|
1926
|
+
/// would have ended *if it had inserted it*, which after a declined
|
|
1927
|
+
/// (formatted, transformed) edit is the pre-paste caret. Apply pasted
|
|
1928
|
+
/// text through the same path as a keystroke instead.
|
|
1929
|
+
override func paste(_ sender: Any?) {
|
|
1930
|
+
guard let owner, let string = UIPasteboard.general.string, let range = selectedTextRange else {
|
|
1931
|
+
return super.paste(sender)
|
|
1932
|
+
}
|
|
1933
|
+
let location = offset(from: beginningOfDocument, to: range.start)
|
|
1934
|
+
let length = offset(from: range.start, to: range.end)
|
|
1935
|
+
let nsRange = NSRange(location: location, length: length)
|
|
1936
|
+
if owner.textField(self, shouldChangeCharactersIn: nsRange, replacementString: string) {
|
|
1937
|
+
replace(range, withText: string)
|
|
1938
|
+
}
|
|
1939
|
+
}
|
|
1940
|
+
|
|
1941
|
+
override func caretRect(for position: UITextPosition) -> CGRect {
|
|
1942
|
+
let rect = super.caretRect(for: position)
|
|
1943
|
+
guard hidesNativeCaret else { return rect }
|
|
1944
|
+
return CGRect(origin: rect.origin, size: .zero)
|
|
1945
|
+
}
|
|
1946
|
+
|
|
1947
|
+
override func textRect(forBounds bounds: CGRect) -> CGRect {
|
|
1948
|
+
insetRect(super.textRect(forBounds: bounds))
|
|
1949
|
+
}
|
|
1950
|
+
|
|
1951
|
+
override func editingRect(forBounds bounds: CGRect) -> CGRect {
|
|
1952
|
+
insetRect(super.editingRect(forBounds: bounds))
|
|
1953
|
+
}
|
|
1954
|
+
|
|
1955
|
+
override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
|
|
1956
|
+
// NOT `super.placeholderRect` - UIKit derives that from `textRect`,
|
|
1957
|
+
// which is overridden above and has already applied the insets, so
|
|
1958
|
+
// insetting its result applies them a second time. The placeholder was
|
|
1959
|
+
// landing at twice the left inset (and, on the filled variant, twice the
|
|
1960
|
+
// top one). It belongs in the text's own rect.
|
|
1961
|
+
insetRect(super.textRect(forBounds: bounds))
|
|
1962
|
+
}
|
|
1963
|
+
|
|
1964
|
+
// The affix accessories are laid out by UIKit, which knows nothing about
|
|
1965
|
+
// our insets - so a prefix sat on top of the frame's stroke instead of
|
|
1966
|
+
// starting where the text does. `insetRect` cannot be reused here: it also
|
|
1967
|
+
// trims the width, and these are sized to their own content.
|
|
1968
|
+
override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
|
|
1969
|
+
var r = super.leftViewRect(forBounds: bounds)
|
|
1970
|
+
r.origin.x += leftInset
|
|
1971
|
+
// `insetRect` moves the text's centre by half the top inset; the affix
|
|
1972
|
+
// has to travel with it or it sits above its own text.
|
|
1973
|
+
r.origin.y += topInset / 2
|
|
1974
|
+
return r
|
|
1975
|
+
}
|
|
1976
|
+
|
|
1977
|
+
override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
|
|
1978
|
+
var r = super.rightViewRect(forBounds: bounds)
|
|
1979
|
+
r.origin.x -= rightInset
|
|
1980
|
+
r.origin.y += topInset / 2
|
|
1981
|
+
return r
|
|
1982
|
+
}
|
|
1983
|
+
|
|
1984
|
+
private func insetRect(_ rect: CGRect) -> CGRect {
|
|
1985
|
+
var r = rect
|
|
1986
|
+
// UIKit lays the text rect out *after* the accessories, using
|
|
1987
|
+
// `leftViewRect` / `rightViewRect` - which are overridden above and
|
|
1988
|
+
// already apply the insets. Adding them again on this side would double
|
|
1989
|
+
// them, which is exactly what `placeholderRect` used to do. So the inset
|
|
1990
|
+
// is ours to apply only on the edges with no accessory.
|
|
1991
|
+
let leading = leftView == nil ? leftInset : 0
|
|
1992
|
+
let trailing = rightView == nil ? rightInset : 0
|
|
1993
|
+
r.origin.x += leading
|
|
1994
|
+
r.size.width = max(0, r.size.width - leading - trailing)
|
|
1995
|
+
r.origin.y += topInset
|
|
1996
|
+
r.size.height = max(0, r.size.height - topInset)
|
|
1997
|
+
return r
|
|
1998
|
+
}
|
|
1999
|
+
|
|
2000
|
+
// UITextInput geometry is in `textInputView`'s coordinates: for a
|
|
2001
|
+
// UITextField that is its internal text canvas, which scrolls on its own
|
|
2002
|
+
// once the text is wider than the field, so convert from there.
|
|
2003
|
+
override func closestPosition(to point: CGPoint) -> UITextPosition? {
|
|
2004
|
+
if let owner, let position = owner.closestTextPosition(to: textInputView.convert(point, to: owner)) {
|
|
2005
|
+
return position
|
|
2006
|
+
}
|
|
2007
|
+
return super.closestPosition(to: point)
|
|
2008
|
+
}
|
|
2009
|
+
|
|
2010
|
+
override func closestPosition(to point: CGPoint, within range: UITextRange) -> UITextPosition? {
|
|
2011
|
+
guard let owner, let position = owner.closestTextPosition(to: textInputView.convert(point, to: owner)) else {
|
|
2012
|
+
return super.closestPosition(to: point, within: range)
|
|
2013
|
+
}
|
|
2014
|
+
if compare(position, to: range.start) == .orderedAscending { return range.start }
|
|
2015
|
+
if compare(position, to: range.end) == .orderedDescending { return range.end }
|
|
2016
|
+
return position
|
|
2017
|
+
}
|
|
2018
|
+
}
|
|
2019
|
+
}
|
|
2020
|
+
|
|
2021
|
+
// MARK: - UITextViewDelegate
|
|
2022
|
+
|
|
2023
|
+
extension NitroInputView: UITextViewDelegate {
|
|
2024
|
+
func textViewDidBeginEditing(_ textView: UITextView) {
|
|
2025
|
+
textFieldDidBeginEditing(field)
|
|
2026
|
+
}
|
|
2027
|
+
|
|
2028
|
+
func textViewDidEndEditing(_ textView: UITextView) {
|
|
2029
|
+
textFieldDidEndEditing(field)
|
|
2030
|
+
}
|
|
2031
|
+
|
|
2032
|
+
func textViewDidChange(_ textView: UITextView) {
|
|
2033
|
+
// The text view owns the text here. `setText` runs it through the
|
|
2034
|
+
// formatter, which is single-line by definition, so the multiline path
|
|
2035
|
+
// reports what the view already holds instead.
|
|
2036
|
+
guard !isSettingText else { return }
|
|
2037
|
+
eventCount += 1
|
|
2038
|
+
// Typing changes how many lines there are, so the height follows it.
|
|
2039
|
+
reportIntrinsicSize()
|
|
2040
|
+
if wantsFrameDrawing { layoutFrame(animated: true) }
|
|
2041
|
+
onTextChange?(text, Double.nan, eventCount, .user)
|
|
2042
|
+
}
|
|
2043
|
+
|
|
2044
|
+
func textViewDidChangeSelection(_ textView: UITextView) {
|
|
2045
|
+
guard !isSettingText else { return }
|
|
2046
|
+
reportSelection()
|
|
2047
|
+
}
|
|
2048
|
+
|
|
2049
|
+
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
|
|
2050
|
+
// The return key arrives as a lone line break. Only that one is the key:
|
|
2051
|
+
// a pasted line break is text, and goes in whatever the submit behaviour.
|
|
2052
|
+
guard text == "\n", (textView as? HiddenTextView)?.isPasting != true else { return true }
|
|
2053
|
+
// `newline` is the one behaviour that inserts it.
|
|
2054
|
+
return !handleReturnKey()
|
|
2055
|
+
}
|
|
2056
|
+
}
|
|
2057
|
+
|
|
2058
|
+
// MARK: - UITextFieldDelegate
|
|
2059
|
+
|
|
2060
|
+
extension NitroInputView: UITextFieldDelegate {
|
|
2061
|
+
|
|
2062
|
+
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
|
|
2063
|
+
// Like React Native's `onKeyPress`: fires before the text changes, with
|
|
2064
|
+
// 'Backspace' for a deletion and the inserted string otherwise.
|
|
2065
|
+
if worklets.onKeyPress != 0 {
|
|
2066
|
+
margelo.nitro.nitroinput.nitroinputworklets.runKeyPress(Int32(worklets.onKeyPress), std.string(string.isEmpty ? "Backspace" : string))
|
|
2067
|
+
}
|
|
2068
|
+
if let onKeyPress {
|
|
2069
|
+
onKeyPress(string.isEmpty ? "Backspace" : string)
|
|
2070
|
+
}
|
|
2071
|
+
let current = text
|
|
2072
|
+
let start = Self.codePointOffset(in: current, utf16: range.location)
|
|
2073
|
+
let end = Self.codePointOffset(in: current, utf16: range.location + range.length)
|
|
2074
|
+
var newText: String
|
|
2075
|
+
var caret: Int
|
|
2076
|
+
switch format.mode {
|
|
2077
|
+
case .number:
|
|
2078
|
+
// Run the edit through the formatter and apply the result ourselves, so
|
|
2079
|
+
// the field never shows an unformatted frame.
|
|
2080
|
+
let edit = formatter.applyEdit(std.string(current), Int32(start), Int32(end), std.string(string))
|
|
2081
|
+
guard edit.accepted else { return false }
|
|
2082
|
+
newText = String(edit.text)
|
|
2083
|
+
caret = Int(edit.caret)
|
|
2084
|
+
case .mask:
|
|
2085
|
+
// The mask owns the whole edit: it decides what the text and caret become.
|
|
2086
|
+
let result = maskEngine.applyEdit(std.string(current), Int32(start), Int32(end), std.string(string),
|
|
2087
|
+
format.maskAutocomplete, format.maskAutoSkip)
|
|
2088
|
+
newText = String(result.formattedText)
|
|
2089
|
+
caret = Int(result.caret)
|
|
2090
|
+
case .text:
|
|
2091
|
+
// Without a transform or a length limit the field edits itself (keeps
|
|
2092
|
+
// marked text / autocorrect intact); `fieldEditingChanged` reports it.
|
|
2093
|
+
guard worklets.transform != 0 || format.maxLength > 0, let swiftRange = Range(range, in: current) else { return true }
|
|
2094
|
+
var replacement = string
|
|
2095
|
+
if format.maxLength > 0 {
|
|
2096
|
+
// Keep as much of the replacement as fits (a paste), or nothing.
|
|
2097
|
+
let room = format.maxLength - (current.unicodeScalars.count - (end - start))
|
|
2098
|
+
if !string.isEmpty && room <= 0 { return false }
|
|
2099
|
+
if string.unicodeScalars.count > room {
|
|
2100
|
+
var view = String.UnicodeScalarView()
|
|
2101
|
+
view.append(contentsOf: string.unicodeScalars.prefix(max(0, room)))
|
|
2102
|
+
replacement = String(view)
|
|
2103
|
+
}
|
|
2104
|
+
}
|
|
2105
|
+
newText = current
|
|
2106
|
+
newText.replaceSubrange(swiftRange, with: replacement)
|
|
2107
|
+
caret = start + replacement.unicodeScalars.count
|
|
2108
|
+
}
|
|
2109
|
+
var selectionEnd = caret
|
|
2110
|
+
if worklets.transform != 0 {
|
|
2111
|
+
let result = margelo.nitro.nitroinput.nitroinputworklets.runTransform(
|
|
2112
|
+
Int32(worklets.transform), std.string(newText), std.string(current), Int32(caret), Int32(caret), Int32(start), Int32(end))
|
|
2113
|
+
if result.applied {
|
|
2114
|
+
newText = String(result.text)
|
|
2115
|
+
let count = newText.unicodeScalars.count
|
|
2116
|
+
caret = Int(result.selectionStart) < 0 ? count : min(Int(result.selectionStart), count)
|
|
2117
|
+
selectionEnd = min(max(caret, Int(result.selectionEnd)), count)
|
|
2118
|
+
}
|
|
2119
|
+
}
|
|
2120
|
+
// The common keystroke: the formatter and transform changed nothing beyond
|
|
2121
|
+
// the typed characters, and the caret lands where UIKit would put it. Let
|
|
2122
|
+
// the field apply the edit itself (its incremental path is far cheaper than
|
|
2123
|
+
// replacing the text); `fieldEditingChanged` then reports it.
|
|
2124
|
+
if let swiftRange = Range(range, in: current), selectionEnd == caret,
|
|
2125
|
+
caret == start + string.unicodeScalars.count {
|
|
2126
|
+
var plain = current
|
|
2127
|
+
plain.replaceSubrange(swiftRange, with: string)
|
|
2128
|
+
if plain == newText { return true }
|
|
2129
|
+
}
|
|
2130
|
+
isSettingText = true
|
|
2131
|
+
replaceMinimally(in: textField, with: newText)
|
|
2132
|
+
let from = Self.utf16Offset(in: newText, codePoint: caret)
|
|
2133
|
+
let to = Self.utf16Offset(in: newText, codePoint: selectionEnd)
|
|
2134
|
+
if let fromPosition = textField.position(from: textField.beginningOfDocument, offset: from),
|
|
2135
|
+
let toPosition = textField.position(from: textField.beginningOfDocument, offset: to) {
|
|
2136
|
+
textField.selectedTextRange = textField.textRange(from: fromPosition, to: toPosition)
|
|
2137
|
+
}
|
|
2138
|
+
isSettingText = false
|
|
2139
|
+
textDidChange(caret: caret, reason: .user)
|
|
2140
|
+
return false
|
|
2141
|
+
}
|
|
2142
|
+
|
|
2143
|
+
/// Replaces only the span that differs between the field's text and `newText`
|
|
2144
|
+
/// (a comma that appeared, a mask's punctuation): `UITextField.text = ...`
|
|
2145
|
+
/// rebuilds the whole text storage and was the bulk of a keystroke's cost.
|
|
2146
|
+
private func replaceMinimally(in textField: UITextField, with newText: String) {
|
|
2147
|
+
let current = Array((textField.text ?? "").utf16)
|
|
2148
|
+
let next = Array(newText.utf16)
|
|
2149
|
+
var prefix = 0
|
|
2150
|
+
while prefix < current.count, prefix < next.count, current[prefix] == next[prefix] { prefix += 1 }
|
|
2151
|
+
var suffix = 0
|
|
2152
|
+
while suffix < current.count - prefix, suffix < next.count - prefix,
|
|
2153
|
+
current[current.count - 1 - suffix] == next[next.count - 1 - suffix] { suffix += 1 }
|
|
2154
|
+
guard prefix + suffix < current.count || prefix + suffix < next.count else { return }
|
|
2155
|
+
let replacement = String(utf16CodeUnits: Array(next[prefix..<(next.count - suffix)]), count: next.count - suffix - prefix)
|
|
2156
|
+
if let from = textField.position(from: textField.beginningOfDocument, offset: prefix),
|
|
2157
|
+
let to = textField.position(from: textField.beginningOfDocument, offset: current.count - suffix),
|
|
2158
|
+
let textRange = textField.textRange(from: from, to: to) {
|
|
2159
|
+
textField.replace(textRange, withText: replacement)
|
|
2160
|
+
} else {
|
|
2161
|
+
textField.text = newText
|
|
2162
|
+
}
|
|
2163
|
+
}
|
|
2164
|
+
|
|
2165
|
+
func textFieldDidBeginEditing(_ textField: UITextField) {
|
|
2166
|
+
if traits.clearTextOnFocus {
|
|
2167
|
+
setText("", reason: .user)
|
|
2168
|
+
} else if traits.selectTextOnFocus {
|
|
2169
|
+
// In the next runloop turn: UIKit sets its own selection as it begins.
|
|
2170
|
+
DispatchQueue.main.async { [weak self] in
|
|
2171
|
+
guard let self, self.editor.isFirstResponder else { return }
|
|
2172
|
+
self.editor.selectAll(nil)
|
|
2173
|
+
}
|
|
2174
|
+
}
|
|
2175
|
+
if contentOverflows { render() }
|
|
2176
|
+
updateCaret(restartBlink: true)
|
|
2177
|
+
if worklets.onFocusChange != 0 {
|
|
2178
|
+
margelo.nitro.nitroinput.nitroinputworklets.runFocusChange(Int32(worklets.onFocusChange), true, std.string(text))
|
|
2179
|
+
}
|
|
2180
|
+
onFocusChange?(true)
|
|
2181
|
+
if wantsFrameDrawing { layoutFrame(animated: true) }
|
|
2182
|
+
}
|
|
2183
|
+
|
|
2184
|
+
func textFieldDidEndEditing(_ textField: UITextField) {
|
|
2185
|
+
if contentOverflows { render() }
|
|
2186
|
+
updateCaret()
|
|
2187
|
+
if worklets.onFocusChange != 0 {
|
|
2188
|
+
margelo.nitro.nitroinput.nitroinputworklets.runFocusChange(Int32(worklets.onFocusChange), false, std.string(text))
|
|
2189
|
+
}
|
|
2190
|
+
if worklets.onEndEditing != 0 {
|
|
2191
|
+
margelo.nitro.nitroinput.nitroinputworklets.runEndEditing(Int32(worklets.onEndEditing), std.string(text))
|
|
2192
|
+
}
|
|
2193
|
+
onFocusChange?(false)
|
|
2194
|
+
onEndEditing?(text)
|
|
2195
|
+
if wantsFrameDrawing { layoutFrame(animated: true) }
|
|
2196
|
+
}
|
|
2197
|
+
|
|
2198
|
+
func textFieldDidChangeSelection(_ textField: UITextField) {
|
|
2199
|
+
guard !isSettingText else { return }
|
|
2200
|
+
// A caret move alone does not re-render; when the content is wider than
|
|
2201
|
+
// the view the scroll offset has to follow it.
|
|
2202
|
+
if contentOverflows { render() }
|
|
2203
|
+
updateCaret(restartBlink: true)
|
|
2204
|
+
reportSelection()
|
|
2205
|
+
}
|
|
2206
|
+
|
|
2207
|
+
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
|
|
2208
|
+
handleReturnKey()
|
|
2209
|
+
return false
|
|
2210
|
+
}
|
|
2211
|
+
|
|
2212
|
+
/// The return key, as React Native's `TextInput` takes it on iOS:
|
|
2213
|
+
/// `blurAndSubmit` submits and dismisses the keyboard, `submit` submits and
|
|
2214
|
+
/// keeps focus so a form can move on itself, and `newline` does neither (a
|
|
2215
|
+
/// wrapping field inserts the line break instead; a single line does
|
|
2216
|
+
/// nothing). Returns whether the press was taken as a submit.
|
|
2217
|
+
@discardableResult
|
|
2218
|
+
private func handleReturnKey() -> Bool {
|
|
2219
|
+
let submits = traits.submitBehavior != .newline
|
|
2220
|
+
if worklets.onKeyPress != 0 {
|
|
2221
|
+
margelo.nitro.nitroinput.nitroinputworklets.runKeyPress(Int32(worklets.onKeyPress), std.string("Enter"))
|
|
2222
|
+
}
|
|
2223
|
+
if submits, worklets.onSubmitEditing != 0 {
|
|
2224
|
+
margelo.nitro.nitroinput.nitroinputworklets.runSubmitEditing(Int32(worklets.onSubmitEditing), std.string(text))
|
|
2225
|
+
}
|
|
2226
|
+
onKeyPress?("Enter")
|
|
2227
|
+
if submits { onSubmit?(text) }
|
|
2228
|
+
if traits.submitBehavior == .blurAndSubmit {
|
|
2229
|
+
editor.resignFirstResponder()
|
|
2230
|
+
}
|
|
2231
|
+
return submits
|
|
2232
|
+
}
|
|
2233
|
+
|
|
2234
|
+
/// Reports the caret/selection in code points, and only when it moved.
|
|
2235
|
+
private func reportSelection() {
|
|
2236
|
+
// A worklet handler counts as a listener too - guarding on the JS one
|
|
2237
|
+
// alone would make a field with only a worklet report nothing.
|
|
2238
|
+
guard onSelectionChange != nil || worklets.onSelectionChange != 0 else { return }
|
|
2239
|
+
guard field.selectedTextRange != nil else { return }
|
|
2240
|
+
let (start, end) = selectionCodePoints()
|
|
2241
|
+
guard lastReportedSelection == nil || lastReportedSelection! != (start, end) else { return }
|
|
2242
|
+
lastReportedSelection = (start, end)
|
|
2243
|
+
if worklets.onSelectionChange != 0 {
|
|
2244
|
+
margelo.nitro.nitroinput.nitroinputworklets.runSelectionChange(Int32(worklets.onSelectionChange), Int32(start), Int32(end))
|
|
2245
|
+
}
|
|
2246
|
+
onSelectionChange?(start, end)
|
|
2247
|
+
}
|
|
2248
|
+
}
|
|
2249
|
+
|
|
2250
|
+
// MARK: - Outlined / filled frame
|
|
2251
|
+
|
|
2252
|
+
extension NitroInputView {
|
|
2253
|
+
|
|
2254
|
+
/// Material's ratio: the floated label is three quarters of the body size.
|
|
2255
|
+
private static let floatedLabelRatio: CGFloat = 0.75
|
|
2256
|
+
/// Breathing room either side of the label inside the notch.
|
|
2257
|
+
private static let labelGapPadding: CGFloat = 4
|
|
2258
|
+
/// Inset of the label (and the text below it) from the leading edge.
|
|
2259
|
+
/// Material uses 16; a large corner radius needs more, or the notch opens
|
|
2260
|
+
/// flush against the corner arc and the run of line before it disappears.
|
|
2261
|
+
private var labelInset: CGFloat { max(16, inputFrame.cornerRadius + 8) }
|
|
2262
|
+
// Timings taken from Material's own text fields. The label runs the whole
|
|
2263
|
+
// duration on the standard decelerate curve; the notch is staggered behind
|
|
2264
|
+
// it, because the label has to travel most of the way to the top edge before
|
|
2265
|
+
// there is anything for a hole to be under. Closing is quicker than opening -
|
|
2266
|
+
// the gap should be gone before the label lands back inside the box.
|
|
2267
|
+
//
|
|
2268
|
+
// MUI's OutlinedInput: label 200ms cubic-bezier(0,0,0.2,1); legend max-width
|
|
2269
|
+
// 100ms after a 50ms delay when notching, 50ms flat when un-notching.
|
|
2270
|
+
// Material Components Android runs both off one animator instead (167ms, or
|
|
2271
|
+
// 400ms `motionDurationMedium4` under an M3 theme) and snaps the stroke.
|
|
2272
|
+
private static let frameAnimationDuration: CFTimeInterval = 0.2
|
|
2273
|
+
private static let notchOpenDelay: CFTimeInterval = 0.05
|
|
2274
|
+
private static let notchOpenDuration: CFTimeInterval = 0.1
|
|
2275
|
+
private static var notchOpenTotal: CFTimeInterval { notchOpenDelay + notchOpenDuration }
|
|
2276
|
+
private static let notchCloseDuration: CFTimeInterval = 0.05
|
|
2277
|
+
/// Material's standard decelerate. UIKit's named `.easeOut` is much weaker
|
|
2278
|
+
/// (0, 0, 0.58, 1), which is what made the move read as abrupt.
|
|
2279
|
+
private static func decelerate() -> CAMediaTimingFunction {
|
|
2280
|
+
CAMediaTimingFunction(controlPoints: 0, 0, 0.2, 1)
|
|
2281
|
+
}
|
|
2282
|
+
|
|
2283
|
+
var wantsFrameDrawing: Bool { inputFrame.draws }
|
|
2284
|
+
|
|
2285
|
+
/// A label resting inside the field already labels it, so the placeholder
|
|
2286
|
+
/// waits until the label has floated clear rather than printing over it.
|
|
2287
|
+
var effectivePlaceholder: String {
|
|
2288
|
+
guard inputFrame.hasLabel, !labelShouldFloat else { return format.placeholder }
|
|
2289
|
+
return ""
|
|
2290
|
+
}
|
|
2291
|
+
|
|
2292
|
+
/// The label floats once the field is focused or holds text - or always, if
|
|
2293
|
+
/// the caller asked for that.
|
|
2294
|
+
private var labelShouldFloat: Bool {
|
|
2295
|
+
guard inputFrame.hasLabel else { return false }
|
|
2296
|
+
if inputFrame.labelBehavior == .always { return true }
|
|
2297
|
+
return editor.isFirstResponder || !text.isEmpty
|
|
2298
|
+
}
|
|
2299
|
+
|
|
2300
|
+
private var restingLabelFont: UIFont { fonts.font(for: .body) }
|
|
2301
|
+
|
|
2302
|
+
private var floatedLabelSize: CGFloat {
|
|
2303
|
+
let explicit = inputFrame.labelFontSize
|
|
2304
|
+
if explicit > 0 { return explicit }
|
|
2305
|
+
return max(9, restingLabelFont.pointSize * Self.floatedLabelRatio)
|
|
2306
|
+
}
|
|
2307
|
+
|
|
2308
|
+
// The frame is drawn in `CGColor`s, which have no appearance of their own:
|
|
2309
|
+
// each is resolved against the view's traits here, and an appearance change
|
|
2310
|
+
// lays the frame out again (`syncWithTraits`).
|
|
2311
|
+
private var resolvedOutlineColor: UIColor {
|
|
2312
|
+
let base = inputFrame.strokeColor ?? UIColor.separator
|
|
2313
|
+
let color = editor.isFirstResponder ? (inputFrame.focusedStrokeColor ?? base) : base
|
|
2314
|
+
return color.resolvedColor(with: traitCollection)
|
|
2315
|
+
}
|
|
2316
|
+
|
|
2317
|
+
private var resolvedLabelColor: UIColor {
|
|
2318
|
+
let color = editor.isFirstResponder
|
|
2319
|
+
? inputFrame.labelFocusedColor ?? inputFrame.focusedStrokeColor ?? typography.placeholderColor
|
|
2320
|
+
: inputFrame.labelColor ?? typography.placeholderColor
|
|
2321
|
+
return color.resolvedColor(with: traitCollection)
|
|
2322
|
+
}
|
|
2323
|
+
|
|
2324
|
+
private var resolvedFillColor: UIColor {
|
|
2325
|
+
(inputFrame.fillColor ?? UIColor.secondarySystemFill).resolvedColor(with: traitCollection)
|
|
2326
|
+
}
|
|
2327
|
+
|
|
2328
|
+
/// Applies everything that does not depend on the bounds, then lays out.
|
|
2329
|
+
func applyFrame() {
|
|
2330
|
+
guard inputFrame.draws else {
|
|
2331
|
+
if didBuildFrameLayers {
|
|
2332
|
+
frameLayer.isHidden = true
|
|
2333
|
+
labelLayer.isHidden = true
|
|
2334
|
+
underlineLayer.isHidden = true
|
|
2335
|
+
}
|
|
2336
|
+
syncAccessibilityFromHost()
|
|
2337
|
+
updateFieldInsets()
|
|
2338
|
+
return
|
|
2339
|
+
}
|
|
2340
|
+
didBuildFrameLayers = true
|
|
2341
|
+
frameLayer.isHidden = false
|
|
2342
|
+
labelLayer.isHidden = !inputFrame.hasLabel
|
|
2343
|
+
labelLayer.string = inputFrame.label
|
|
2344
|
+
// The label is also the field's accessible name when nothing else gives it
|
|
2345
|
+
// one, so a change to it has to reach VoiceOver.
|
|
2346
|
+
syncAccessibilityFromHost()
|
|
2347
|
+
updateFieldInsets()
|
|
2348
|
+
layoutFrame(animated: false)
|
|
2349
|
+
}
|
|
2350
|
+
|
|
2351
|
+
/// The top inset the label needs when it is floated onto the outline: half of
|
|
2352
|
+
/// it sits above the line, so the text below has to start lower.
|
|
2353
|
+
var frameTopInset: CGFloat {
|
|
2354
|
+
// Only the filled variant needs the room. Its floated label lives inside
|
|
2355
|
+
// the box, on its own line above the text. An outlined field's floated
|
|
2356
|
+
// label sits *on* the stroke, outside the content box entirely - it
|
|
2357
|
+
// intrudes into the top of the frame but never onto the text's line - so
|
|
2358
|
+
// the text stays centred, which is what Material's outlined field does and
|
|
2359
|
+
// what a field with no label at all does. Reserving space for it here left
|
|
2360
|
+
// the text sitting half an inset low.
|
|
2361
|
+
guard inputFrame.hasLabel, inputFrame.variant == .filled else { return 0 }
|
|
2362
|
+
// 1.4 is a fudge, not a Material metric: enough of a gap under the
|
|
2363
|
+
// floated label that the two lines do not crowd at the default sizes.
|
|
2364
|
+
// Material's filled field is specified at a fixed 56dp with its own
|
|
2365
|
+
// baselines; if this field is ever given fixed metrics, derive it there.
|
|
2366
|
+
return floatedLabelSize * 1.4
|
|
2367
|
+
}
|
|
2368
|
+
|
|
2369
|
+
/// The room a framed field keeps above and below its text. Flat, because
|
|
2370
|
+
/// nothing about the vertical middle of the box depends on its corners.
|
|
2371
|
+
static let framePadding: CGFloat = 16
|
|
2372
|
+
|
|
2373
|
+
/// Horizontal room for the frame, so the text lines up under the label
|
|
2374
|
+
/// instead of running into the stroke.
|
|
2375
|
+
var frameSideInset: CGFloat {
|
|
2376
|
+
inputFrame.draws ? labelInset : 0
|
|
2377
|
+
}
|
|
2378
|
+
|
|
2379
|
+
func layoutFrame(animated: Bool) {
|
|
2380
|
+
guard inputFrame.draws, bounds.width > 0, bounds.height > 0 else { return }
|
|
2381
|
+
|
|
2382
|
+
let target: CGFloat = labelShouldFloat ? 1 : 0
|
|
2383
|
+
var snapshot = FrameSnapshot()
|
|
2384
|
+
snapshot.bounds = bounds
|
|
2385
|
+
snapshot.progress = target
|
|
2386
|
+
snapshot.stroke = strokeWidthNow
|
|
2387
|
+
snapshot.focused = editor.isFirstResponder
|
|
2388
|
+
snapshot.label = inputFrame.label
|
|
2389
|
+
snapshot.fontSize = restingLabelFont.pointSize
|
|
2390
|
+
snapshot.frame = inputFrame
|
|
2391
|
+
guard snapshot != lastFrameSnapshot else { return }
|
|
2392
|
+
|
|
2393
|
+
let changed = target != labelProgress
|
|
2394
|
+
// Focusing a field that already holds text does not move the label, but the
|
|
2395
|
+
// stroke still has to travel to its focused colour and weight rather than
|
|
2396
|
+
// snapping to it.
|
|
2397
|
+
let focusChanged = lastFrameSnapshot.focused != snapshot.focused
|
|
2398
|
+
labelProgress = target
|
|
2399
|
+
lastFrameSnapshot = snapshot
|
|
2400
|
+
defer { didLayOutFrame = true }
|
|
2401
|
+
if changed {
|
|
2402
|
+
// The placeholder is hidden behind a resting label and revealed once it
|
|
2403
|
+
// floats, so it has to follow the same transition.
|
|
2404
|
+
syncAccessibilityPlaceholder()
|
|
2405
|
+
feedEngine(caret: -1)
|
|
2406
|
+
}
|
|
2407
|
+
|
|
2408
|
+
let floatedSize = floatedLabelSize
|
|
2409
|
+
let labelText = inputFrame.label as NSString
|
|
2410
|
+
let restingFont = restingLabelFont
|
|
2411
|
+
let floatedFont = restingFont.withSize(floatedSize)
|
|
2412
|
+
let restingWidth = labelText.size(withAttributes: [.font: restingFont]).width
|
|
2413
|
+
let floatedWidth = labelText.size(withAttributes: [.font: floatedFont]).width
|
|
2414
|
+
|
|
2415
|
+
// Resting: on the text's own line. A single line is centred in the box, so
|
|
2416
|
+
// that is `midY`; a wrapping one starts at the top, and the label belongs
|
|
2417
|
+
// where the first character will appear rather than halfway down an empty
|
|
2418
|
+
// field.
|
|
2419
|
+
let restingCentreY = traits.multiline
|
|
2420
|
+
? frameVerticalInset.top + lineBoxHeight / 2
|
|
2421
|
+
: bounds.midY
|
|
2422
|
+
let floatedCentreY = inputFrame.variant == .outlined ? 0 : floatedSize * 0.9
|
|
2423
|
+
// The label sits at the start edge: `labelInset` from the left, or the same
|
|
2424
|
+
// distance from the right under a right-to-left layout. The notch is cut
|
|
2425
|
+
// where the floated label is, so it follows.
|
|
2426
|
+
let restingX = isRTL ? bounds.width - labelInset - restingWidth : labelInset
|
|
2427
|
+
let floatedX = isRTL ? bounds.width - labelInset - floatedWidth : labelInset
|
|
2428
|
+
let resting = Outline.Rect(x: Double(restingX), y: Double(restingCentreY),
|
|
2429
|
+
width: Double(restingWidth), height: Double(restingFont.lineHeight))
|
|
2430
|
+
let floated = Outline.Rect(x: Double(floatedX), y: Double(floatedCentreY),
|
|
2431
|
+
width: Double(floatedWidth), height: Double(floatedFont.lineHeight))
|
|
2432
|
+
|
|
2433
|
+
let filled = inputFrame.variant == .filled
|
|
2434
|
+
var box = Outline.Box()
|
|
2435
|
+
box.width = Double(bounds.width)
|
|
2436
|
+
box.height = Double(bounds.height)
|
|
2437
|
+
box.radius = Double(inputFrame.cornerRadius)
|
|
2438
|
+
// Filled is not stroked, so the path is the fill's own edge rather than the
|
|
2439
|
+
// centre line of a stroke, and its bottom is square: that is the edge the
|
|
2440
|
+
// indicator rule below sits flush against. Rounding it would leave the rule
|
|
2441
|
+
// overhanging the curve at both ends.
|
|
2442
|
+
box.strokeWidth = filled ? 0 : Double(strokeWidthNow)
|
|
2443
|
+
box.bottomRadius = filled ? 0 : -1
|
|
2444
|
+
|
|
2445
|
+
// The notch follows the floated label whatever the progress, so the two
|
|
2446
|
+
// paths we animate between describe the same shape.
|
|
2447
|
+
let gap = inputFrame.hasLabel && !filled
|
|
2448
|
+
? Outline.gapFor(floated, Double(Self.labelGapPadding))
|
|
2449
|
+
: Outline.Gap()
|
|
2450
|
+
let path = Self.cgPath(from: Outline.outline(box, gap, Double(target)))
|
|
2451
|
+
|
|
2452
|
+
let placement = Outline.lerp(resting, floated, Double(target))
|
|
2453
|
+
let scale = floatedWidth > 0 && restingWidth > 0
|
|
2454
|
+
? (target == 1 ? floatedSize / restingFont.pointSize : 1)
|
|
2455
|
+
: 1
|
|
2456
|
+
|
|
2457
|
+
let animating = animated && (changed || focusChanged)
|
|
2458
|
+
CATransaction.begin()
|
|
2459
|
+
if animating {
|
|
2460
|
+
CATransaction.setAnimationDuration(Self.frameAnimationDuration)
|
|
2461
|
+
CATransaction.setAnimationTimingFunction(Self.decelerate())
|
|
2462
|
+
} else {
|
|
2463
|
+
CATransaction.setDisableActions(true)
|
|
2464
|
+
}
|
|
2465
|
+
frameLayer.frame = bounds
|
|
2466
|
+
// `path` is the one animatable CAShapeLayer property with no implicit
|
|
2467
|
+
// animation (UIKit documents the exception), so setting it inside an
|
|
2468
|
+
// animated transaction still snaps. The notch jumping open a frame before
|
|
2469
|
+
// the label reaches it was exactly that. Driving it explicitly hands the
|
|
2470
|
+
// interpolation to Core Animation - the render server tweens it off the
|
|
2471
|
+
// main thread, with no display link and nothing in JS - and the stroke
|
|
2472
|
+
// travels with it. The two paths always have the same verbs, which is what
|
|
2473
|
+
// makes them interpolable at all; see `OutlineGeometry.hpp`.
|
|
2474
|
+
animateShape(
|
|
2475
|
+
path: path,
|
|
2476
|
+
lineWidth: strokeWidthNow,
|
|
2477
|
+
strokeColor: filled ? nil : resolvedOutlineColor.cgColor,
|
|
2478
|
+
fillColor: filled ? resolvedFillColor.cgColor : nil,
|
|
2479
|
+
animated: animating,
|
|
2480
|
+
opening: target == 1,
|
|
2481
|
+
)
|
|
2482
|
+
|
|
2483
|
+
if filled {
|
|
2484
|
+
underlineLayer.isHidden = false
|
|
2485
|
+
let thickness = strokeWidthNow
|
|
2486
|
+
underlineLayer.frame = CGRect(x: 0, y: bounds.height - thickness, width: bounds.width, height: thickness)
|
|
2487
|
+
underlineLayer.backgroundColor = resolvedOutlineColor.cgColor
|
|
2488
|
+
} else if didBuildFrameLayers {
|
|
2489
|
+
underlineLayer.isHidden = true
|
|
2490
|
+
}
|
|
2491
|
+
|
|
2492
|
+
labelLayer.fontSize = restingFont.pointSize
|
|
2493
|
+
labelLayer.font = CGFont(restingFont.fontName as CFString)
|
|
2494
|
+
labelLayer.foregroundColor = resolvedLabelColor.cgColor
|
|
2495
|
+
labelLayer.bounds = CGRect(x: 0, y: 0, width: restingWidth + 1, height: restingFont.lineHeight)
|
|
2496
|
+
labelLayer.position = CGPoint(x: CGFloat(placement.x), y: CGFloat(placement.y))
|
|
2497
|
+
labelLayer.transform = CATransform3DMakeScale(scale, scale, 1)
|
|
2498
|
+
CATransaction.commit()
|
|
2499
|
+
}
|
|
2500
|
+
|
|
2501
|
+
/// A focused outlined field draws a heavier line, as Material does.
|
|
2502
|
+
private var strokeWidthNow: CGFloat {
|
|
2503
|
+
guard inputFrame.draws else { return inputFrame.strokeWidth }
|
|
2504
|
+
return editor.isFirstResponder ? inputFrame.strokeWidth * 2 : inputFrame.strokeWidth
|
|
2505
|
+
}
|
|
2506
|
+
|
|
2507
|
+
/// Replays the shared geometry into a CGPath. The arcs are the same centre /
|
|
2508
|
+
/// radius / angles Android's `Path.arcTo` takes, so both platforms trace it
|
|
2509
|
+
/// identically.
|
|
2510
|
+
/// Moves the frame layer to a new shape, explicitly rather than relying on
|
|
2511
|
+
/// implicit actions. The stroke keeps pace with the path so the outline never
|
|
2512
|
+
/// changes colour or weight ahead of its own geometry.
|
|
2513
|
+
private func animateShape(path: CGPath, lineWidth: CGFloat, strokeColor: CGColor?, fillColor: CGColor?,
|
|
2514
|
+
animated: Bool, opening: Bool) {
|
|
2515
|
+
// Read the presentation layer first: an interrupted run continues from
|
|
2516
|
+
// wherever it had got to rather than snapping back to its target.
|
|
2517
|
+
let live = frameLayer.presentation()
|
|
2518
|
+
let fromPath = live?.path ?? frameLayer.path
|
|
2519
|
+
let fromWidth = live?.lineWidth ?? frameLayer.lineWidth
|
|
2520
|
+
let fromStroke = live?.strokeColor ?? frameLayer.strokeColor
|
|
2521
|
+
let fromFill = live?.fillColor ?? frameLayer.fillColor
|
|
2522
|
+
|
|
2523
|
+
frameLayer.removeAnimation(forKey: Self.shapeAnimationKey)
|
|
2524
|
+
frameLayer.path = path
|
|
2525
|
+
frameLayer.lineWidth = lineWidth
|
|
2526
|
+
frameLayer.strokeColor = strokeColor
|
|
2527
|
+
frameLayer.fillColor = fillColor
|
|
2528
|
+
guard animated, let fromPath else { return }
|
|
2529
|
+
|
|
2530
|
+
func basic(_ keyPath: String, _ from: Any?, _ to: Any?) -> CABasicAnimation? {
|
|
2531
|
+
guard from != nil || to != nil else { return nil }
|
|
2532
|
+
let animation = CABasicAnimation(keyPath: keyPath)
|
|
2533
|
+
animation.fromValue = from
|
|
2534
|
+
animation.toValue = to
|
|
2535
|
+
// Set on every child rather than only on the group: a group's timing
|
|
2536
|
+
// function governs the group's own clock, not its children's, so the
|
|
2537
|
+
// children would otherwise run linear.
|
|
2538
|
+
animation.timingFunction = Self.decelerate()
|
|
2539
|
+
return animation
|
|
2540
|
+
}
|
|
2541
|
+
|
|
2542
|
+
// The notch's delay is a keyframe hold, not a `beginTime`. A delayed
|
|
2543
|
+
// animation is a thing that has not started yet, and any of the layout
|
|
2544
|
+
// passes that follow a focus change will pre-empt it before it does - the
|
|
2545
|
+
// gap then jumped open in a single frame. A keyframe is running from the
|
|
2546
|
+
// first frame; it just has not moved yet.
|
|
2547
|
+
let notch = CAKeyframeAnimation(keyPath: "path")
|
|
2548
|
+
notch.calculationMode = .linear
|
|
2549
|
+
if opening {
|
|
2550
|
+
notch.values = [fromPath, fromPath, path]
|
|
2551
|
+
notch.keyTimes = [0, NSNumber(value: Self.notchOpenDelay / Self.notchOpenTotal), 1]
|
|
2552
|
+
notch.duration = Self.notchOpenTotal
|
|
2553
|
+
notch.timingFunctions = [CAMediaTimingFunction(name: .linear), Self.decelerate()]
|
|
2554
|
+
} else {
|
|
2555
|
+
notch.values = [fromPath, path]
|
|
2556
|
+
notch.keyTimes = [0, 1]
|
|
2557
|
+
notch.duration = Self.notchCloseDuration
|
|
2558
|
+
notch.timingFunctions = [Self.decelerate()]
|
|
2559
|
+
}
|
|
2560
|
+
|
|
2561
|
+
// The stroke travels with the label, over the full duration.
|
|
2562
|
+
let group = CAAnimationGroup()
|
|
2563
|
+
group.duration = Self.frameAnimationDuration
|
|
2564
|
+
group.animations = [
|
|
2565
|
+
notch,
|
|
2566
|
+
basic("lineWidth", fromWidth, lineWidth),
|
|
2567
|
+
basic("strokeColor", fromStroke, strokeColor),
|
|
2568
|
+
basic("fillColor", fromFill, fillColor),
|
|
2569
|
+
].compactMap { $0 }
|
|
2570
|
+
frameLayer.add(group, forKey: Self.shapeAnimationKey)
|
|
2571
|
+
}
|
|
2572
|
+
|
|
2573
|
+
private static let shapeAnimationKey = "nitroFrameShape"
|
|
2574
|
+
|
|
2575
|
+
private static func cgPath<S: Sequence>(from segments: S) -> CGPath where S.Element == Outline.Segment {
|
|
2576
|
+
let path = CGMutablePath()
|
|
2577
|
+
for segment in segments {
|
|
2578
|
+
let point = CGPoint(x: CGFloat(segment.point.x), y: CGFloat(segment.point.y))
|
|
2579
|
+
switch segment.verb {
|
|
2580
|
+
case .Move:
|
|
2581
|
+
path.move(to: point)
|
|
2582
|
+
case .Line:
|
|
2583
|
+
path.addLine(to: point)
|
|
2584
|
+
case .Arc:
|
|
2585
|
+
// `addRelativeArc` takes a signed sweep, so there is no `clockwise`
|
|
2586
|
+
// flag to get the wrong way round under the y-down flip - which drew
|
|
2587
|
+
// 270-degree arcs. It is also the exact shape of Android's
|
|
2588
|
+
// `Path.arcTo(oval, start, sweep)`, so both platforms trace the same
|
|
2589
|
+
// geometry from the same numbers.
|
|
2590
|
+
path.addRelativeArc(center: point,
|
|
2591
|
+
radius: CGFloat(segment.radius),
|
|
2592
|
+
startAngle: CGFloat(segment.startAngle) * .pi / 180,
|
|
2593
|
+
delta: CGFloat(segment.sweepAngle) * .pi / 180)
|
|
2594
|
+
@unknown default:
|
|
2595
|
+
break
|
|
2596
|
+
}
|
|
2597
|
+
}
|
|
2598
|
+
return path
|
|
2599
|
+
}
|
|
2600
|
+
}
|