react-native-nitro-input 0.4.0 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +2 -1
  3. package/android/src/main/java/com/margelo/nitro/nitroinput/DigitSlots.kt +143 -0
  4. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroInputView.kt +6 -0
  5. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroNumberView.kt +24 -1
  6. package/android/src/main/java/com/margelo/nitro/nitroinput/InputFonts.kt +50 -5
  7. package/android/src/main/java/com/margelo/nitro/nitroinput/InputSizing.kt +7 -1
  8. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputView.kt +117 -6
  9. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroNumberView.kt +290 -137
  10. package/ios/HybridNitroInputView.swift +4 -0
  11. package/ios/InputSizing.swift +98 -4
  12. package/ios/NitroInputView.swift +79 -12
  13. package/lib/commonjs/nitrogen/generated/shared/json/NitroInputViewConfig.json +2 -0
  14. package/lib/commonjs/src/NitroInput.js +3 -1
  15. package/lib/commonjs/src/NitroNumber.js +94 -29
  16. package/lib/module/nitrogen/generated/shared/json/NitroInputViewConfig.json +2 -0
  17. package/lib/module/src/NitroInput.js +3 -1
  18. package/lib/module/src/NitroNumber.js +94 -29
  19. package/lib/typescript/src/NitroInput.d.ts +11 -0
  20. package/lib/typescript/src/specs/NitroInput.nitro.d.ts +4 -0
  21. package/lib/typescript/src/specs/NitroInputMeasure.nitro.d.ts +2 -0
  22. package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.cpp +18 -0
  23. package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.hpp +4 -0
  24. package/nitrogen/generated/android/c++/JNitroInputSizing.hpp +9 -1
  25. package/nitrogen/generated/android/c++/views/JHybridNitroInputViewStateUpdater.cpp +10 -0
  26. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroInputViewSpec.kt +12 -0
  27. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputSizing.kt +12 -2
  28. package/nitrogen/generated/ios/c++/HybridNitroInputViewSpecSwift.hpp +12 -0
  29. package/nitrogen/generated/ios/c++/views/HybridNitroInputViewComponent.mm +12 -0
  30. package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec.swift +2 -0
  31. package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec_cxx.swift +22 -0
  32. package/nitrogen/generated/ios/swift/NitroInputSizing.swift +12 -2
  33. package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.cpp +4 -0
  34. package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.hpp +4 -0
  35. package/nitrogen/generated/shared/c++/NitroInputSizing.hpp +9 -1
  36. package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.cpp +4 -0
  37. package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.hpp +6 -0
  38. package/nitrogen/generated/shared/json/NitroInputViewConfig.json +2 -0
  39. package/package.json +1 -1
  40. package/src/NitroInput.tsx +14 -0
  41. package/src/NitroNumber.tsx +121 -54
  42. package/src/specs/NitroInput.nitro.ts +4 -0
  43. package/src/specs/NitroInputMeasure.nitro.ts +2 -0
@@ -47,6 +47,8 @@ protocol InputSizingProps {
47
47
  var textWeight: Double { get }
48
48
  var textFamily: String { get }
49
49
  var textLetterSpacing: Double { get }
50
+ var tabularNums: Bool { get }
51
+ var slotDigits: Bool { get }
50
52
  var prefixSpacing: Double { get }
51
53
  var suffixSpacing: Double { get }
52
54
  var allowFontScaling: Bool { get }
@@ -108,6 +110,8 @@ enum InputMapping {
108
110
  typography.fontWeight = CGFloat(p.textWeight.isFinite ? p.textWeight : 400)
109
111
  typography.fontFamily = p.textFamily.isEmpty ? nil : p.textFamily
110
112
  typography.letterSpacing = CGFloat(p.textLetterSpacing.isFinite ? p.textLetterSpacing : 0)
113
+ typography.tabularNums = p.tabularNums
114
+ typography.slotDigits = p.slotDigits
111
115
  typography.prefixSpacing = p.prefixSpacing.isFinite ? CGFloat(p.prefixSpacing) : nil
112
116
  typography.suffixSpacing = p.suffixSpacing.isFinite ? CGFloat(p.suffixSpacing) : nil
113
117
  typography.allowFontScaling = p.allowFontScaling
@@ -215,6 +219,17 @@ final class InputMetrics {
215
219
  let lineBoxHeight: CGFloat
216
220
  /// The advance of one of the bullets a plain secure field draws (see `init`).
217
221
  let secureBulletWidth: CGFloat
222
+ /// The body's digit advances when they are slotted (`tabularNums` set) and
223
+ /// the font has no tabular figures; nil otherwise. The monospaced-numbers feature asks for them, but a font
224
+ /// without it (Open Runde) keeps proportional digits: every typed "1" was
225
+ /// narrower than the placeholder's "0" it replaced, so `keepPlaceholder`'s
226
+ /// tail slid left on each keystroke and an amount changed width as its
227
+ /// digits did. Such a font's digits each get a slot as wide as the widest,
228
+ /// centred in it, as NitroNumber's columns do (and as Android's DigitSlots
229
+ /// does). The affixes keep their own: they never change under the typing.
230
+ let bodyDigitWidths: [CGFloat]?
231
+ /// The slot a body digit is laid out in, when `bodyDigitWidths` is set.
232
+ let bodySlot: CGFloat
218
233
  private var widthCache: [WidthKey: CGFloat] = [:]
219
234
 
220
235
  private struct WidthKey: Hashable {
@@ -224,9 +239,11 @@ final class InputMetrics {
224
239
 
225
240
  init(_ t: NitroInputView.Typography) {
226
241
  let scale = NitroInputView.systemFontMultiplier(t)
227
- body = NitroInputView.makeFont(size: t.fontSize * scale, weight: t.fontWeight, family: t.fontFamily)
228
- prefix = NitroInputView.makeFont(size: (t.prefixFontSize ?? t.fontSize) * scale, weight: t.fontWeight, family: t.fontFamily)
229
- suffix = NitroInputView.makeFont(size: (t.suffixFontSize ?? t.fontSize) * scale, weight: t.fontWeight, family: t.fontFamily)
242
+ body = NitroInputView.makeFont(size: t.fontSize * scale, weight: t.fontWeight, family: t.fontFamily, tabular: t.tabularNums)
243
+ prefix = NitroInputView.makeFont(size: (t.prefixFontSize ?? t.fontSize) * scale, weight: t.fontWeight, family: t.fontFamily,
244
+ tabular: t.tabularNums)
245
+ suffix = NitroInputView.makeFont(size: (t.suffixFontSize ?? t.fontSize) * scale, weight: t.fontWeight, family: t.fontFamily,
246
+ tabular: t.tabularNums)
230
247
  bodySpacing = t.letterSpacing * scale
231
248
  prefixLetterSpacing = t.letterSpacing * scale * (prefix.pointSize / body.pointSize)
232
249
  suffixLetterSpacing = t.letterSpacing * scale * (suffix.pointSize / body.pointSize)
@@ -245,6 +262,10 @@ final class InputMetrics {
245
262
  ? UIFont.systemFont(ofSize: body.pointSize, weight: NitroInputView.uiWeight(t.fontWeight))
246
263
  : UIFont.systemFont(ofSize: body.pointSize)
247
264
  secureBulletWidth = ("\u{2219}" as NSString).size(withAttributes: [.font: bulletFont]).width
265
+ let bodyFont = body
266
+ let digits = (0..<10).map { NSAttributedString(string: String($0), attributes: [.font: bodyFont, .kern: 0]).size().width }
267
+ bodySlot = digits.max() ?? 0
268
+ bodyDigitWidths = t.slotDigits && bodySlot - (digits.min() ?? 0) > bodyFont.pointSize * 0.01 ? digits : nil
248
269
  }
249
270
 
250
271
  func font(for role: NitroInputView.GlyphRole) -> UIFont {
@@ -268,11 +289,84 @@ final class InputMetrics {
268
289
  func width(of text: String, role: NitroInputView.GlyphRole) -> CGFloat {
269
290
  let key = WidthKey(text: text, role: role)
270
291
  if let cached = widthCache[key] { return cached }
271
- let width = NSAttributedString(string: text, attributes: [.font: font(for: role), .kern: 0]).size().width
292
+ var width = NSAttributedString(string: text, attributes: [.font: font(for: role), .kern: 0]).size().width
293
+ if role == .body, bodyDigitWidths != nil {
294
+ for scalar in text.unicodeScalars { width += 2 * halfRoom(scalar) }
295
+ }
272
296
  widthCache[key] = width
273
297
  return width
274
298
  }
275
299
 
300
+ private static func digit(_ scalar: Unicode.Scalar) -> Int? {
301
+ scalar.value >= 0x30 && scalar.value <= 0x39 ? Int(scalar.value - 0x30) : nil
302
+ }
303
+
304
+ /// Half the room a body digit's slot leaves beside its glyph (0 for anything else).
305
+ private func halfRoom(_ scalar: Unicode.Scalar) -> CGFloat {
306
+ guard let widths = bodyDigitWidths, let digit = Self.digit(scalar) else { return 0 }
307
+ return (bodySlot - widths[digit]) / 2
308
+ }
309
+
310
+ private var pairKernCache: [UInt64: CGFloat] = [:]
311
+
312
+ /// The body font's own kerning between `a` and `b`, which non-zero `.kern`s on both leave in place.
313
+ private func pairKern(_ a: Unicode.Scalar, _ b: Unicode.Scalar) -> CGFloat {
314
+ let key = UInt64(a.value) << 32 | UInt64(b.value)
315
+ if let cached = pairKernCache[key] { return cached }
316
+ // The pair with a kern of 1 on both glyphs, against the same with kerning off.
317
+ func line(_ kern: CGFloat) -> CGFloat {
318
+ let pair = NSAttributedString(string: String(a) + String(b), attributes: [.font: body, .kern: kern])
319
+ return CGFloat(CTLineGetTypographicBounds(CTLineCreateWithAttributedString(pair), nil, nil, nil))
320
+ }
321
+ let kern = line(1) - 2 - line(0)
322
+ pairKernCache[key] = kern
323
+ return kern
324
+ }
325
+
326
+ /// How far in from the left of its advance to draw `text` (one glyph): a slotted digit is centred in it.
327
+ func inset(of text: String, role: NitroInputView.GlyphRole) -> CGFloat {
328
+ guard role == .body, let scalar = text.unicodeScalars.first else { return 0 }
329
+ return halfRoom(scalar)
330
+ }
331
+
332
+ /// `text` in `attributes`, kerned for UIKit to lay out as the overlay and the
333
+ /// measure do: the body spacing after every glyph and each digit in its slot.
334
+ /// Kerning only adds room after a glyph, so half a digit's room goes after
335
+ /// the glyph before it and half after its own. A first digit has none before
336
+ /// it: with `lead`, that half is returned for the caller to move the text by
337
+ /// (the tail's label); without, the first line is indented by it (the
338
+ /// field's text and placeholder, which UIKit places itself). Nil when the
339
+ /// digits are not slotted.
340
+ func slotted(_ text: String, attributes: [NSAttributedString.Key: Any], lead: Bool) -> (string: NSAttributedString, lead: CGFloat)? {
341
+ guard bodyDigitWidths != nil else { return nil }
342
+ let result = NSMutableAttributedString(string: text, attributes: attributes)
343
+ let scalars = Array(text.unicodeScalars)
344
+ let halves = scalars.map(halfRoom)
345
+ var leading: CGFloat = 0
346
+ var offset = 0
347
+ let kerns = halves.indices.map { bodySpacing + halves[$0] + ($0 + 1 < halves.count ? halves[$0 + 1] : 0) }
348
+ for (i, scalar) in scalars.enumerated() {
349
+ var kern = kerns[i]
350
+ // The font's kerning between two glyphs comes back once both carry a
351
+ // kern other than 0 (Open Runde kerns "74" by -0.058 em). The measure
352
+ // has it off, so it is taken back out of the first one's.
353
+ if i + 1 < scalars.count, kern != 0, kerns[i + 1] != 0 {
354
+ kern -= pairKern(scalar, scalars[i + 1])
355
+ if kern == 0 { kern = 0.0001 }
356
+ }
357
+ if i == 0 { leading = halves[0] }
358
+ let length = String(scalar).utf16.count
359
+ result.addAttribute(.kern, value: kern, range: NSRange(location: offset, length: length))
360
+ offset += length
361
+ }
362
+ if !lead, leading > 0 {
363
+ let style = ((attributes[.paragraphStyle] as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle) ?? NSMutableParagraphStyle()
364
+ style.firstLineHeadIndent = leading
365
+ result.addAttribute(.paragraphStyle, value: style, range: NSRange(location: 0, length: result.length))
366
+ }
367
+ return (result, leading)
368
+ }
369
+
276
370
  /// The room an affix takes beside the text: its glyphs, their spacing and the seam.
277
371
  func affixRoom(_ affix: String, role: NitroInputView.GlyphRole) -> CGFloat {
278
372
  guard !affix.isEmpty else { return 0 }
@@ -144,6 +144,10 @@ final class NitroInputView: UIView {
144
144
  var suffixAlign: AffixAlign = .baseline
145
145
  /// Points added after every glyph, as `Text`'s letterSpacing; an affix gets it in proportion to its size.
146
146
  var letterSpacing: CGFloat = 0
147
+ /// The font's tabular figures rather than its proportional ones.
148
+ var tabularNums = true
149
+ /// Every digit laid out as wide as the widest, centred (`InputMetrics.bodyDigitWidths`): tabular figures for a font without them.
150
+ var slotDigits = false
147
151
  /// Points between the prefix and the text, and between the text and the suffix, in place of the letter spacing there.
148
152
  var prefixSpacing: CGFloat? = nil
149
153
  var suffixSpacing: CGFloat? = nil
@@ -293,6 +297,9 @@ final class NitroInputView: UIView {
293
297
  didSet {
294
298
  guard alignment != oldValue else { return }
295
299
  field.textAlignment = textAlignment(for: alignment)
300
+ // The new alignment is the field's paragraph style, which the slots' indent rides on.
301
+ applyDigitSlots()
302
+ syncAccessibilityPlaceholder()
296
303
  render()
297
304
  }
298
305
  }
@@ -677,6 +684,8 @@ final class NitroInputView: UIView {
677
684
  private struct GlyphEntry {
678
685
  let layer: CALayer
679
686
  let topOffset: CGFloat
687
+ /// A slotted digit's offset into its advance (`InputMetrics.inset`).
688
+ let leftInset: CGFloat
680
689
  /// The render pass that last saw this glyph; one a pass missed has left.
681
690
  var generation: UInt
682
691
  /// What the layer was last given, so a frame only sets what moved: most
@@ -791,12 +800,18 @@ final class NitroInputView: UIView {
791
800
  // field's own copy exists only so an empty field still has an
792
801
  // accessibility value, hence clear.
793
802
  let color = traits.plain ? typography.placeholderColor : UIColor.clear
794
- let unchanged = field.attributedPlaceholder?.string == placeholder
795
- && field.attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor == color
796
- guard !unchanged || placeholder.isEmpty != (field.attributedPlaceholder == nil) else { return }
797
- field.attributedPlaceholder = placeholder.isEmpty
803
+ // Its digits slotted like the text's, or the placeholder is narrower than
804
+ // the field measures it, and a typed digit moves the rest along. In the
805
+ // field's own attributes, which carry its alignment.
806
+ var slotAttributes = field.defaultTextAttributes
807
+ slotAttributes[.foregroundColor] = color
808
+ let next = placeholder.isEmpty
798
809
  ? nil
799
- : NSAttributedString(string: placeholder, attributes: [.foregroundColor: color])
810
+ : fonts.metrics.slotted(placeholder, attributes: slotAttributes, lead: false)?.string
811
+ ?? NSAttributedString(string: placeholder, attributes: [.foregroundColor: color])
812
+ if let current = field.attributedPlaceholder, let next, current.isEqual(to: next) { return }
813
+ if field.attributedPlaceholder == nil, next == nil { return }
814
+ field.attributedPlaceholder = next
800
815
  }
801
816
 
802
817
  override func didMoveToSuperview() {
@@ -844,6 +859,8 @@ final class NitroInputView: UIView {
844
859
  private func applyLayoutDirection() {
845
860
  engine.setRightToLeft(isRTL)
846
861
  field.textAlignment = traits.plain ? textAlignment(for: alignment) : .left
862
+ applyDigitSlots()
863
+ syncAccessibilityPlaceholder()
847
864
  if didBuildTextView {
848
865
  textView.textAlignment = textAlignment(for: alignment)
849
866
  applyTextViewTypography()
@@ -1313,10 +1330,49 @@ final class NitroInputView: UIView {
1313
1330
  attributes[.font] = fonts.body
1314
1331
  attributes[.foregroundColor] = traits.plain ? typography.color : UIColor.clear
1315
1332
  field.defaultTextAttributes = attributes
1333
+ fieldSlotted = false
1334
+ applyDigitSlots()
1335
+ syncAccessibilityPlaceholder()
1316
1336
  updateFieldInsets()
1317
1337
  applyTextViewTypography()
1318
1338
  }
1319
1339
 
1340
+ /// Whether the field's text carries `applyDigitSlots`' kerning.
1341
+ private var fieldSlotted = false
1342
+
1343
+ /// Lays the field's own digits out in the slots the overlay and the measure
1344
+ /// give them when the font has no tabular figures (`InputMetrics.slotted`):
1345
+ /// plain mode draws that text, and otherwise the caret and the selection
1346
+ /// follow it. Setting `attributedText` moves the selection, so it is put
1347
+ /// back; a composition in progress is left alone until it is committed.
1348
+ private func applyDigitSlots() {
1349
+ guard field.markedTextRange == nil else { return }
1350
+ let current = field.text ?? ""
1351
+ guard !traits.secureTextEntry, !current.isEmpty,
1352
+ let slotted = fonts.metrics.slotted(current, attributes: field.defaultTextAttributes, lead: false)?.string else {
1353
+ if fieldSlotted {
1354
+ // Back to one kerning for the whole text: re-setting the attributes applies them throughout.
1355
+ fieldSlotted = false
1356
+ let attributes = field.defaultTextAttributes
1357
+ field.defaultTextAttributes = attributes
1358
+ }
1359
+ return
1360
+ }
1361
+ if let existing = field.attributedText, existing.isEqual(to: slotted) { return }
1362
+ let start = field.beginningOfDocument
1363
+ let selection = field.selectedTextRange.map { (field.offset(from: start, to: $0.start), field.offset(from: start, to: $0.end)) }
1364
+ let wasSetting = isSettingText
1365
+ isSettingText = true
1366
+ field.attributedText = slotted
1367
+ if let (from, to) = selection,
1368
+ let fromPosition = field.position(from: field.beginningOfDocument, offset: from),
1369
+ let toPosition = field.position(from: field.beginningOfDocument, offset: to) {
1370
+ field.selectedTextRange = field.textRange(from: fromPosition, to: toPosition)
1371
+ }
1372
+ isSettingText = wasSetting
1373
+ fieldSlotted = true
1374
+ }
1375
+
1320
1376
  /// In reflow mode the overlay draws the prefix and suffix, so the field only
1321
1377
  /// has to reserve the space. In `plain` mode nothing is drawing them, so the
1322
1378
  /// field carries them itself as its left/right accessory views — UIKit insets
@@ -1582,6 +1638,8 @@ final class NitroInputView: UIView {
1582
1638
  var attributes = field.defaultTextAttributes
1583
1639
  attributes[.foregroundColor] = plain ? typography.color : UIColor.clear
1584
1640
  field.defaultTextAttributes = attributes
1641
+ fieldSlotted = false
1642
+ applyDigitSlots()
1585
1643
  updateFieldInsets()
1586
1644
  // Turning plain on tore the overlay down and reset the engine, so on the
1587
1645
  // way back it has nothing to draw until the next edit: hand it the text.
@@ -1678,6 +1736,7 @@ final class NitroInputView: UIView {
1678
1736
  /// `changed` is false only for the first, unchanged application of the
1679
1737
  /// `text` prop (the engine still needs feeding); a keystroke always changes.
1680
1738
  private func textDidChange(caret: Int, reason: ChangeReason, changed: Bool = true) {
1739
+ applyDigitSlots()
1681
1740
  feedEngine(caret: caret)
1682
1741
  if reason != .prop {
1683
1742
  eventCount += 1
@@ -1897,7 +1956,7 @@ final class NitroInputView: UIView {
1897
1956
  return multiplier
1898
1957
  }
1899
1958
 
1900
- static func makeFont(size: CGFloat, weight: CGFloat, family: String?) -> UIFont {
1959
+ static func makeFont(size: CGFloat, weight: CGFloat, family: String?, tabular: Bool = true) -> UIFont {
1901
1960
  let uiWeight = uiWeight(weight)
1902
1961
  let traits: [UIFontDescriptor.TraitKey: Any] = [.weight: uiWeight]
1903
1962
  var base: UIFont
@@ -1910,8 +1969,11 @@ final class NitroInputView: UIView {
1910
1969
  } else {
1911
1970
  base = UIFont.systemFont(ofSize: size, weight: uiWeight)
1912
1971
  }
1913
- // Tabular digits: a column keeps its width while its digit reflows.
1914
- let feature: [UIFontDescriptor.FeatureKey: Int] = [.type: kNumberSpacingType, .selector: kMonospacedNumbersSelector]
1972
+ // Tabular digits, so a column keeps its width while its digit reflows, unless asked for the font's own.
1973
+ let feature: [UIFontDescriptor.FeatureKey: Int] = [
1974
+ .type: kNumberSpacingType,
1975
+ .selector: tabular ? kMonospacedNumbersSelector : kProportionalNumbersSelector,
1976
+ ]
1915
1977
  let descriptor = base.fontDescriptor.addingAttributes([.featureSettings: [feature]])
1916
1978
  return UIFont(descriptor: descriptor, size: size)
1917
1979
  }
@@ -1999,7 +2061,10 @@ final class NitroInputView: UIView {
1999
2061
  if ghostLabel.superview !== field { field.addSubview(ghostLabel) }
2000
2062
  var attributes = field.defaultTextAttributes
2001
2063
  attributes[.foregroundColor] = typography.placeholderColor.resolvedColor(with: traitCollection)
2002
- ghostLabel.attributedText = NSAttributedString(string: tail, attributes: attributes)
2064
+ // A first slotted digit's half-room before it moves the label instead (`InputMetrics.slotted`).
2065
+ let slotted = fonts.metrics.slotted(tail, attributes: attributes, lead: true)
2066
+ ghostLabel.attributedText = slotted?.string ?? NSAttributedString(string: tail, attributes: attributes)
2067
+ let lead = slotted?.lead ?? 0
2003
2068
  let box = field.textRect(forBounds: field.bounds)
2004
2069
  let typed = fonts.width(of: text, role: .body) + fonts.bodySpacing * CGFloat(text.unicodeScalars.count)
2005
2070
  let tailWidth = fonts.width(of: tail, role: .body) + fonts.bodySpacing * CGFloat(tail.unicodeScalars.count)
@@ -2014,7 +2079,8 @@ final class NitroInputView: UIView {
2014
2079
  let end = start + typed
2015
2080
  // Text wider than the box scrolls inside the field; the tail has no place then.
2016
2081
  ghostLabel.isHidden = typed > box.width
2017
- ghostLabel.frame = CGRect(x: end, y: box.minY, width: min(tailWidth + 1, max(0, box.maxX - end)), height: box.height)
2082
+ ghostLabel.frame = CGRect(x: end + lead, y: box.minY, width: min(tailWidth - lead + 1, max(0, box.maxX - end - lead)),
2083
+ height: box.height)
2018
2084
  }
2019
2085
 
2020
2086
  private func contentWidth() -> CGFloat {
@@ -2177,14 +2243,15 @@ final class NitroInputView: UIView {
2177
2243
  glyphLayer.bounds = CGRect(origin: .zero, size: image.size)
2178
2244
  }
2179
2245
  clipLayer.addSublayer(glyphLayer)
2180
- glyphLayers[g.id] = GlyphEntry(layer: glyphLayer, topOffset: fonts.top(for: role, text: text, lineTop: 0), generation: generation)
2246
+ glyphLayers[g.id] = GlyphEntry(layer: glyphLayer, topOffset: fonts.top(for: role, text: text, lineTop: 0),
2247
+ leftInset: fonts.metrics.inset(of: text, role: role), generation: generation)
2181
2248
  index = glyphLayers.index(forKey: g.id)!
2182
2249
  }
2183
2250
  let entry = glyphLayers.values[index]
2184
2251
  let glyphLayer = entry.layer
2185
2252
  let size = glyphLayer.bounds.size
2186
2253
  let top = band + entry.topOffset + CGFloat(g.y) * lineHeight
2187
- let position = CGPoint(x: pad + CGFloat(g.x) + size.width / 2, y: top + size.height / 2)
2254
+ let position = CGPoint(x: pad + CGFloat(g.x) + entry.leftInset + size.width / 2, y: top + size.height / 2)
2188
2255
  if position != entry.position {
2189
2256
  glyphLayer.position = position
2190
2257
  glyphLayers.values[index].position = position
@@ -41,6 +41,8 @@
41
41
  "prefixAlign": true,
42
42
  "suffixAlign": true,
43
43
  "textLetterSpacing": true,
44
+ "tabularNums": true,
45
+ "slotDigits": true,
44
46
  "prefixSpacing": true,
45
47
  "suffixSpacing": true,
46
48
  "prefixOffset": true,
@@ -252,7 +252,7 @@ function measureSizing(sizing) {
252
252
  return null;
253
253
  }
254
254
  }
255
- exports.NitroInput = (0, react_1.forwardRef)(function NitroInput({ value, defaultValue, mode, fractionDigits, maxIntegerDigits, groupingSeparator, decimalSeparator, prefix, suffix, prefixFontSize, suffixFontSize, affixAlign, signPlacement, prefixAlign, suffixAlign, letterSpacing: letterSpacingProp, prefixSpacing, suffixSpacing, prefixOffset, suffixOffset, format, placeholder, placeholderTextColor, duration, easing, bounce, effect, fontSize: fontSizeProp, lineHeight: lineHeightProp, fontWeight: fontWeightProp, fontFamily: fontFamilyProp, color: colorProp, textAlign: textAlignProp, cursorColor, selectionColor, caretHidden, adjustsFontSizeToFit, minimumFontScale, allowFontScaling, maxFontSizeMultiplier, variant, label, labelBehavior, labelColor, labelFocusedColor, labelFontSize, strokeColor, focusedStrokeColor, strokeWidth, cornerRadius, fillColor, keyboardType, inputMode, enterKeyHint, mask, maskNotations, maskAutocomplete, maskAutoSkip, maskAffinityFormats, maskAffinityStrategy, maskTextCase, maskCharacterMap, maskSlotPlaceholder, keepPlaceholder, returnKeyType, autoCapitalize, autoCorrect, editable, multiline, numberOfLines, rows, textAlignVertical: textAlignVerticalProp, scrollEnabled, autoFocus, transition, autoWidth: autoWidthProp, submitBehavior, blurOnSubmit, secureTextEntry, keyboardAppearance, textContentType, autoComplete, enablesReturnKeyAutomatically, showSoftInputOnFocus, selectTextOnFocus, clearTextOnFocus, keyboardHandoffMs, returnKeyBar, contextMenuHidden, spellCheck, readOnly, selection, onEndEditing, onSelectionChange, onKeyPress, maxLength, transform, onChangeText, onChange, onChangeValue, onChangeMask, onFocus, onBlur, focusedValue, onSubmitEditing, onNativeRef, style, ...viewProps }, ref) {
255
+ exports.NitroInput = (0, react_1.forwardRef)(function NitroInput({ value, defaultValue, mode, fractionDigits, maxIntegerDigits, groupingSeparator, decimalSeparator, prefix, suffix, prefixFontSize, suffixFontSize, affixAlign, signPlacement, prefixAlign, suffixAlign, letterSpacing: letterSpacingProp, tabularNums, prefixSpacing, suffixSpacing, prefixOffset, suffixOffset, format, placeholder, placeholderTextColor, duration, easing, bounce, effect, fontSize: fontSizeProp, lineHeight: lineHeightProp, fontWeight: fontWeightProp, fontFamily: fontFamilyProp, color: colorProp, textAlign: textAlignProp, cursorColor, selectionColor, caretHidden, adjustsFontSizeToFit, minimumFontScale, allowFontScaling, maxFontSizeMultiplier, variant, label, labelBehavior, labelColor, labelFocusedColor, labelFontSize, strokeColor, focusedStrokeColor, strokeWidth, cornerRadius, fillColor, keyboardType, inputMode, enterKeyHint, mask, maskNotations, maskAutocomplete, maskAutoSkip, maskAffinityFormats, maskAffinityStrategy, maskTextCase, maskCharacterMap, maskSlotPlaceholder, keepPlaceholder, returnKeyType, autoCapitalize, autoCorrect, editable, multiline, numberOfLines, rows, textAlignVertical: textAlignVerticalProp, scrollEnabled, autoFocus, transition, autoWidth: autoWidthProp, submitBehavior, blurOnSubmit, secureTextEntry, keyboardAppearance, textContentType, autoComplete, enablesReturnKeyAutomatically, showSoftInputOnFocus, selectTextOnFocus, clearTextOnFocus, keyboardHandoffMs, returnKeyBar, contextMenuHidden, spellCheck, readOnly, selection, onEndEditing, onSelectionChange, onKeyPress, maxLength, transform, onChangeText, onChange, onChangeValue, onChangeMask, onFocus, onBlur, focusedValue, onSubmitEditing, onNativeRef, style, ...viewProps }, ref) {
256
256
  const nativeRef = (0, react_1.useRef)(null);
257
257
  // `keyboardHandoffMs`: hand the keyboard off while this field still has it.
258
258
  // A layout-effect cleanup runs in React's commit, so the native call is
@@ -749,6 +749,8 @@ exports.NitroInput = (0, react_1.forwardRef)(function NitroInput({ value, defaul
749
749
  textWeight: numericWeight,
750
750
  textFamily: fontFamily ?? '',
751
751
  textLetterSpacing: letterSpacing ?? 0,
752
+ tabularNums: tabularNums ?? !flat?.fontVariant?.includes('proportional-nums'),
753
+ slotDigits: tabularNums === true,
752
754
  prefixSpacing: prefixSpacing ?? Infinity,
753
755
  suffixSpacing: suffixSpacing ?? Infinity,
754
756
  allowFontScaling: allowFontScaling ?? false,
@@ -50,6 +50,73 @@ const formatProps_1 = require("./formatProps");
50
50
  exports.NativeNitroNumberView = (0, react_native_nitro_modules_1.getHostComponent)('NitroNumberView', () => NitroNumberViewConfig_json_1.default);
51
51
  const EMPTY = [];
52
52
  const EMPTY_STRINGS = [];
53
+ /**
54
+ * A weak reference where the engine has them (Hermes, JSC, V8), else a strong
55
+ * one. Two functions on purpose: an engine keeps one scope per function for
56
+ * everything its closures capture, so a `() => target` fallback written beside
57
+ * the weak closure would put `target` in the weak closure's scope too.
58
+ */
59
+ function weakly(target) {
60
+ return typeof WeakRef === 'function' ? weakDeref(new WeakRef(target)) : strongDeref(target);
61
+ }
62
+ function weakDeref(ref) {
63
+ return () => ref.deref();
64
+ }
65
+ function strongDeref(target) {
66
+ return () => target;
67
+ }
68
+ /**
69
+ * A Nitro callback that calls `handler(self, ...args)` for as long as the
70
+ * component behind `self` is alive, holding `self` only weakly.
71
+ *
72
+ * Why. Nitro keeps every callback prop of a view as a JS function held from
73
+ * C++ (in the Fabric props of its shadow node), which Hermes treats as a GC
74
+ * root. A closure written inside the component shares the render's scope,
75
+ * so it reaches the fiber (through `setSize`) and the hybrid view's handle
76
+ * (through `nativeRef`), and the fiber holds the shadow node that holds the
77
+ * props that hold the closure: a loop through native code that Hermes can
78
+ * never collect. Every unmounted NitroNumber stayed, its fiber subtree, its
79
+ * hybrid view and Nitro's C++ part included: over 4,000 after a minute of
80
+ * a scrolling list, and the app's memory climbed with them. Built here, in
81
+ * module scope, the closure holds only the weak reference and `handler`
82
+ * (itself module-level); the fiber is what keeps `self` alive.
83
+ */
84
+ function relay(self, handler) {
85
+ return relayTo(weakly(self), handler);
86
+ }
87
+ /**
88
+ * The closure itself, made where `self` is not in scope at all: Hermes (in
89
+ * debuggable builds, at least) keeps every variable of a function that makes
90
+ * a closure in that closure's scope, used or not, and a `self` there would
91
+ * hold the component strongly again.
92
+ */
93
+ function relayTo(live, handler) {
94
+ return (0, react_native_nitro_modules_1.callback)((...args) => {
95
+ const target = live();
96
+ if (target !== undefined)
97
+ handler(target, ...args);
98
+ });
99
+ }
100
+ function attachNative(self, instance) {
101
+ self.nativeRef.current = instance;
102
+ self.latestOnNativeRef.current?.(instance);
103
+ }
104
+ function applySize(self, width, height) {
105
+ self.setSize((previous) => previous !== null && previous.width === width && previous.height === height ? previous : { width, height });
106
+ }
107
+ function fireRevealEnd(self) {
108
+ self.latestOnRevealEnd.current?.();
109
+ }
110
+ function fireRevealMilestone(self, index, milestone) {
111
+ self.latestOnRevealMilestone.current?.(index, milestone);
112
+ }
113
+ function fireAnimationStart(self) {
114
+ self.latestOnAnimationStart.current?.();
115
+ }
116
+ /** The figure a compact format rolls is not the value (1.2 for 1,234): report the value. */
117
+ function fireAnimationEnd(self, shown) {
118
+ self.latestOnAnimationEnd.current?.(self.compactRef.current ? (0, formatProps_1.toNumber)(self.latestValue.current) : shown);
119
+ }
53
120
  /** Each transition's own timing, used when the props leave it unsaid. */
54
121
  const TRANSITION_DEFAULTS = {
55
122
  roll: { duration: 500, easing: 'easeInOut', stagger: 0 },
@@ -68,6 +135,8 @@ const TRANSITION_DEFAULTS = {
68
135
  */
69
136
  exports.NitroNumber = (0, react_1.forwardRef)(function NitroNumber({ value, minorDigits, fractionDigits, minimumIntegerDigits, groupingSeparator, decimalSeparator, prefix, suffix, transition, flashUpColor, flashDownColor, flashDuration, popOnChange, duration, easing, bounce, stagger, direction, reveal, revealStyle, revealDuration, revealBounce, revealGrow, revealStagger, revealMilestones, revealMilestoneHold, onRevealEnd, onRevealMilestone, loading, shimmerColor, shimmerDuration, shimmerAngle, shimmerWidth, shimmerBaseColor, shimmerDirection, shimmerDelay, fontSize, prefixFontSize, suffixFontSize, affixAlign, prefixAlign, suffixAlign, letterSpacing, prefixSpacing, suffixSpacing, prefixOffset, suffixOffset, tabularNums, format, adjustsFontSizeToFit, minimumFontScale, allowFontScaling, maxFontSizeMultiplier, fontWeight, fontFamily, color, textAlign, signDisplay, plusSign, minusSign, prefixColor, suffixColor, fractionColor, fractionFontSize, fractionAlign, digitGlyphs, groupingSizes, digits, continuous, animated, respectReduceMotion, onAnimationStart, onAnimationEnd, onNativeRef, style, ...viewProps }, ref) {
70
137
  const nativeRef = (0, react_1.useRef)(null);
138
+ // Whether a compact format is rolling (its figure is not the value); set below.
139
+ const compactRef = (0, react_1.useRef)(false);
71
140
  const latestOnNativeRef = (0, react_1.useRef)(onNativeRef);
72
141
  latestOnNativeRef.current = onNativeRef;
73
142
  const latestOnRevealEnd = (0, react_1.useRef)(onRevealEnd);
@@ -83,34 +152,31 @@ exports.NitroNumber = (0, react_1.forwardRef)(function NitroNumber({ value, mino
83
152
  const latestOnAnimationEnd = (0, react_1.useRef)(onAnimationEnd);
84
153
  latestOnAnimationEnd.current = onAnimationEnd;
85
154
  const [size, setSize] = (0, react_1.useState)(null);
86
- // Nitro callbacks must be wrapped with `callback()` and the wrapper object
87
- // has to be referentially stable, otherwise every render re-sets the prop.
88
- const hybridRef = (0, react_1.useMemo)(() => (0, react_native_nitro_modules_1.callback)((instance) => {
89
- nativeRef.current = instance;
90
- latestOnNativeRef.current?.(instance);
91
- }), []);
92
- const onSizeChange = (0, react_1.useMemo)(() => (0, react_native_nitro_modules_1.callback)((width, height) => {
93
- setSize((previous) => previous !== null &&
94
- previous.width === width &&
95
- previous.height === height
96
- ? previous
97
- : { width, height });
98
- }), []);
99
- // Stable like the others; the latest handler is read through a ref so a
100
- // caller passing an inline arrow doesn't re-set the native prop each render.
101
- const onRevealEndCallback = (0, react_1.useMemo)(() => (0, react_native_nitro_modules_1.callback)(() => {
102
- latestOnRevealEnd.current?.();
103
- }), []);
104
- const onRevealMilestoneCallback = (0, react_1.useMemo)(() => (0, react_native_nitro_modules_1.callback)((index, milestone) => {
105
- latestOnRevealMilestone.current?.(index, milestone);
106
- }), []);
107
- const onAnimationStartCallback = (0, react_1.useMemo)(() => (0, react_native_nitro_modules_1.callback)(() => {
108
- latestOnAnimationStart.current?.();
109
- }), []);
110
- // The figure a compact format rolls is not the value (1.2 for 1,234): report the value.
111
- const onAnimationEndCallback = (0, react_1.useMemo)(() => (0, react_native_nitro_modules_1.callback)((shown) => {
112
- latestOnAnimationEnd.current?.(compactRef.current ? (0, formatProps_1.toNumber)(latestValue.current) : shown);
113
- }), []);
155
+ // The native callbacks: wrapped with `callback()` and referentially stable
156
+ // (a new wrapper re-sets the prop every render), and built in module scope
157
+ // around a weak reference to this component's state (see `relay`).
158
+ const self = (0, react_1.useMemo)(() => ({
159
+ nativeRef,
160
+ latestOnNativeRef,
161
+ setSize,
162
+ latestOnRevealEnd,
163
+ latestOnRevealMilestone,
164
+ latestOnAnimationStart,
165
+ latestOnAnimationEnd,
166
+ compactRef,
167
+ latestValue,
168
+ }),
169
+ // Every member is a ref or a state setter, stable for the component's life.
170
+ // eslint-disable-next-line react-hooks/exhaustive-deps
171
+ []);
172
+ const hybridRef = (0, react_1.useMemo)(() => relay(self, attachNative), [self]);
173
+ const onSizeChange = (0, react_1.useMemo)(() => relay(self, applySize), [self]);
174
+ // The latest handlers are read through refs, so a caller passing an inline
175
+ // arrow doesn't re-set the native prop each render.
176
+ const onRevealEndCallback = (0, react_1.useMemo)(() => relay(self, fireRevealEnd), [self]);
177
+ const onRevealMilestoneCallback = (0, react_1.useMemo)(() => relay(self, fireRevealMilestone), [self]);
178
+ const onAnimationStartCallback = (0, react_1.useMemo)(() => relay(self, fireAnimationStart), [self]);
179
+ const onAnimationEndCallback = (0, react_1.useMemo)(() => relay(self, fireAnimationEnd), [self]);
114
180
  // A new array literal each render must not re-set the native prop. Always an
115
181
  // array (empty = no tiers): removing the prop would reach native as `null`,
116
182
  // which Nitro's array parser rejects ("Value is null, expected an Object").
@@ -150,7 +216,6 @@ exports.NitroNumber = (0, react_1.forwardRef)(function NitroNumber({ value, mino
150
216
  // rolls the figure 1.2.
151
217
  const figure = (0, react_1.useMemo)(() => (format ? (0, formatProps_1.figureOf)(format, input) : undefined), [format, input]);
152
218
  const compact = derived?.compact ? figure : undefined;
153
- const compactRef = (0, react_1.useRef)(false);
154
219
  compactRef.current = compact !== undefined;
155
220
  // Which way the value moved, for a compact figure that fell while the value grew (999 → 1K).
156
221
  const numericValue = (0, formatProps_1.toNumber)(input);
@@ -41,6 +41,8 @@
41
41
  "prefixAlign": true,
42
42
  "suffixAlign": true,
43
43
  "textLetterSpacing": true,
44
+ "tabularNums": true,
45
+ "slotDigits": true,
44
46
  "prefixSpacing": true,
45
47
  "suffixSpacing": true,
46
48
  "prefixOffset": true,
@@ -213,7 +213,7 @@ function measureSizing(sizing) {
213
213
  return null;
214
214
  }
215
215
  }
216
- export const NitroInput = forwardRef(function NitroInput({ value, defaultValue, mode, fractionDigits, maxIntegerDigits, groupingSeparator, decimalSeparator, prefix, suffix, prefixFontSize, suffixFontSize, affixAlign, signPlacement, prefixAlign, suffixAlign, letterSpacing: letterSpacingProp, prefixSpacing, suffixSpacing, prefixOffset, suffixOffset, format, placeholder, placeholderTextColor, duration, easing, bounce, effect, fontSize: fontSizeProp, lineHeight: lineHeightProp, fontWeight: fontWeightProp, fontFamily: fontFamilyProp, color: colorProp, textAlign: textAlignProp, cursorColor, selectionColor, caretHidden, adjustsFontSizeToFit, minimumFontScale, allowFontScaling, maxFontSizeMultiplier, variant, label, labelBehavior, labelColor, labelFocusedColor, labelFontSize, strokeColor, focusedStrokeColor, strokeWidth, cornerRadius, fillColor, keyboardType, inputMode, enterKeyHint, mask, maskNotations, maskAutocomplete, maskAutoSkip, maskAffinityFormats, maskAffinityStrategy, maskTextCase, maskCharacterMap, maskSlotPlaceholder, keepPlaceholder, returnKeyType, autoCapitalize, autoCorrect, editable, multiline, numberOfLines, rows, textAlignVertical: textAlignVerticalProp, scrollEnabled, autoFocus, transition, autoWidth: autoWidthProp, submitBehavior, blurOnSubmit, secureTextEntry, keyboardAppearance, textContentType, autoComplete, enablesReturnKeyAutomatically, showSoftInputOnFocus, selectTextOnFocus, clearTextOnFocus, keyboardHandoffMs, returnKeyBar, contextMenuHidden, spellCheck, readOnly, selection, onEndEditing, onSelectionChange, onKeyPress, maxLength, transform, onChangeText, onChange, onChangeValue, onChangeMask, onFocus, onBlur, focusedValue, onSubmitEditing, onNativeRef, style, ...viewProps }, ref) {
216
+ export const NitroInput = forwardRef(function NitroInput({ value, defaultValue, mode, fractionDigits, maxIntegerDigits, groupingSeparator, decimalSeparator, prefix, suffix, prefixFontSize, suffixFontSize, affixAlign, signPlacement, prefixAlign, suffixAlign, letterSpacing: letterSpacingProp, tabularNums, prefixSpacing, suffixSpacing, prefixOffset, suffixOffset, format, placeholder, placeholderTextColor, duration, easing, bounce, effect, fontSize: fontSizeProp, lineHeight: lineHeightProp, fontWeight: fontWeightProp, fontFamily: fontFamilyProp, color: colorProp, textAlign: textAlignProp, cursorColor, selectionColor, caretHidden, adjustsFontSizeToFit, minimumFontScale, allowFontScaling, maxFontSizeMultiplier, variant, label, labelBehavior, labelColor, labelFocusedColor, labelFontSize, strokeColor, focusedStrokeColor, strokeWidth, cornerRadius, fillColor, keyboardType, inputMode, enterKeyHint, mask, maskNotations, maskAutocomplete, maskAutoSkip, maskAffinityFormats, maskAffinityStrategy, maskTextCase, maskCharacterMap, maskSlotPlaceholder, keepPlaceholder, returnKeyType, autoCapitalize, autoCorrect, editable, multiline, numberOfLines, rows, textAlignVertical: textAlignVerticalProp, scrollEnabled, autoFocus, transition, autoWidth: autoWidthProp, submitBehavior, blurOnSubmit, secureTextEntry, keyboardAppearance, textContentType, autoComplete, enablesReturnKeyAutomatically, showSoftInputOnFocus, selectTextOnFocus, clearTextOnFocus, keyboardHandoffMs, returnKeyBar, contextMenuHidden, spellCheck, readOnly, selection, onEndEditing, onSelectionChange, onKeyPress, maxLength, transform, onChangeText, onChange, onChangeValue, onChangeMask, onFocus, onBlur, focusedValue, onSubmitEditing, onNativeRef, style, ...viewProps }, ref) {
217
217
  const nativeRef = useRef(null);
218
218
  // `keyboardHandoffMs`: hand the keyboard off while this field still has it.
219
219
  // A layout-effect cleanup runs in React's commit, so the native call is
@@ -710,6 +710,8 @@ export const NitroInput = forwardRef(function NitroInput({ value, defaultValue,
710
710
  textWeight: numericWeight,
711
711
  textFamily: fontFamily ?? '',
712
712
  textLetterSpacing: letterSpacing ?? 0,
713
+ tabularNums: tabularNums ?? !flat?.fontVariant?.includes('proportional-nums'),
714
+ slotDigits: tabularNums === true,
713
715
  prefixSpacing: prefixSpacing ?? Infinity,
714
716
  suffixSpacing: suffixSpacing ?? Infinity,
715
717
  allowFontScaling: allowFontScaling ?? false,