@onekeyfe/react-native-native-list 6.7.0-57 → 6.7.0-59

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.
@@ -78,9 +78,9 @@ internal class NativeListActivityDetailsView(private val reactContext: ThemedRea
78
78
  return parseNativeListColor(theme?.optString(key, fallback) ?: fallback)
79
79
  }
80
80
  private fun text(label: NativeListTextView, value: String, style: JSONObject?, size: Float,
81
- ink: Int, line: Int, weight: String = "regular", lines: Int = 1) {
82
- NativeListResolvedText.resolve(context, fonts, value, style, size, weight, ink, line, lines, sourceScale).bind(label)
83
- }
81
+ ink: Int, line: Int, weight: String = "regular", lines: Int = 1): NativeListResolvedText =
82
+ NativeListResolvedText.resolve(context, fonts, value, style, size, weight, ink, line, lines, sourceScale)
83
+ .also { it.bind(label) }
84
84
  fun bind(item: NativeListItem, theme: JSONObject?, sourceScale: Boolean) {
85
85
  this.sourceScale = sourceScale
86
86
  val data = item.json
@@ -98,12 +98,20 @@ internal class NativeListActivityDetailsView(private val reactContext: ThemedRea
98
98
  setClipping(nativeListActivityHostClips(leadingOverhangs))
99
99
  amounts.layoutParams = if (table) LayoutParams(0, -2, 1f).apply { marginStart = gap } else LayoutParams(-2, -2).apply { marginStart = gap }
100
100
  text(title, data.optString("title"), style.optJSONObject("title"), 16f, color("primary", theme), 24, "medium")
101
- text(description, data.optString("description"), style.optJSONObject("description"), 14f, color("secondary", theme), 20, lines = 2)
101
+ val descriptionText = text(description, data.optString("description"), style.optJSONObject("description"), 14f, color("secondary", theme), 20, lines = 2)
102
102
  text(status, data.optString("status"), style.optJSONObject("status"), 12f, color("secondary", theme), 16)
103
103
  description.setOnClickListener(null)
104
104
  val descriptionKey = data.optString("descriptionActionKey")
105
- description.isClickable = descriptionKey.isNotEmpty()
106
- if (descriptionKey.isNotEmpty()) description.setOnClickListener { onAction?.invoke(descriptionKey, description, "description", 0) }
105
+ // The view spans the identity column, so with an action only its text from
106
+ // the caller's `descriptionActionStart` on takes touches. The start is
107
+ // never read out of the string, and one at the end leaves no action.
108
+ val actionStart =
109
+ if (descriptionKey.isEmpty()) null
110
+ else descriptionText.displayOffset(data.optLong("descriptionActionStart"), data.optString("description"))
111
+ val hasActionText = actionStart != null && actionStart < descriptionText.text.length
112
+ description.touchableTextStart = actionStart
113
+ description.isClickable = hasActionText
114
+ if (hasActionText) description.setOnClickListener { onAction?.invoke(descriptionKey, description, "description", 0) }
107
115
  for (view in listOf(description, status)) (view.layoutParams as LayoutParams).topMargin = if (style.has("lineGap")) px(style.optDouble("lineGap")) else 0
108
116
  badges.forEach(titleLine::removeView); badges.clear()
109
117
  val badgeData = data.optJSONArray("badges")
@@ -172,6 +180,7 @@ internal class NativeListActivityDetailsView(private val reactContext: ThemedRea
172
180
  }
173
181
  fun recycle() {
174
182
  visual.recycle(); visual.visibility = VISIBLE; amountViews.forEach { it.recycle() }; description.setOnClickListener(null); actions.removeAllViews()
183
+ description.touchableTextStart = null
175
184
  leadingOverhangs = false
176
185
  setClipping(true)
177
186
  }
@@ -62,6 +62,66 @@ internal fun nativeListLeadingVisualOverhangsFrame(
62
62
  */
63
63
  internal fun nativeListActivityHostClips(leadingOverhangs: Boolean): Boolean = !leadingOverhangs
64
64
 
65
+ /** A one-line text view shows each line break of its text as one space. */
66
+ internal fun nativeListFoldLineBreaks(text: String): String = text.replace(Regex("\\r\\n|[\\r\\n]"), " ")
67
+
68
+ /**
69
+ * Offset into the displayed text for [sourceOffset], a UTF-16 offset into the
70
+ * caller's [source], kept within the text. Folding line breaks
71
+ * ([nativeListFoldLineBreaks]) moves every offset after a CRLF. The offset is a
72
+ * Long because JSON carries any safe integer; narrowing it first would wrap a
73
+ * value past Int range instead of clamping it to the end.
74
+ */
75
+ internal fun nativeListDisplayOffset(source: String, sourceOffset: Long, foldsLineBreaks: Boolean): Int {
76
+ val clamped = sourceOffset.coerceIn(0L, source.length.toLong()).toInt()
77
+ return if (foldsLineBreaks) nativeListFoldLineBreaks(source.substring(0, clamped)).length else clamped
78
+ }
79
+
80
+ /** A horizontal run of laid-out text on one line, in view coordinates. */
81
+ internal data class NativeListTextRun(val left: Float, val right: Float)
82
+
83
+ /**
84
+ * One laid-out line of a text view, in view coordinates: its vertical extent,
85
+ * the runs of [touchable] text and the runs of [plain] text before it. A line
86
+ * holds one run of each, or several where mixed-direction text puts plain text
87
+ * between touchable text.
88
+ */
89
+ internal data class NativeListTextLine(
90
+ val top: Float,
91
+ val bottom: Float,
92
+ val touchable: List<NativeListTextRun>,
93
+ val plain: List<NativeListTextRun> = emptyList(),
94
+ )
95
+
96
+ internal data class NativeListTouchRegion(val left: Float, val top: Float, val right: Float, val bottom: Float) {
97
+ fun contains(x: Float, y: Float): Boolean = x in left..right && y in top..bottom
98
+ }
99
+
100
+ /** Runs are read back from pixel regions, so neighbours can be a pixel apart. */
101
+ private const val TEXT_RUN_EDGE = 1f
102
+
103
+ /**
104
+ * Parts of a stretched text view that take touches: every run of touchable
105
+ * text, widened by [slop] into blank space only. The widening stops at plain
106
+ * text on the same line, so text before the touchable text never takes the
107
+ * touch, however narrow it is. Touches outside the regions fall through to the
108
+ * row behind the view (OK-67219).
109
+ */
110
+ internal fun nativeListTouchableTextRegions(
111
+ lines: List<NativeListTextLine>,
112
+ slop: Float,
113
+ ): List<NativeListTouchRegion> = lines.flatMap { line ->
114
+ line.touchable.map { run ->
115
+ var left = run.left - slop
116
+ var right = run.right + slop
117
+ for (other in line.plain) {
118
+ if (other.right <= run.left + TEXT_RUN_EDGE) left = maxOf(left, other.right)
119
+ if (other.left >= run.right - TEXT_RUN_EDGE) right = minOf(right, other.left)
120
+ }
121
+ NativeListTouchRegion(left, line.top, right, line.bottom)
122
+ }
123
+ }
124
+
65
125
  internal data class NativeListSlotFrame(val x: Int, val y: Int, val width: Int, val height: Int)
66
126
 
67
127
  /** Side of one member of an Activity token pair inside a [frame]-unit box (24 in 40). */
@@ -43,6 +43,10 @@ internal data class NativeListResolvedText(
43
43
  val gravity: Int,
44
44
  val offset: Float,
45
45
  ) {
46
+ /** Offset into [text] for a UTF-16 offset into the [source] it was resolved from. */
47
+ fun displayOffset(sourceOffset: Long, source: String): Int =
48
+ nativeListDisplayOffset(source, sourceOffset, foldsLineBreaks = lines == 1 && explicitTruncation)
49
+
46
50
  fun bind(view: NativeListTextView) {
47
51
  view.includeFontPadding = false
48
52
  view.fontFeatureSettings = "tnum"
@@ -119,7 +123,7 @@ internal data class NativeListResolvedText(
119
123
  else -> Gravity.TOP
120
124
  }
121
125
  return NativeListResolvedText(
122
- if (maxLines == 1 && truncation) text.replace(Regex("\\r\\n|[\\r\\n]"), " ") else text,
126
+ if (maxLines == 1 && truncation) nativeListFoldLineBreaks(text) else text,
123
127
  fontSize,
124
128
  face,
125
129
  style
@@ -3,9 +3,16 @@ package com.margelo.nitro.nativelist
3
3
  import android.graphics.Canvas
4
4
  import android.graphics.DashPathEffect
5
5
  import android.graphics.Paint
6
+ import android.graphics.Path
7
+ import android.graphics.Rect
6
8
  import android.graphics.RectF
9
+ import android.graphics.Region
10
+ import android.graphics.RegionIterator
11
+ import android.text.Layout
7
12
  import android.view.MotionEvent
8
13
  import android.widget.TextView
14
+ import kotlin.math.ceil
15
+ import kotlin.math.floor
9
16
 
10
17
  internal open class NativeListTextView(context: android.content.Context) : TextView(context) {
11
18
  var helpBindingGeneration = 0
@@ -33,9 +40,73 @@ internal open class NativeListTextView(context: android.content.Context) : TextV
33
40
  )
34
41
  }
35
42
 
43
+ /**
44
+ * Character offset the touchable text starts at. `null` keeps the view's own
45
+ * hit testing, its whole bounds. With an offset only the drawn text from
46
+ * there on takes touches, plus a small horizontal slop, so text before the
47
+ * offset and the unused width of a stretched view fall through to the row
48
+ * behind it: `0` covers all of the text, the text length leaves nothing to
49
+ * touch.
50
+ */
51
+ var touchableTextStart: Int? = null
52
+
53
+ val touchableTextRegions: List<NativeListTouchRegion>
54
+ get() {
55
+ val textStart = touchableTextStart ?: return emptyList()
56
+ val textLayout = layout ?: return emptyList()
57
+ // Lines past the line cap are laid out but never drawn.
58
+ val count = minOf(textLayout.lineCount, maxLines.takeIf { it > 0 } ?: Int.MAX_VALUE)
59
+ if (count == 0) return emptyList()
60
+ val originX = totalPaddingLeft.toFloat()
61
+ val originY = totalPaddingTop + opticalOffsetY
62
+ val lines = (0 until count).map { line ->
63
+ val lineStart = textLayout.getLineStart(line)
64
+ val lineEnd = textLayout.getLineEnd(line)
65
+ // An ellipsis hides the rest of its line. Once it hides the touchable
66
+ // text as well it also stands for plain text, so nothing is left to touch.
67
+ val visibleEnd =
68
+ if (textLayout.getEllipsisCount(line) > 0) lineStart + textLayout.getEllipsisStart(line) else lineEnd
69
+ val touchableStart = maxOf(textStart, lineStart)
70
+ NativeListTextLine(
71
+ // The outer lines also take the view's own vertical padding.
72
+ top = if (line == 0) 0f else originY + textLayout.getLineTop(line),
73
+ bottom = if (line == count - 1) height.toFloat() else originY + textLayout.getLineBottom(line),
74
+ touchable =
75
+ if (touchableStart < visibleEnd) textRuns(textLayout, line, touchableStart, lineEnd, originX)
76
+ else emptyList(),
77
+ plain = textRuns(textLayout, line, lineStart, minOf(textStart, lineEnd), originX),
78
+ )
79
+ }
80
+ return nativeListTouchableTextRegions(lines, TOUCH_SLOP_DP * resources.displayMetrics.density)
81
+ }
82
+
83
+ /**
84
+ * Horizontal extents the layout gives characters `[from, to)` of [line]: the
85
+ * layout's own selection, so mixed-direction text yields one run per
86
+ * direction run instead of one box around all of them.
87
+ */
88
+ private fun textRuns(textLayout: Layout, line: Int, from: Int, to: Int, originX: Float): List<NativeListTextRun> {
89
+ if (from >= to) return emptyList()
90
+ val selection = Path()
91
+ textLayout.getSelectionPath(from, to, selection)
92
+ // A selection that reaches the line end also covers the blank up to the
93
+ // layout edge and starts the next line; only this line's text counts.
94
+ val lineBounds = Region(
95
+ floor(textLayout.getLineLeft(line)).toInt(), textLayout.getLineTop(line),
96
+ ceil(textLayout.getLineRight(line)).toInt(), textLayout.getLineBottom(line),
97
+ )
98
+ val runs = mutableListOf<NativeListTextRun>()
99
+ val iterator = RegionIterator(Region().apply { setPath(selection, lineBounds) })
100
+ val run = Rect()
101
+ while (iterator.next(run)) runs += NativeListTextRun(originX + run.left, originX + run.right)
102
+ return runs
103
+ }
104
+
36
105
  override fun onTouchEvent(event: MotionEvent): Boolean {
37
106
  if (primaryHelpOnly && event.actionMasked == MotionEvent.ACTION_DOWN &&
38
107
  helpAnchorBounds?.contains(event.x, event.y) != true) return false
108
+ if (touchableTextStart != null && event.actionMasked == MotionEvent.ACTION_DOWN &&
109
+ touchableTextRegions.none { it.contains(event.x, event.y) }) return false
39
110
  if (guardsHelpTouches) {
40
111
  if (event.actionMasked == MotionEvent.ACTION_DOWN) helpDownGeneration = helpBindingGeneration
41
112
  if (event.actionMasked == MotionEvent.ACTION_UP && helpDownGeneration != helpBindingGeneration) {
@@ -76,4 +147,8 @@ internal open class NativeListTextView(context: android.content.Context) : TextV
76
147
  drawHelpUnderline(canvas)
77
148
  canvas.restoreToCount(checkpoint)
78
149
  }
150
+
151
+ private companion object {
152
+ const val TOUCH_SLOP_DP = 8f
153
+ }
79
154
  }
@@ -0,0 +1,153 @@
1
+ package com.margelo.nitro.nativelist
2
+
3
+ import org.junit.Assert.assertEquals
4
+ import org.junit.Assert.assertFalse
5
+ import org.junit.Assert.assertTrue
6
+ import org.junit.Test
7
+
8
+ class NativeListDescriptionTouchPolicyTest {
9
+ private fun hit(regions: List<NativeListTouchRegion>, x: Float, y: Float) = regions.any { it.contains(x, y) }
10
+
11
+ private fun run(left: Float, right: Float) = NativeListTextRun(left, right)
12
+
13
+ private fun regions(vararg lines: NativeListTextLine) = nativeListTouchableTextRegions(lines.toList(), slop = 8f)
14
+
15
+ // The description view spans the identity column, so a tap anywhere on its
16
+ // line used to open the description action. Only the text opens it now; the
17
+ // blank rest of the line belongs to the row press (OK-67219).
18
+ @Test
19
+ fun onlyTheDrawnTextTakesTouches() {
20
+ val text = regions(NativeListTextLine(top = 0f, bottom = 20f, touchable = listOf(run(0f, 60f))))
21
+
22
+ assertTrue(hit(text, 30f, 10f))
23
+ // The slop reaches into the blank on both sides of the text.
24
+ assertTrue(hit(text, 66f, 10f))
25
+ assertTrue(hit(text, -6f, 10f))
26
+ assertFalse(hit(text, 120f, 10f))
27
+ }
28
+
29
+ // The caller states where the action text starts; the text before it, a
30
+ // time for one, is not part of the action.
31
+ @Test
32
+ fun textBeforeTheStartIsNotPartOfTheAction() {
33
+ val ltr = regions(
34
+ NativeListTextLine(top = 0f, bottom = 20f, touchable = listOf(run(50f, 160f)), plain = listOf(run(0f, 50f))),
35
+ )
36
+ assertFalse(hit(ltr, 20f, 10f))
37
+ assertTrue(hit(ltr, 100f, 10f))
38
+
39
+ // Right to left the plain text sits on the right of the touchable text.
40
+ val rtl = regions(
41
+ NativeListTextLine(top = 0f, bottom = 20f, touchable = listOf(run(40f, 150f)), plain = listOf(run(150f, 200f))),
42
+ )
43
+ assertTrue(hit(rtl, 100f, 10f))
44
+ assertFalse(hit(rtl, 180f, 10f))
45
+ }
46
+
47
+ // The slop is for blank space. It must not reach into plain text beside the
48
+ // touchable text, or a prefix narrower than the slop, like the "i" of
49
+ // "iRouter", would open the action it is not part of.
50
+ @Test
51
+ fun theSlopStopsAtPlainTextBesideTheTouchableText() {
52
+ val short = regions(
53
+ NativeListTextLine(top = 0f, bottom = 20f, touchable = listOf(run(3f, 46f)), plain = listOf(run(0f, 3f))),
54
+ )
55
+ assertFalse(hit(short, 1.5f, 10f))
56
+ assertFalse(hit(short, -4f, 10f))
57
+ assertTrue(hit(short, 4f, 10f))
58
+ assertTrue(hit(short, 52f, 10f))
59
+ assertEquals(3f, short.single().left)
60
+ assertEquals(54f, short.single().right)
61
+
62
+ // Neighbouring runs read back from pixel regions may be a pixel apart.
63
+ val apart = regions(
64
+ NativeListTextLine(top = 0f, bottom = 20f, touchable = listOf(run(4f, 46f)), plain = listOf(run(0f, 3f))),
65
+ )
66
+ assertEquals(3f, apart.single().left)
67
+ }
68
+
69
+ // Mixed-direction text can split one logical suffix into several visual
70
+ // runs with plain text between them: "ABC אבג XYZ" from the last Hebrew
71
+ // letter on draws that letter left of the two plain ones. Each run is its
72
+ // own region, and the plain text between them takes no touches.
73
+ @Test
74
+ fun aSuffixSplitByMixedDirectionTextIsSeveralRuns() {
75
+ val mixed = regions(
76
+ NativeListTextLine(
77
+ top = 0f, bottom = 20f,
78
+ touchable = listOf(run(32f, 38f), run(55f, 86f)),
79
+ plain = listOf(run(0f, 32f), run(38f, 55f)),
80
+ ),
81
+ )
82
+
83
+ assertEquals(2, mixed.size)
84
+ assertFalse(hit(mixed, 16f, 10f))
85
+ assertTrue(hit(mixed, 35f, 10f))
86
+ assertFalse(hit(mixed, 46f, 10f))
87
+ assertTrue(hit(mixed, 70f, 10f))
88
+ // Only the outer edge of the last run faces blank space.
89
+ assertTrue(hit(mixed, 92f, 10f))
90
+ assertEquals(32f, mixed[0].left)
91
+ assertEquals(38f, mixed[0].right)
92
+ assertEquals(55f, mixed[1].left)
93
+ }
94
+
95
+ // A narrow row wraps the description. The time stays outside the action on
96
+ // its line, while the address is hit on both lines, also at the x the time
97
+ // occupies one line above.
98
+ @Test
99
+ fun aWrappedDescriptionKeepsTheTimeOutsideTheAction() {
100
+ val wrapped = regions(
101
+ NativeListTextLine(top = 0f, bottom = 20f, touchable = listOf(run(55f, 110f)), plain = listOf(run(0f, 55f))),
102
+ NativeListTextLine(top = 20f, bottom = 40f, touchable = listOf(run(0f, 100f))),
103
+ )
104
+ assertFalse(hit(wrapped, 20f, 10f))
105
+ assertTrue(hit(wrapped, 80f, 10f))
106
+ assertTrue(hit(wrapped, 20f, 30f))
107
+ assertFalse(hit(wrapped, 130f, 30f))
108
+
109
+ // The whole time sits on the first line: that line takes no touches at all.
110
+ val timeOnItsOwnLine = regions(
111
+ NativeListTextLine(top = 0f, bottom = 20f, touchable = emptyList(), plain = listOf(run(0f, 55f))),
112
+ NativeListTextLine(top = 20f, bottom = 40f, touchable = listOf(run(0f, 100f))),
113
+ )
114
+ assertFalse(hit(timeOnItsOwnLine, 20f, 10f))
115
+ // Nor does the address line reach up into it.
116
+ assertFalse(hit(timeOnItsOwnLine, 20f, 19f))
117
+ assertTrue(hit(timeOnItsOwnLine, 20f, 30f))
118
+ }
119
+
120
+ // A start at the end of the text leaves nothing to touch.
121
+ @Test
122
+ fun aLineWithoutTouchableTextLeavesNoRegion() {
123
+ val none = regions(NativeListTextLine(top = 0f, bottom = 20f, touchable = emptyList(), plain = listOf(run(0f, 55f))))
124
+
125
+ assertTrue(none.isEmpty())
126
+ }
127
+
128
+ // `descriptionActionStart` is a UTF-16 offset into the caller's string. It is
129
+ // kept within the text, and follows the line breaks a one-line view folds.
130
+ @Test
131
+ fun theCallersStartIsMappedOntoTheDisplayedText() {
132
+ val label = "Router • V2"
133
+ assertEquals(0, nativeListDisplayOffset(label, 0, foldsLineBreaks = false))
134
+ assertEquals(8, nativeListDisplayOffset("08:48 • $label", 8, foldsLineBreaks = false))
135
+ assertEquals(0, nativeListDisplayOffset(label, -3, foldsLineBreaks = false))
136
+ assertEquals(label.length, nativeListDisplayOffset(label, 99, foldsLineBreaks = false))
137
+ // Any safe integer arrives over JSON. One past Int range still clamps to
138
+ // the end; narrowed to Int first it would wrap to 0, the whole text.
139
+ assertEquals(label.length, nativeListDisplayOffset(label, 4_294_967_296L, foldsLineBreaks = false))
140
+ assertEquals(label.length, nativeListDisplayOffset(label, Long.MAX_VALUE, foldsLineBreaks = true))
141
+
142
+ // The emoji takes two UTF-16 units, as in the JavaScript string.
143
+ val emojiPrefix = "🕘 08:48 • "
144
+ assertEquals(11, emojiPrefix.length)
145
+ assertEquals(label, "$emojiPrefix$label".substring(nativeListDisplayOffset("$emojiPrefix$label", 11, foldsLineBreaks = false)))
146
+
147
+ val broken = "08:48\r\n• Router"
148
+ assertEquals("08:48 • Router", nativeListFoldLineBreaks(broken))
149
+ assertEquals(8, nativeListDisplayOffset(broken, 9, foldsLineBreaks = true))
150
+ assertEquals(9, nativeListDisplayOffset(broken, 9, foldsLineBreaks = false))
151
+ assertEquals(14, nativeListDisplayOffset(broken, 99, foldsLineBreaks = true))
152
+ }
153
+ }
@@ -181,7 +181,10 @@ separately from source implementation in STYLE_SPEC §9.
181
181
  - **Native rich amounts:** optional `amounts` replaces the legacy two strings,
182
182
  with at most 32 unique keyed entries. Each entry supports a leading visual,
183
183
  tone, primary/secondary text and subscript segments. The title supports at
184
- most four keyed badges. `descriptionActionKey` emits a description action.
184
+ most four keyed badges. `descriptionActionKey` emits a description action on
185
+ the description text from `descriptionActionStart` on (a UTF-16 offset the
186
+ caller supplies; default `0`, the whole text). The text before it and the
187
+ rest of the line stay with the row press.
185
188
  `presentation: 'table'` allocates identity (including the leading visual and
186
189
  its gap), amounts and optional fee in a stable `1:1:0.6` ratio after column
187
190
  gaps. Without fee, identity and amounts have equal widths. Amount content
package/docs/SPEC.md CHANGED
@@ -1787,6 +1787,61 @@ tones. `descriptionActionKey` makes only the description emit that action with
1787
1787
  source `description`; footer actions retain their existing source/keys and
1788
1788
  disabled behavior. All actions use the current host binding epoch.
1789
1789
 
1790
+ Description action text. The action is hit on text only, never on the unused
1791
+ width of the description line, which belongs to the row press. Which text is
1792
+ stated by the caller in `descriptionActionStart`, a UTF-16 offset into
1793
+ `description` as supplied (JavaScript string index): the text from the offset on
1794
+ opens the action, the text before it is plain and belongs to the row press.
1795
+ NativeList never derives the offset from the displayed string, its separators or
1796
+ its wording; a caller that composes `prefix + label` records `prefix.length`.
1797
+
1798
+ - Absent means `0`: the whole description text is the action.
1799
+ `description.length` leaves no action text; the row then has no description
1800
+ action, and no button semantics, on any platform.
1801
+ - The field is ignored without `descriptionActionKey`.
1802
+ - Development validation rejects a value that is not a non-negative safe
1803
+ integer, and on a complete row (a snapshot row, or a row after a patch is
1804
+ merged) a value past `description.length`. Production drops a malformed value,
1805
+ which restores the default, and renderers clamp a value past the text to its
1806
+ end.
1807
+ - A patch that changes `description` without `descriptionActionStart` clears the
1808
+ stored offset, because it pointed into the previous string. Callers that keep
1809
+ a prefix restate the offset in the same patch.
1810
+ - iOS and Android map the offset onto the displayed text: a one-line description
1811
+ folds each line break into one space, so offsets after a CRLF move by one.
1812
+ - The hit area follows the laid-out text. iOS and Android build it from the
1813
+ layout engine's own rects for the action's character range (TextKit enclosing
1814
+ rects, the Android layout's selection), one per line and per visual run. A
1815
+ line that ends before the offset takes no touches, the line that holds it
1816
+ takes them from the offset on, later lines take them on their text. In
1817
+ mixed-direction text the action can be several runs on one line with plain
1818
+ text between them, and each run is its own region.
1819
+ - Touch slop reaches into blank space only. iOS and Android widen each run of
1820
+ action text by 8 units, and the widening stops at plain description text on
1821
+ the same line: text before the offset never opens the action, however narrow
1822
+ it is. iOS also extends the first and the last line of the whole layout by 6
1823
+ points away from the text, never a line in between, so the slop cannot reach
1824
+ into a line that holds only plain text. Android extends the first and last
1825
+ line of the layout to the view's top and bottom edge.
1826
+ - An ellipsis belongs to the action while action text is visible before it.
1827
+ Once truncation hides the action text altogether the ellipsis also stands for
1828
+ plain text, and the row has no hit area for the action.
1829
+ - Truncation. The description stays on its declared lines as `prefix + action`.
1830
+ On Web the prefix keeps its natural width and the action text truncates
1831
+ first, which matches the tail truncation of the native label. While action
1832
+ text follows, the Web prefix is capped at the row width less `3em` and
1833
+ truncates itself, so a prefix wider than the row cannot squeeze the action to
1834
+ nothing and leave it without a pointer target. iOS and Android draw one label
1835
+ and truncate its tail; they do not reserve room, so there a long prefix can
1836
+ push the action text out of view. The Web prefix and action are two elements
1837
+ side by side and each resolves its own text direction, so an offset inside a
1838
+ directional run draws that run in two parts; the action element is still
1839
+ exactly the action text.
1840
+ - Internally the native text view holds one optional start: none keeps the
1841
+ view's own hit testing (rows without the action), `0` limits touches to all of
1842
+ the text, a positive value to the text from there on. Binding, rebinding
1843
+ without the action and recycling set or clear that one value.
1844
+
1790
1845
  Rich rows measure the declared line/visual metrics; there is no six-line native
1791
1846
  truncation. iOS automatic height mirrors the rendered stacks: `lineGap` between the
1792
1847
  visible title/description/status lines, the description measured at the identity
@@ -187,17 +187,24 @@ final class NativeListActivityDetailsView: UIStackView {
187
187
  weight: .medium, color: nativeListColor(theme, "primaryText", "#202020"), lineHeight: 24,
188
188
  lines: 1, fonts: fonts
189
189
  ).bind(title)
190
- NativeListResolvedText(data.string("description"), style: style.dictionary("description"), size: 14,
190
+ let descriptionText = NativeListResolvedText(data.string("description"), style: style.dictionary("description"), size: 14,
191
191
  color: nativeListColor(theme, "secondaryText", "#646464"), lineHeight: 20, lines: 2,
192
- fonts: fonts
193
- ).bind(descriptionLabel)
192
+ fonts: fonts)
193
+ descriptionText.bind(descriptionLabel)
194
194
  NativeListResolvedText(data.string("status"), style: style.dictionary("status"), size: 12,
195
195
  color: nativeListColor(theme, "secondaryText", "#646464"), lineHeight: 16, lines: 1,
196
196
  fonts: fonts
197
197
  ).bind(status)
198
198
  descriptionKey = data.string("descriptionActionKey")
199
- descriptionLabel.isUserInteractionEnabled = !descriptionKey.isEmpty
200
- descriptionLabel.accessibilityTraits = descriptionKey.isEmpty ? .staticText : .button
199
+ // The label spans the identity column, so with an action only its text
200
+ // from the caller's `descriptionActionStart` on takes touches. The start is
201
+ // never read out of the string, and one at the end leaves no action.
202
+ let actionStart = descriptionKey.isEmpty
203
+ ? nil : descriptionText.displayOffset(data.int("descriptionActionStart"), in: data.string("description"))
204
+ let hasActionText = actionStart.map { $0 < (descriptionText.text as NSString).length } ?? false
205
+ descriptionLabel.touchableTextStart = actionStart
206
+ descriptionLabel.isUserInteractionEnabled = hasActionText
207
+ descriptionLabel.accessibilityTraits = hasActionText ? .button : .staticText
201
208
  for badge in badgeViews { titleLine.removeArrangedSubview(badge); badge.removeFromSuperview() }
202
209
  badgeViews = data.dictionaries("badges").map { descriptor in
203
210
  let label = NativeListTextLabel()
@@ -269,6 +276,7 @@ final class NativeListActivityDetailsView: UIStackView {
269
276
  }
270
277
  func recycle() {
271
278
  visual.recycle(); visual.isHidden = false; amountViews.forEach { $0.recycle() }; actionKeys = []; descriptionKey = ""
279
+ descriptionLabel.touchableTextStart = nil
272
280
  }
273
281
  }
274
282
 
@@ -29,10 +29,7 @@ struct NativeListResolvedText {
29
29
  let requestedLines = style.int("lines", default: lines)
30
30
  self.lines = requestedLines == 0 ? 0 : min(3, max(1, requestedLines))
31
31
  explicitTruncation = style["lines"] != nil || style["truncate"] != nil
32
- text =
33
- self.lines == 1 && explicitTruncation
34
- ? value.replacingOccurrences(of: "\r\n|[\r\n]", with: " ", options: .regularExpression)
35
- : value
32
+ text = self.lines == 1 && explicitTruncation ? Self.foldingLineBreaks(value) : value
36
33
  let resolvedWeight: NativeListFontWeight
37
34
  switch style.string("fontWeight") {
38
35
  case "regular": resolvedWeight = .regular
@@ -59,6 +56,20 @@ struct NativeListResolvedText {
59
56
  offsetY = CGFloat(style.double("offsetY"))
60
57
  }
61
58
 
59
+ private static func foldingLineBreaks(_ value: String) -> String {
60
+ value.replacingOccurrences(of: "\r\n|[\r\n]", with: " ", options: .regularExpression)
61
+ }
62
+
63
+ /// UTF-16 offset in `text` for an offset into the caller's `source`, kept
64
+ /// within the text. A one-line label folds each line break into one space,
65
+ /// which moves every offset after a CRLF.
66
+ func displayOffset(_ offset: Int, in source: String) -> Int {
67
+ let units = source as NSString
68
+ let clamped = min(max(offset, 0), units.length)
69
+ guard lines == 1, explicitTruncation else { return clamped }
70
+ return (Self.foldingLineBreaks(units.substring(to: clamped)) as NSString).length
71
+ }
72
+
62
73
  /// Start/end follow the host view's layout direction, as legacy `marketTextAlignment` did.
63
74
  func alignment(for direction: UIUserInterfaceLayoutDirection) -> NSTextAlignment {
64
75
  guard let alignmentName else { return .natural }
@@ -3,6 +3,112 @@ import UIKit
3
3
  class NativeListTextLabel: UILabel {
4
4
  var rowVerticalAlignment: String? { didSet { setNeedsDisplay() } }
5
5
  var rowOffsetY: CGFloat = 0 { didSet { setNeedsDisplay() } }
6
+ /// UTF-16 offset the touchable text starts at. `nil` keeps the label's own
7
+ /// hit testing, its whole bounds. With an offset only the drawn text from
8
+ /// there on takes touches, plus a small slop, so text before the offset and
9
+ /// the unused width of a stretched label fall through to the row behind it:
10
+ /// `0` covers all of the text, the text length leaves nothing to touch.
11
+ var touchableTextStart: Int?
12
+ private static let touchSlop = CGSize(width: 8, height: 6)
13
+
14
+ /// One rect per laid-out run of touchable text, in label coordinates. The
15
+ /// label's own layout is not public, so the runs come from a text container
16
+ /// with the label's width, line cap and truncation. A line holds one run, or
17
+ /// several where mixed-direction text puts plain text between touchable text.
18
+ var touchableTextRegions: [CGRect] {
19
+ guard let start = touchableTextStart, let attributed = attributedText, attributed.length > start,
20
+ bounds.width > 0
21
+ else { return [] }
22
+ let storage = NSTextStorage(attributedString: attributed)
23
+ let manager = NSLayoutManager()
24
+ let container = NSTextContainer(
25
+ size: CGSize(width: bounds.width, height: .greatestFiniteMagnitude))
26
+ container.lineFragmentPadding = 0
27
+ container.maximumNumberOfLines = numberOfLines
28
+ container.lineBreakMode = lineBreakMode
29
+ manager.addTextContainer(container)
30
+ storage.addLayoutManager(manager)
31
+ let glyphs = manager.glyphRange(for: container)
32
+ // Mirrors drawText: the text is centered unless the row aligns it.
33
+ let textHeight = manager.usedRect(for: container).height
34
+ var originY = (bounds.height - textHeight) / 2
35
+ if let alignment = rowVerticalAlignment {
36
+ originY = alignment == "top" ? 0 : alignment == "bottom" ? bounds.height - textHeight : originY
37
+ }
38
+ originY += rowOffsetY
39
+ var lines: [CGRect] = []
40
+ var visibleEnd = attributed.length
41
+ manager.enumerateLineFragments(forGlyphRange: glyphs) { _, usedRect, _, lineGlyphs, _ in
42
+ lines.append(usedRect)
43
+ let truncated = manager.truncatedGlyphRange(inLineFragmentForGlyphAt: lineGlyphs.location)
44
+ if truncated.location != NSNotFound {
45
+ visibleEnd = min(visibleEnd, manager.characterIndexForGlyph(at: truncated.location))
46
+ }
47
+ }
48
+ // Truncation can hide the touchable text altogether. The ellipsis then
49
+ // stands for plain text as well, so nothing is left to touch.
50
+ guard start < visibleEnd else { return [] }
51
+ // The layout engine's own rects for a character range: one per line and
52
+ // per visual run, which is what makes mixed-direction text come out right.
53
+ func runs(_ characters: NSRange) -> [CGRect] {
54
+ let range = NSIntersectionRange(
55
+ manager.glyphRange(forCharacterRange: characters, actualCharacterRange: nil), glyphs)
56
+ guard range.length > 0 else { return [] }
57
+ var rects: [CGRect] = []
58
+ manager.enumerateEnclosingRects(
59
+ forGlyphRange: range, withinSelectedGlyphRange: NSRange(location: NSNotFound, length: 0),
60
+ in: container
61
+ ) { rect, _ in
62
+ // A run that continues on the next line is reported up to the
63
+ // container edge; its text ends where the line's used rect does.
64
+ guard let used = lines.first(where: { $0.minY <= rect.midY && rect.midY < $0.maxY })
65
+ else { return }
66
+ let minX = max(rect.minX, used.minX)
67
+ let maxX = min(rect.maxX, used.maxX)
68
+ if maxX > minX {
69
+ rects.append(CGRect(x: minX, y: rect.minY, width: maxX - minX, height: rect.height))
70
+ }
71
+ }
72
+ return rects
73
+ }
74
+ let plain = runs(NSRange(location: 0, length: start))
75
+ return runs(NSRange(location: start, length: attributed.length - start)).map { run in
76
+ // The slop reaches into blank space only. Sideways it stops at plain
77
+ // text on the same line, so text before the start never takes the
78
+ // touch, however narrow it is.
79
+ var minX = run.minX - Self.touchSlop.width
80
+ var maxX = run.maxX + Self.touchSlop.width
81
+ for other in plain where other.minY < run.midY && run.midY < other.maxY {
82
+ if other.maxX <= run.minX + 0.5 { minX = max(minX, other.maxX) }
83
+ if other.minX >= run.maxX - 0.5 { maxX = min(maxX, other.minX) }
84
+ }
85
+ // Vertically it grows only past the first and last line of the whole
86
+ // layout, so it never reaches into another line.
87
+ let line = lines.firstIndex { $0.minY <= run.midY && run.midY < $0.maxY }
88
+ let top = line == 0 ? Self.touchSlop.height : 0
89
+ let bottom = line == lines.count - 1 ? Self.touchSlop.height : 0
90
+ return CGRect(
91
+ x: minX, y: run.minY + originY - top, width: maxX - minX,
92
+ height: run.height + top + bottom)
93
+ }
94
+ }
95
+
96
+ override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
97
+ guard touchableTextStart != nil else { return super.point(inside: point, with: event) }
98
+ return touchableTextRegions.contains { $0.contains(point) }
99
+ }
100
+
101
+ // Assistive activation taps this point; the label's center can be blank.
102
+ override var accessibilityActivationPoint: CGPoint {
103
+ get {
104
+ guard let region = touchableTextRegions.first else {
105
+ return super.accessibilityActivationPoint
106
+ }
107
+ let target = UIAccessibility.convertToScreenCoordinates(region.intersection(bounds), in: self)
108
+ return CGPoint(x: target.midX, y: target.midY)
109
+ }
110
+ set { super.accessibilityActivationPoint = newValue }
111
+ }
6
112
 
7
113
  override func drawText(in rect: CGRect) {
8
114
  var target = rect