diff --git a/native-views/react-native-native-list/android/src/main/java/com/onekey/nativelist/NativeListActivityDetailsView.kt b/native-views/react-native-native-list/android/src/main/java/com/onekey/nativelist/NativeListActivityDetailsView.kt index d45ea604c..7c180e12b 100644 --- a/native-views/react-native-native-list/android/src/main/java/com/onekey/nativelist/NativeListActivityDetailsView.kt +++ b/native-views/react-native-native-list/android/src/main/java/com/onekey/nativelist/NativeListActivityDetailsView.kt @@ -78,9 +78,9 @@ internal class NativeListActivityDetailsView(private val reactContext: ThemedRea return parseNativeListColor(theme?.optString(key, fallback) ?: fallback) } private fun text(label: NativeListTextView, value: String, style: JSONObject?, size: Float, - ink: Int, line: Int, weight: String = "regular", lines: Int = 1) { - NativeListResolvedText.resolve(context, fonts, value, style, size, weight, ink, line, lines, sourceScale).bind(label) - } + ink: Int, line: Int, weight: String = "regular", lines: Int = 1): NativeListResolvedText = + NativeListResolvedText.resolve(context, fonts, value, style, size, weight, ink, line, lines, sourceScale) + .also { it.bind(label) } fun bind(item: NativeListItem, theme: JSONObject?, sourceScale: Boolean) { this.sourceScale = sourceScale val data = item.json @@ -98,12 +98,20 @@ internal class NativeListActivityDetailsView(private val reactContext: ThemedRea setClipping(nativeListActivityHostClips(leadingOverhangs)) amounts.layoutParams = if (table) LayoutParams(0, -2, 1f).apply { marginStart = gap } else LayoutParams(-2, -2).apply { marginStart = gap } text(title, data.optString("title"), style.optJSONObject("title"), 16f, color("primary", theme), 24, "medium") - text(description, data.optString("description"), style.optJSONObject("description"), 14f, color("secondary", theme), 20, lines = 2) + val descriptionText = text(description, data.optString("description"), style.optJSONObject("description"), 14f, color("secondary", theme), 20, lines = 2) text(status, data.optString("status"), style.optJSONObject("status"), 12f, color("secondary", theme), 16) description.setOnClickListener(null) val descriptionKey = data.optString("descriptionActionKey") - description.isClickable = descriptionKey.isNotEmpty() - if (descriptionKey.isNotEmpty()) description.setOnClickListener { onAction?.invoke(descriptionKey, description, "description", 0) } + // The view spans the identity column, so with an action only its text from + // the caller's `descriptionActionStart` on takes touches. The start is + // never read out of the string, and one at the end leaves no action. + val actionStart = + if (descriptionKey.isEmpty()) null + else descriptionText.displayOffset(data.optLong("descriptionActionStart"), data.optString("description")) + val hasActionText = actionStart != null && actionStart < descriptionText.text.length + description.touchableTextStart = actionStart + description.isClickable = hasActionText + if (hasActionText) description.setOnClickListener { onAction?.invoke(descriptionKey, description, "description", 0) } for (view in listOf(description, status)) (view.layoutParams as LayoutParams).topMargin = if (style.has("lineGap")) px(style.optDouble("lineGap")) else 0 badges.forEach(titleLine::removeView); badges.clear() val badgeData = data.optJSONArray("badges") @@ -172,6 +180,7 @@ internal class NativeListActivityDetailsView(private val reactContext: ThemedRea } fun recycle() { visual.recycle(); visual.visibility = VISIBLE; amountViews.forEach { it.recycle() }; description.setOnClickListener(null); actions.removeAllViews() + description.touchableTextStart = null leadingOverhangs = false setClipping(true) } diff --git a/native-views/react-native-native-list/android/src/main/java/com/onekey/nativelist/NativeListModels.kt b/native-views/react-native-native-list/android/src/main/java/com/onekey/nativelist/NativeListModels.kt index 0eec67a28..8d1719005 100644 --- a/native-views/react-native-native-list/android/src/main/java/com/onekey/nativelist/NativeListModels.kt +++ b/native-views/react-native-native-list/android/src/main/java/com/onekey/nativelist/NativeListModels.kt @@ -62,6 +62,66 @@ internal fun nativeListLeadingVisualOverhangsFrame( */ internal fun nativeListActivityHostClips(leadingOverhangs: Boolean): Boolean = !leadingOverhangs +/** A one-line text view shows each line break of its text as one space. */ +internal fun nativeListFoldLineBreaks(text: String): String = text.replace(Regex("\\r\\n|[\\r\\n]"), " ") + +/** + * Offset into the displayed text for [sourceOffset], a UTF-16 offset into the + * caller's [source], kept within the text. Folding line breaks + * ([nativeListFoldLineBreaks]) moves every offset after a CRLF. The offset is a + * Long because JSON carries any safe integer; narrowing it first would wrap a + * value past Int range instead of clamping it to the end. + */ +internal fun nativeListDisplayOffset(source: String, sourceOffset: Long, foldsLineBreaks: Boolean): Int { + val clamped = sourceOffset.coerceIn(0L, source.length.toLong()).toInt() + return if (foldsLineBreaks) nativeListFoldLineBreaks(source.substring(0, clamped)).length else clamped +} + +/** A horizontal run of laid-out text on one line, in view coordinates. */ +internal data class NativeListTextRun(val left: Float, val right: Float) + +/** + * One laid-out line of a text view, in view coordinates: its vertical extent, + * the runs of [touchable] text and the runs of [plain] text before it. A line + * holds one run of each, or several where mixed-direction text puts plain text + * between touchable text. + */ +internal data class NativeListTextLine( + val top: Float, + val bottom: Float, + val touchable: List, + val plain: List = emptyList(), +) + +internal data class NativeListTouchRegion(val left: Float, val top: Float, val right: Float, val bottom: Float) { + fun contains(x: Float, y: Float): Boolean = x in left..right && y in top..bottom +} + +/** Runs are read back from pixel regions, so neighbours can be a pixel apart. */ +private const val TEXT_RUN_EDGE = 1f + +/** + * Parts of a stretched text view that take touches: every run of touchable + * text, widened by [slop] into blank space only. The widening stops at plain + * text on the same line, so text before the touchable text never takes the + * touch, however narrow it is. Touches outside the regions fall through to the + * row behind the view (OK-67219). + */ +internal fun nativeListTouchableTextRegions( + lines: List, + slop: Float, +): List = lines.flatMap { line -> + line.touchable.map { run -> + var left = run.left - slop + var right = run.right + slop + for (other in line.plain) { + if (other.right <= run.left + TEXT_RUN_EDGE) left = maxOf(left, other.right) + if (other.left >= run.right - TEXT_RUN_EDGE) right = minOf(right, other.left) + } + NativeListTouchRegion(left, line.top, right, line.bottom) + } +} + internal data class NativeListSlotFrame(val x: Int, val y: Int, val width: Int, val height: Int) /** Side of one member of an Activity token pair inside a [frame]-unit box (24 in 40). */ diff --git a/native-views/react-native-native-list/android/src/main/java/com/onekey/nativelist/NativeListResolvedText.kt b/native-views/react-native-native-list/android/src/main/java/com/onekey/nativelist/NativeListResolvedText.kt index 8d5c5e352..28228407a 100644 --- a/native-views/react-native-native-list/android/src/main/java/com/onekey/nativelist/NativeListResolvedText.kt +++ b/native-views/react-native-native-list/android/src/main/java/com/onekey/nativelist/NativeListResolvedText.kt @@ -43,6 +43,10 @@ internal data class NativeListResolvedText( val gravity: Int, val offset: Float, ) { + /** Offset into [text] for a UTF-16 offset into the [source] it was resolved from. */ + fun displayOffset(sourceOffset: Long, source: String): Int = + nativeListDisplayOffset(source, sourceOffset, foldsLineBreaks = lines == 1 && explicitTruncation) + fun bind(view: NativeListTextView) { view.includeFontPadding = false view.fontFeatureSettings = "tnum" @@ -119,7 +123,7 @@ internal data class NativeListResolvedText( else -> Gravity.TOP } return NativeListResolvedText( - if (maxLines == 1 && truncation) text.replace(Regex("\\r\\n|[\\r\\n]"), " ") else text, + if (maxLines == 1 && truncation) nativeListFoldLineBreaks(text) else text, fontSize, face, style diff --git a/native-views/react-native-native-list/android/src/main/java/com/onekey/nativelist/NativeListTextView.kt b/native-views/react-native-native-list/android/src/main/java/com/onekey/nativelist/NativeListTextView.kt index 2a26f062b..d365d08be 100644 --- a/native-views/react-native-native-list/android/src/main/java/com/onekey/nativelist/NativeListTextView.kt +++ b/native-views/react-native-native-list/android/src/main/java/com/onekey/nativelist/NativeListTextView.kt @@ -3,9 +3,16 @@ package com.margelo.nitro.nativelist import android.graphics.Canvas import android.graphics.DashPathEffect import android.graphics.Paint +import android.graphics.Path +import android.graphics.Rect import android.graphics.RectF +import android.graphics.Region +import android.graphics.RegionIterator +import android.text.Layout import android.view.MotionEvent import android.widget.TextView +import kotlin.math.ceil +import kotlin.math.floor internal open class NativeListTextView(context: android.content.Context) : TextView(context) { var helpBindingGeneration = 0 @@ -33,9 +40,73 @@ internal open class NativeListTextView(context: android.content.Context) : TextV ) } + /** + * Character offset the touchable text starts at. `null` keeps the view's own + * hit testing, its whole bounds. With an offset only the drawn text from + * there on takes touches, plus a small horizontal slop, so text before the + * offset and the unused width of a stretched view fall through to the row + * behind it: `0` covers all of the text, the text length leaves nothing to + * touch. + */ + var touchableTextStart: Int? = null + + val touchableTextRegions: List + get() { + val textStart = touchableTextStart ?: return emptyList() + val textLayout = layout ?: return emptyList() + // Lines past the line cap are laid out but never drawn. + val count = minOf(textLayout.lineCount, maxLines.takeIf { it > 0 } ?: Int.MAX_VALUE) + if (count == 0) return emptyList() + val originX = totalPaddingLeft.toFloat() + val originY = totalPaddingTop + opticalOffsetY + val lines = (0 until count).map { line -> + val lineStart = textLayout.getLineStart(line) + val lineEnd = textLayout.getLineEnd(line) + // An ellipsis hides the rest of its line. Once it hides the touchable + // text as well it also stands for plain text, so nothing is left to touch. + val visibleEnd = + if (textLayout.getEllipsisCount(line) > 0) lineStart + textLayout.getEllipsisStart(line) else lineEnd + val touchableStart = maxOf(textStart, lineStart) + NativeListTextLine( + // The outer lines also take the view's own vertical padding. + top = if (line == 0) 0f else originY + textLayout.getLineTop(line), + bottom = if (line == count - 1) height.toFloat() else originY + textLayout.getLineBottom(line), + touchable = + if (touchableStart < visibleEnd) textRuns(textLayout, line, touchableStart, lineEnd, originX) + else emptyList(), + plain = textRuns(textLayout, line, lineStart, minOf(textStart, lineEnd), originX), + ) + } + return nativeListTouchableTextRegions(lines, TOUCH_SLOP_DP * resources.displayMetrics.density) + } + + /** + * Horizontal extents the layout gives characters `[from, to)` of [line]: the + * layout's own selection, so mixed-direction text yields one run per + * direction run instead of one box around all of them. + */ + private fun textRuns(textLayout: Layout, line: Int, from: Int, to: Int, originX: Float): List { + if (from >= to) return emptyList() + val selection = Path() + textLayout.getSelectionPath(from, to, selection) + // A selection that reaches the line end also covers the blank up to the + // layout edge and starts the next line; only this line's text counts. + val lineBounds = Region( + floor(textLayout.getLineLeft(line)).toInt(), textLayout.getLineTop(line), + ceil(textLayout.getLineRight(line)).toInt(), textLayout.getLineBottom(line), + ) + val runs = mutableListOf() + val iterator = RegionIterator(Region().apply { setPath(selection, lineBounds) }) + val run = Rect() + while (iterator.next(run)) runs += NativeListTextRun(originX + run.left, originX + run.right) + return runs + } + override fun onTouchEvent(event: MotionEvent): Boolean { if (primaryHelpOnly && event.actionMasked == MotionEvent.ACTION_DOWN && helpAnchorBounds?.contains(event.x, event.y) != true) return false + if (touchableTextStart != null && event.actionMasked == MotionEvent.ACTION_DOWN && + touchableTextRegions.none { it.contains(event.x, event.y) }) return false if (guardsHelpTouches) { if (event.actionMasked == MotionEvent.ACTION_DOWN) helpDownGeneration = helpBindingGeneration if (event.actionMasked == MotionEvent.ACTION_UP && helpDownGeneration != helpBindingGeneration) { @@ -76,4 +147,8 @@ internal open class NativeListTextView(context: android.content.Context) : TextV drawHelpUnderline(canvas) canvas.restoreToCount(checkpoint) } + + private companion object { + const val TOUCH_SLOP_DP = 8f + } } diff --git a/native-views/react-native-native-list/android/src/test/java/com/margelo/nitro/nativelist/NativeListDescriptionTouchPolicyTest.kt b/native-views/react-native-native-list/android/src/test/java/com/margelo/nitro/nativelist/NativeListDescriptionTouchPolicyTest.kt new file mode 100644 index 000000000..3addf0224 --- /dev/null +++ b/native-views/react-native-native-list/android/src/test/java/com/margelo/nitro/nativelist/NativeListDescriptionTouchPolicyTest.kt @@ -0,0 +1,153 @@ +package com.margelo.nitro.nativelist + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class NativeListDescriptionTouchPolicyTest { + private fun hit(regions: List, x: Float, y: Float) = regions.any { it.contains(x, y) } + + private fun run(left: Float, right: Float) = NativeListTextRun(left, right) + + private fun regions(vararg lines: NativeListTextLine) = nativeListTouchableTextRegions(lines.toList(), slop = 8f) + + // The description view spans the identity column, so a tap anywhere on its + // line used to open the description action. Only the text opens it now; the + // blank rest of the line belongs to the row press (OK-67219). + @Test + fun onlyTheDrawnTextTakesTouches() { + val text = regions(NativeListTextLine(top = 0f, bottom = 20f, touchable = listOf(run(0f, 60f)))) + + assertTrue(hit(text, 30f, 10f)) + // The slop reaches into the blank on both sides of the text. + assertTrue(hit(text, 66f, 10f)) + assertTrue(hit(text, -6f, 10f)) + assertFalse(hit(text, 120f, 10f)) + } + + // The caller states where the action text starts; the text before it, a + // time for one, is not part of the action. + @Test + fun textBeforeTheStartIsNotPartOfTheAction() { + val ltr = regions( + NativeListTextLine(top = 0f, bottom = 20f, touchable = listOf(run(50f, 160f)), plain = listOf(run(0f, 50f))), + ) + assertFalse(hit(ltr, 20f, 10f)) + assertTrue(hit(ltr, 100f, 10f)) + + // Right to left the plain text sits on the right of the touchable text. + val rtl = regions( + NativeListTextLine(top = 0f, bottom = 20f, touchable = listOf(run(40f, 150f)), plain = listOf(run(150f, 200f))), + ) + assertTrue(hit(rtl, 100f, 10f)) + assertFalse(hit(rtl, 180f, 10f)) + } + + // The slop is for blank space. It must not reach into plain text beside the + // touchable text, or a prefix narrower than the slop, like the "i" of + // "iRouter", would open the action it is not part of. + @Test + fun theSlopStopsAtPlainTextBesideTheTouchableText() { + val short = regions( + NativeListTextLine(top = 0f, bottom = 20f, touchable = listOf(run(3f, 46f)), plain = listOf(run(0f, 3f))), + ) + assertFalse(hit(short, 1.5f, 10f)) + assertFalse(hit(short, -4f, 10f)) + assertTrue(hit(short, 4f, 10f)) + assertTrue(hit(short, 52f, 10f)) + assertEquals(3f, short.single().left) + assertEquals(54f, short.single().right) + + // Neighbouring runs read back from pixel regions may be a pixel apart. + val apart = regions( + NativeListTextLine(top = 0f, bottom = 20f, touchable = listOf(run(4f, 46f)), plain = listOf(run(0f, 3f))), + ) + assertEquals(3f, apart.single().left) + } + + // Mixed-direction text can split one logical suffix into several visual + // runs with plain text between them: "ABC אבג XYZ" from the last Hebrew + // letter on draws that letter left of the two plain ones. Each run is its + // own region, and the plain text between them takes no touches. + @Test + fun aSuffixSplitByMixedDirectionTextIsSeveralRuns() { + val mixed = regions( + NativeListTextLine( + top = 0f, bottom = 20f, + touchable = listOf(run(32f, 38f), run(55f, 86f)), + plain = listOf(run(0f, 32f), run(38f, 55f)), + ), + ) + + assertEquals(2, mixed.size) + assertFalse(hit(mixed, 16f, 10f)) + assertTrue(hit(mixed, 35f, 10f)) + assertFalse(hit(mixed, 46f, 10f)) + assertTrue(hit(mixed, 70f, 10f)) + // Only the outer edge of the last run faces blank space. + assertTrue(hit(mixed, 92f, 10f)) + assertEquals(32f, mixed[0].left) + assertEquals(38f, mixed[0].right) + assertEquals(55f, mixed[1].left) + } + + // A narrow row wraps the description. The time stays outside the action on + // its line, while the address is hit on both lines, also at the x the time + // occupies one line above. + @Test + fun aWrappedDescriptionKeepsTheTimeOutsideTheAction() { + val wrapped = regions( + NativeListTextLine(top = 0f, bottom = 20f, touchable = listOf(run(55f, 110f)), plain = listOf(run(0f, 55f))), + NativeListTextLine(top = 20f, bottom = 40f, touchable = listOf(run(0f, 100f))), + ) + assertFalse(hit(wrapped, 20f, 10f)) + assertTrue(hit(wrapped, 80f, 10f)) + assertTrue(hit(wrapped, 20f, 30f)) + assertFalse(hit(wrapped, 130f, 30f)) + + // The whole time sits on the first line: that line takes no touches at all. + val timeOnItsOwnLine = regions( + NativeListTextLine(top = 0f, bottom = 20f, touchable = emptyList(), plain = listOf(run(0f, 55f))), + NativeListTextLine(top = 20f, bottom = 40f, touchable = listOf(run(0f, 100f))), + ) + assertFalse(hit(timeOnItsOwnLine, 20f, 10f)) + // Nor does the address line reach up into it. + assertFalse(hit(timeOnItsOwnLine, 20f, 19f)) + assertTrue(hit(timeOnItsOwnLine, 20f, 30f)) + } + + // A start at the end of the text leaves nothing to touch. + @Test + fun aLineWithoutTouchableTextLeavesNoRegion() { + val none = regions(NativeListTextLine(top = 0f, bottom = 20f, touchable = emptyList(), plain = listOf(run(0f, 55f)))) + + assertTrue(none.isEmpty()) + } + + // `descriptionActionStart` is a UTF-16 offset into the caller's string. It is + // kept within the text, and follows the line breaks a one-line view folds. + @Test + fun theCallersStartIsMappedOntoTheDisplayedText() { + val label = "Router • V2" + assertEquals(0, nativeListDisplayOffset(label, 0, foldsLineBreaks = false)) + assertEquals(8, nativeListDisplayOffset("08:48 • $label", 8, foldsLineBreaks = false)) + assertEquals(0, nativeListDisplayOffset(label, -3, foldsLineBreaks = false)) + assertEquals(label.length, nativeListDisplayOffset(label, 99, foldsLineBreaks = false)) + // Any safe integer arrives over JSON. One past Int range still clamps to + // the end; narrowed to Int first it would wrap to 0, the whole text. + assertEquals(label.length, nativeListDisplayOffset(label, 4_294_967_296L, foldsLineBreaks = false)) + assertEquals(label.length, nativeListDisplayOffset(label, Long.MAX_VALUE, foldsLineBreaks = true)) + + // The emoji takes two UTF-16 units, as in the JavaScript string. + val emojiPrefix = "🕘 08:48 • " + assertEquals(11, emojiPrefix.length) + assertEquals(label, "$emojiPrefix$label".substring(nativeListDisplayOffset("$emojiPrefix$label", 11, foldsLineBreaks = false))) + + val broken = "08:48\r\n• Router" + assertEquals("08:48 • Router", nativeListFoldLineBreaks(broken)) + assertEquals(8, nativeListDisplayOffset(broken, 9, foldsLineBreaks = true)) + assertEquals(9, nativeListDisplayOffset(broken, 9, foldsLineBreaks = false)) + assertEquals(14, nativeListDisplayOffset(broken, 99, foldsLineBreaks = true)) + } +} diff --git a/native-views/react-native-native-list/docs/ROW_TEMPLATES.md b/native-views/react-native-native-list/docs/ROW_TEMPLATES.md index f0fef95e3..f292ff857 100644 --- a/native-views/react-native-native-list/docs/ROW_TEMPLATES.md +++ b/native-views/react-native-native-list/docs/ROW_TEMPLATES.md @@ -181,7 +181,10 @@ separately from source implementation in STYLE_SPEC §9. - **Native rich amounts:** optional `amounts` replaces the legacy two strings, with at most 32 unique keyed entries. Each entry supports a leading visual, tone, primary/secondary text and subscript segments. The title supports at - most four keyed badges. `descriptionActionKey` emits a description action. + most four keyed badges. `descriptionActionKey` emits a description action on + the description text from `descriptionActionStart` on (a UTF-16 offset the + caller supplies; default `0`, the whole text). The text before it and the + rest of the line stay with the row press. `presentation: 'table'` allocates identity (including the leading visual and its gap), amounts and optional fee in a stable `1:1:0.6` ratio after column gaps. Without fee, identity and amounts have equal widths. Amount content diff --git a/native-views/react-native-native-list/docs/SPEC.md b/native-views/react-native-native-list/docs/SPEC.md index 3e3964292..c82d2c521 100644 --- a/native-views/react-native-native-list/docs/SPEC.md +++ b/native-views/react-native-native-list/docs/SPEC.md @@ -1787,6 +1787,61 @@ tones. `descriptionActionKey` makes only the description emit that action with source `description`; footer actions retain their existing source/keys and disabled behavior. All actions use the current host binding epoch. +Description action text. The action is hit on text only, never on the unused +width of the description line, which belongs to the row press. Which text is +stated by the caller in `descriptionActionStart`, a UTF-16 offset into +`description` as supplied (JavaScript string index): the text from the offset on +opens the action, the text before it is plain and belongs to the row press. +NativeList never derives the offset from the displayed string, its separators or +its wording; a caller that composes `prefix + label` records `prefix.length`. + +- Absent means `0`: the whole description text is the action. + `description.length` leaves no action text; the row then has no description + action, and no button semantics, on any platform. +- The field is ignored without `descriptionActionKey`. +- Development validation rejects a value that is not a non-negative safe + integer, and on a complete row (a snapshot row, or a row after a patch is + merged) a value past `description.length`. Production drops a malformed value, + which restores the default, and renderers clamp a value past the text to its + end. +- A patch that changes `description` without `descriptionActionStart` clears the + stored offset, because it pointed into the previous string. Callers that keep + a prefix restate the offset in the same patch. +- iOS and Android map the offset onto the displayed text: a one-line description + folds each line break into one space, so offsets after a CRLF move by one. +- The hit area follows the laid-out text. iOS and Android build it from the + layout engine's own rects for the action's character range (TextKit enclosing + rects, the Android layout's selection), one per line and per visual run. A + line that ends before the offset takes no touches, the line that holds it + takes them from the offset on, later lines take them on their text. In + mixed-direction text the action can be several runs on one line with plain + text between them, and each run is its own region. +- Touch slop reaches into blank space only. iOS and Android widen each run of + action text by 8 units, and the widening stops at plain description text on + the same line: text before the offset never opens the action, however narrow + it is. iOS also extends the first and the last line of the whole layout by 6 + points away from the text, never a line in between, so the slop cannot reach + into a line that holds only plain text. Android extends the first and last + line of the layout to the view's top and bottom edge. +- An ellipsis belongs to the action while action text is visible before it. + Once truncation hides the action text altogether the ellipsis also stands for + plain text, and the row has no hit area for the action. +- Truncation. The description stays on its declared lines as `prefix + action`. + On Web the prefix keeps its natural width and the action text truncates + first, which matches the tail truncation of the native label. While action + text follows, the Web prefix is capped at the row width less `3em` and + truncates itself, so a prefix wider than the row cannot squeeze the action to + nothing and leave it without a pointer target. iOS and Android draw one label + and truncate its tail; they do not reserve room, so there a long prefix can + push the action text out of view. The Web prefix and action are two elements + side by side and each resolves its own text direction, so an offset inside a + directional run draws that run in two parts; the action element is still + exactly the action text. +- Internally the native text view holds one optional start: none keeps the + view's own hit testing (rows without the action), `0` limits touches to all of + the text, a positive value to the text from there on. Binding, rebinding + without the action and recycling set or clear that one value. + Rich rows measure the declared line/visual metrics; there is no six-line native truncation. iOS automatic height mirrors the rendered stacks: `lineGap` between the visible title/description/status lines, the description measured at the identity diff --git a/native-views/react-native-native-list/ios/NativeListActivityDetailsView.swift b/native-views/react-native-native-list/ios/NativeListActivityDetailsView.swift index 7f11094ee..665ee7369 100644 --- a/native-views/react-native-native-list/ios/NativeListActivityDetailsView.swift +++ b/native-views/react-native-native-list/ios/NativeListActivityDetailsView.swift @@ -187,17 +187,24 @@ final class NativeListActivityDetailsView: UIStackView { weight: .medium, color: nativeListColor(theme, "primaryText", "#202020"), lineHeight: 24, lines: 1, fonts: fonts ).bind(title) - NativeListResolvedText(data.string("description"), style: style.dictionary("description"), size: 14, + let descriptionText = NativeListResolvedText(data.string("description"), style: style.dictionary("description"), size: 14, color: nativeListColor(theme, "secondaryText", "#646464"), lineHeight: 20, lines: 2, - fonts: fonts - ).bind(descriptionLabel) + fonts: fonts) + descriptionText.bind(descriptionLabel) NativeListResolvedText(data.string("status"), style: style.dictionary("status"), size: 12, color: nativeListColor(theme, "secondaryText", "#646464"), lineHeight: 16, lines: 1, fonts: fonts ).bind(status) descriptionKey = data.string("descriptionActionKey") - descriptionLabel.isUserInteractionEnabled = !descriptionKey.isEmpty - descriptionLabel.accessibilityTraits = descriptionKey.isEmpty ? .staticText : .button + // The label spans the identity column, so with an action only its text + // from the caller's `descriptionActionStart` on takes touches. The start is + // never read out of the string, and one at the end leaves no action. + let actionStart = descriptionKey.isEmpty + ? nil : descriptionText.displayOffset(data.int("descriptionActionStart"), in: data.string("description")) + let hasActionText = actionStart.map { $0 < (descriptionText.text as NSString).length } ?? false + descriptionLabel.touchableTextStart = actionStart + descriptionLabel.isUserInteractionEnabled = hasActionText + descriptionLabel.accessibilityTraits = hasActionText ? .button : .staticText for badge in badgeViews { titleLine.removeArrangedSubview(badge); badge.removeFromSuperview() } badgeViews = data.dictionaries("badges").map { descriptor in let label = NativeListTextLabel() @@ -269,6 +276,7 @@ final class NativeListActivityDetailsView: UIStackView { } func recycle() { visual.recycle(); visual.isHidden = false; amountViews.forEach { $0.recycle() }; actionKeys = []; descriptionKey = "" + descriptionLabel.touchableTextStart = nil } } diff --git a/native-views/react-native-native-list/ios/NativeListResolvedText.swift b/native-views/react-native-native-list/ios/NativeListResolvedText.swift index 1cc06dd0b..c6c0ac08e 100644 --- a/native-views/react-native-native-list/ios/NativeListResolvedText.swift +++ b/native-views/react-native-native-list/ios/NativeListResolvedText.swift @@ -29,10 +29,7 @@ struct NativeListResolvedText { let requestedLines = style.int("lines", default: lines) self.lines = requestedLines == 0 ? 0 : min(3, max(1, requestedLines)) explicitTruncation = style["lines"] != nil || style["truncate"] != nil - text = - self.lines == 1 && explicitTruncation - ? value.replacingOccurrences(of: "\r\n|[\r\n]", with: " ", options: .regularExpression) - : value + text = self.lines == 1 && explicitTruncation ? Self.foldingLineBreaks(value) : value let resolvedWeight: NativeListFontWeight switch style.string("fontWeight") { case "regular": resolvedWeight = .regular @@ -59,6 +56,20 @@ struct NativeListResolvedText { offsetY = CGFloat(style.double("offsetY")) } + private static func foldingLineBreaks(_ value: String) -> String { + value.replacingOccurrences(of: "\r\n|[\r\n]", with: " ", options: .regularExpression) + } + + /// UTF-16 offset in `text` for an offset into the caller's `source`, kept + /// within the text. A one-line label folds each line break into one space, + /// which moves every offset after a CRLF. + func displayOffset(_ offset: Int, in source: String) -> Int { + let units = source as NSString + let clamped = min(max(offset, 0), units.length) + guard lines == 1, explicitTruncation else { return clamped } + return (Self.foldingLineBreaks(units.substring(to: clamped)) as NSString).length + } + /// Start/end follow the host view's layout direction, as legacy `marketTextAlignment` did. func alignment(for direction: UIUserInterfaceLayoutDirection) -> NSTextAlignment { guard let alignmentName else { return .natural } diff --git a/native-views/react-native-native-list/ios/NativeListTextLabel.swift b/native-views/react-native-native-list/ios/NativeListTextLabel.swift index ee982e3de..53f01619a 100644 --- a/native-views/react-native-native-list/ios/NativeListTextLabel.swift +++ b/native-views/react-native-native-list/ios/NativeListTextLabel.swift @@ -3,6 +3,112 @@ import UIKit class NativeListTextLabel: UILabel { var rowVerticalAlignment: String? { didSet { setNeedsDisplay() } } var rowOffsetY: CGFloat = 0 { didSet { setNeedsDisplay() } } + /// UTF-16 offset the touchable text starts at. `nil` keeps the label's own + /// hit testing, its whole bounds. With an offset only the drawn text from + /// there on takes touches, plus a small slop, so text before the offset and + /// the unused width of a stretched label fall through to the row behind it: + /// `0` covers all of the text, the text length leaves nothing to touch. + var touchableTextStart: Int? + private static let touchSlop = CGSize(width: 8, height: 6) + + /// One rect per laid-out run of touchable text, in label coordinates. The + /// label's own layout is not public, so the runs come from a text container + /// with the label's width, line cap and truncation. A line holds one run, or + /// several where mixed-direction text puts plain text between touchable text. + var touchableTextRegions: [CGRect] { + guard let start = touchableTextStart, let attributed = attributedText, attributed.length > start, + bounds.width > 0 + else { return [] } + let storage = NSTextStorage(attributedString: attributed) + let manager = NSLayoutManager() + let container = NSTextContainer( + size: CGSize(width: bounds.width, height: .greatestFiniteMagnitude)) + container.lineFragmentPadding = 0 + container.maximumNumberOfLines = numberOfLines + container.lineBreakMode = lineBreakMode + manager.addTextContainer(container) + storage.addLayoutManager(manager) + let glyphs = manager.glyphRange(for: container) + // Mirrors drawText: the text is centered unless the row aligns it. + let textHeight = manager.usedRect(for: container).height + var originY = (bounds.height - textHeight) / 2 + if let alignment = rowVerticalAlignment { + originY = alignment == "top" ? 0 : alignment == "bottom" ? bounds.height - textHeight : originY + } + originY += rowOffsetY + var lines: [CGRect] = [] + var visibleEnd = attributed.length + manager.enumerateLineFragments(forGlyphRange: glyphs) { _, usedRect, _, lineGlyphs, _ in + lines.append(usedRect) + let truncated = manager.truncatedGlyphRange(inLineFragmentForGlyphAt: lineGlyphs.location) + if truncated.location != NSNotFound { + visibleEnd = min(visibleEnd, manager.characterIndexForGlyph(at: truncated.location)) + } + } + // Truncation can hide the touchable text altogether. The ellipsis then + // stands for plain text as well, so nothing is left to touch. + guard start < visibleEnd else { return [] } + // The layout engine's own rects for a character range: one per line and + // per visual run, which is what makes mixed-direction text come out right. + func runs(_ characters: NSRange) -> [CGRect] { + let range = NSIntersectionRange( + manager.glyphRange(forCharacterRange: characters, actualCharacterRange: nil), glyphs) + guard range.length > 0 else { return [] } + var rects: [CGRect] = [] + manager.enumerateEnclosingRects( + forGlyphRange: range, withinSelectedGlyphRange: NSRange(location: NSNotFound, length: 0), + in: container + ) { rect, _ in + // A run that continues on the next line is reported up to the + // container edge; its text ends where the line's used rect does. + guard let used = lines.first(where: { $0.minY <= rect.midY && rect.midY < $0.maxY }) + else { return } + let minX = max(rect.minX, used.minX) + let maxX = min(rect.maxX, used.maxX) + if maxX > minX { + rects.append(CGRect(x: minX, y: rect.minY, width: maxX - minX, height: rect.height)) + } + } + return rects + } + let plain = runs(NSRange(location: 0, length: start)) + return runs(NSRange(location: start, length: attributed.length - start)).map { run in + // The slop reaches into blank space only. Sideways it stops at plain + // text on the same line, so text before the start never takes the + // touch, however narrow it is. + var minX = run.minX - Self.touchSlop.width + var maxX = run.maxX + Self.touchSlop.width + for other in plain where other.minY < run.midY && run.midY < other.maxY { + if other.maxX <= run.minX + 0.5 { minX = max(minX, other.maxX) } + if other.minX >= run.maxX - 0.5 { maxX = min(maxX, other.minX) } + } + // Vertically it grows only past the first and last line of the whole + // layout, so it never reaches into another line. + let line = lines.firstIndex { $0.minY <= run.midY && run.midY < $0.maxY } + let top = line == 0 ? Self.touchSlop.height : 0 + let bottom = line == lines.count - 1 ? Self.touchSlop.height : 0 + return CGRect( + x: minX, y: run.minY + originY - top, width: maxX - minX, + height: run.height + top + bottom) + } + } + + override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { + guard touchableTextStart != nil else { return super.point(inside: point, with: event) } + return touchableTextRegions.contains { $0.contains(point) } + } + + // Assistive activation taps this point; the label's center can be blank. + override var accessibilityActivationPoint: CGPoint { + get { + guard let region = touchableTextRegions.first else { + return super.accessibilityActivationPoint + } + let target = UIAccessibility.convertToScreenCoordinates(region.intersection(bounds), in: self) + return CGPoint(x: target.midX, y: target.midY) + } + set { super.accessibilityActivationPoint = newValue } + } override func drawText(in rect: CGRect) { var target = rect diff --git a/native-views/react-native-native-list/ios/tests/NativeListActivityPresentationTests.swift b/native-views/react-native-native-list/ios/tests/NativeListActivityPresentationTests.swift index 5c4417a62..9cbcc5b98 100644 --- a/native-views/react-native-native-list/ios/tests/NativeListActivityPresentationTests.swift +++ b/native-views/react-native-native-list/ios/tests/NativeListActivityPresentationTests.swift @@ -60,6 +60,276 @@ final class NativeListActivityPresentationTests: XCTestCase { } } + // The description label spans the identity column, so a tap anywhere on its + // line used to open the description action. Only the action text opens it + // now; the blank rest of the line belongs to the row press (OK-67219). Where + // that text starts is the caller's `descriptionActionStart`, never something + // read out of the string. + func testDescriptionActionTakesTouchesOnItsTextOnly() throws { + let details = NativeListActivityDetailsView() + // Wide enough that the label keeps blank space beside its text even when + // the amounts take their full half of the row. + let container = UIView(frame: CGRect(x: 0, y: 0, width: 600, height: 300)) + details.translatesAutoresizingMaskIntoConstraints = false + container.addSubview(details) + NSLayoutConstraint.activate([ + details.leadingAnchor.constraint(equalTo: container.leadingAnchor), + details.trailingAnchor.constraint(equalTo: container.trailingAnchor), + details.topAnchor.constraint(equalTo: container.topAnchor), + ]) + func bind(description: String, actionKey: String?, actionStart: Int? = nil) throws -> NativeListTextLabel { + var data: [String: Any] = [ + "type": "activity", "key": "tx", "title": "Swap", "description": description, + "leading": ["kind": "icon", "name": "ArrowTopOutline"], + "amounts": [["key": "send", "text": "-1"]], + ] + if let actionKey { data["descriptionActionKey"] = actionKey } + if let actionStart { data["descriptionActionStart"] = actionStart } + details.bind(try NativeListItem(data: data), theme: nil, fonts: NativeListFontFamilies()) + container.layoutIfNeeded() + func find(_ view: UIView) -> NativeListTextLabel? { + if let label = view as? NativeListTextLabel, label.text == description { return label } + return view.subviews.lazy.compactMap(find).first + } + return try XCTUnwrap(find(details)) + } + func hit(_ label: NativeListTextLabel, x: CGFloat) -> Bool { + label.point(inside: CGPoint(x: x, y: label.bounds.midY), with: nil) + } + + // Without a start the whole text is the action, also a label holding the + // separator a time prefix would use. + let label = try bind(description: "Router • V2", actionKey: "address-info") + let labelText = try XCTUnwrap(label.touchableTextRegions.first) + XCTAssertEqual(label.touchableTextStart, 0) + XCTAssertEqual(label.touchableTextRegions.count, 1) + XCTAssertGreaterThan(label.bounds.width, labelText.maxX + 40) + XCTAssertTrue(hit(label, x: 4)) + XCTAssertTrue(hit(label, x: labelText.maxX - 12)) + XCTAssertFalse(hit(label, x: label.bounds.maxX - 4)) + + // With a start only the text from there on is the action: the time is + // not, the complete label behind it is. + let prefix = "08:48 • " + let timed = try bind( + description: prefix + "Router • V2", actionKey: "address-info", + actionStart: (prefix as NSString).length) + let timedText = try XCTUnwrap(timed.touchableTextRegions.first) + XCTAssertEqual(timed.touchableTextRegions.count, 1) + XCTAssertGreaterThan(timed.bounds.width, timedText.maxX + 40) + // The same label, less the slop on the side where the time is. + XCTAssertEqual(timedText.width, labelText.width - 8, accuracy: 1) + XCTAssertFalse(hit(timed, x: 4)) + XCTAssertFalse(hit(timed, x: timedText.minX - 2)) + XCTAssertTrue(hit(timed, x: timedText.minX + 2)) + XCTAssertTrue(hit(timed, x: timedText.maxX - 12)) + XCTAssertFalse(hit(timed, x: timed.bounds.maxX - 4)) + + // The start counts UTF-16 units: the emoji takes two. + let emojiPrefix = "🕘 08:48 • " + XCTAssertEqual((emojiPrefix as NSString).length, 11) + let emoji = try bind( + description: emojiPrefix + "Router • V2", actionKey: "address-info", actionStart: 11) + let emojiText = try XCTUnwrap(emoji.touchableTextRegions.first) + XCTAssertEqual(emojiText.width, labelText.width - 8, accuracy: 1) + XCTAssertFalse(hit(emoji, x: 4)) + XCTAssertFalse(hit(emoji, x: emojiText.minX - 2)) + XCTAssertTrue(hit(emoji, x: emojiText.minX + 2)) + XCTAssertTrue(hit(emoji, x: emojiText.maxX - 12)) + + // A start at the end of the text, or clamped to it, leaves nothing to tap. + // 4294967296 is a safe integer past 32 bits; it must clamp, not wrap to 0. + for start in [(prefix as NSString).length, 99, 4_294_967_296] { + let ended = try bind(description: prefix, actionKey: "address-info", actionStart: start) + XCTAssertTrue(ended.touchableTextRegions.isEmpty) + XCTAssertFalse(ended.isUserInteractionEnabled) + XCTAssertFalse(hit(ended, x: 4)) + } + + // The reused view keeps no state: a rebind without a start covers the + // whole text again, one without the action restores the label's own hit + // testing even when a start is still supplied, and so does recycling. + let rebound = try bind(description: "Router • V2", actionKey: "address-info") + XCTAssertEqual(rebound.touchableTextStart, 0) + XCTAssertTrue(rebound.isUserInteractionEnabled) + XCTAssertTrue(hit(rebound, x: 4)) + let plain = try bind(description: "Router • V2", actionKey: nil, actionStart: 3) + XCTAssertNil(plain.touchableTextStart) + XCTAssertFalse(plain.isUserInteractionEnabled) + XCTAssertTrue(hit(plain, x: plain.bounds.maxX - 4)) + let recycled = try bind( + description: prefix + "Router", actionKey: "address-info", + actionStart: (prefix as NSString).length) + XCTAssertEqual(recycled.touchableTextStart, (prefix as NSString).length) + details.recycle() + XCTAssertNil(recycled.touchableTextStart) + } + + // A narrow column wraps "time • address". The time stays outside the action + // on its line, while the address is hit on both lines, also at the x the + // time occupies one line above. The label is sized directly so the wrap does + // not depend on how the row shares its width. + func testWrappedDescriptionKeepsTheTimeOutsideTheAction() throws { + let description = "08:48 • Uniswap Router" + let label = NativeListTextLabel() + NativeListResolvedText( + description, style: nil, size: 14, color: .label, lineHeight: 20, lines: 2, + fonts: NativeListFontFamilies() + ).bind(label) + label.frame = CGRect(x: 0, y: 0, width: 142, height: 40) + label.touchableTextStart = ("08:48 • " as NSString).length + func hit(_ x: CGFloat, _ y: CGFloat) -> Bool { + label.point(inside: CGPoint(x: x, y: y), with: nil) + } + + let lines = label.touchableTextRegions + XCTAssertEqual(lines.count, 2) + guard lines.count == 2 else { return } + XCTAssertFalse(hit(4, lines[0].midY)) + XCTAssertTrue(hit(lines[0].maxX - 12, lines[0].midY)) + XCTAssertTrue(hit(4, lines[1].midY)) + XCTAssertFalse(hit(label.bounds.maxX - 2, lines[1].midY)) + } + + // The first line holds only the time, so it takes no touches, and the slop + // of the address line below it must not reach up into the time. + func testAddressStartingOnTheSecondLineLeavesTheTimeLineAlone() throws { + let prefix = "08:48 • " + let address = "UniswapUniversalRouter" + func text(_ value: String) -> NativeListResolvedText { + NativeListResolvedText( + value, style: nil, size: 14, color: .label, lineHeight: 20, lines: 2, + fonts: NativeListFontFamilies()) + } + let label = NativeListTextLabel() + text(prefix + address).bind(label) + // Wide enough for the address alone, too narrow for the time beside it. + label.frame = CGRect(x: 0, y: 0, width: text(address).measureWidth() + 4, height: 40) + label.touchableTextStart = (prefix as NSString).length + func hit(y: CGFloat) -> Bool { label.point(inside: CGPoint(x: 4, y: y), with: nil) } + + let line = try XCTUnwrap(label.touchableTextRegions.first) + XCTAssertEqual(label.touchableTextRegions.count, 1) + XCTAssertEqual(line.minY, 20, accuracy: 0.5) + XCTAssertFalse(hit(y: 10)) + XCTAssertFalse(hit(y: line.minY - 2)) + XCTAssertTrue(hit(y: line.minY + 2)) + // The last line of the layout still takes its slop below the text. + XCTAssertTrue(hit(y: label.bounds.maxY + 4)) + } + + private func descriptionText(_ value: String, style: [String: Any]? = nil) -> NativeListResolvedText { + NativeListResolvedText( + value, style: style, size: 14, color: .label, lineHeight: 20, lines: 1, + fonts: NativeListFontFamilies()) + } + + /// Width the description font gives `value` on its own. + private func descriptionWidth(_ value: String) -> CGFloat { + descriptionText(value).attributed(direction: .leftToRight).size().width + } + + private func descriptionLabel( + _ value: String, start: Int, width: CGFloat = 300, style: [String: Any]? = nil + ) -> NativeListTextLabel { + let label = NativeListTextLabel() + descriptionText(value, style: style).bind(label) + label.frame = CGRect(x: 0, y: 0, width: width, height: 20) + label.touchableTextStart = start + return label + } + + private func hit(_ label: NativeListTextLabel, x: CGFloat) -> Bool { + label.point(inside: CGPoint(x: x, y: label.bounds.midY), with: nil) + } + + // The slop is for blank space. It stops at plain text beside the action + // text, or a prefix narrower than the slop, like the "i" of "iRouter", would + // open an action it is not part of. + func testSlopStopsAtPlainTextBesideTheActionText() throws { + let short = descriptionLabel("iRouter", start: 1) + let i = descriptionWidth("i") + XCTAssertLessThan(i, 8) + let region = try XCTUnwrap(short.touchableTextRegions.first) + XCTAssertEqual(short.touchableTextRegions.count, 1) + XCTAssertEqual(region.minX, i, accuracy: 0.5) + XCTAssertFalse(hit(short, x: i / 2)) + XCTAssertFalse(hit(short, x: -3)) + XCTAssertTrue(hit(short, x: i + 2)) + // Into the blank after the text the slop still reaches. + XCTAssertTrue(hit(short, x: descriptionWidth("iRouter") + 6)) + XCTAssertFalse(hit(short, x: descriptionWidth("iRouter") + 10)) + // And into the blank before a line that starts with the action text. + XCTAssertTrue(hit(descriptionLabel("Router", start: 0), x: -6)) + } + + // Mixed-direction text can split one logical suffix into several visual + // runs. From offset 6 of "ABC אבג XYZ" the suffix is the last Hebrew letter + // and " XYZ"; the Hebrew run is drawn right to left, so that letter sits + // left of the two plain ones. Each run is its own region and the plain text + // between them takes no touches. + func testMixedDirectionSuffixFollowsTheLaidOutRuns() { + let label = descriptionLabel("ABC \u{05D0}\u{05D1}\u{05D2} XYZ", start: 6) + let abc = descriptionWidth("ABC ") + let last = descriptionWidth("\u{05D2}") + let plain = descriptionWidth("\u{05D1}\u{05D0}") + let xyz = descriptionWidth(" XYZ") + let regions = label.touchableTextRegions.sorted { $0.minX < $1.minX } + XCTAssertEqual(regions.count, 2) + guard regions.count == 2 else { return } + XCTAssertEqual(regions[0].minX, abc, accuracy: 1) + XCTAssertEqual(regions[0].maxX, abc + last, accuracy: 1) + XCTAssertEqual(regions[1].minX, abc + last + plain, accuracy: 1) + XCTAssertFalse(hit(label, x: abc / 2)) + XCTAssertTrue(hit(label, x: abc + last / 2)) + XCTAssertFalse(hit(label, x: abc + last + plain / 2)) + XCTAssertTrue(hit(label, x: abc + last + plain + xyz / 2)) + // Only the outer edge of the last run faces blank space. + XCTAssertTrue(hit(label, x: abc + last + plain + xyz + 5)) + } + + // A one-line description that does not fit ends in an ellipsis. Action text + // it only shortens stays touchable up to and including the ellipsis. Once it + // hides the action text altogether the ellipsis also stands for plain text, + // and nothing is left to touch. + func testTruncationCanHideTheActionText() throws { + let cut = descriptionLabel( + "08:48 • UniswapUniversalRouterWithAVeryLongName", start: 8, width: 150, + style: ["lines": 1]) + let region = try XCTUnwrap(cut.touchableTextRegions.first) + XCTAssertEqual(cut.touchableTextRegions.count, 1) + XCTAssertEqual(region.minX, descriptionWidth("08:48 • "), accuracy: 1) + XCTAssertFalse(hit(cut, x: 20)) + XCTAssertTrue(hit(cut, x: 100)) + XCTAssertTrue(hit(cut, x: 145)) + + let prefix = "A very long plain prefix that fills the row • " + let hidden = descriptionLabel( + prefix + "Router", start: (prefix as NSString).length, width: 150, style: ["lines": 1]) + XCTAssertTrue(hidden.touchableTextRegions.isEmpty) + XCTAssertFalse(hit(hidden, x: 145)) + } + + // A one-line description folds each line break into one space, so the + // caller's offset is mapped onto the displayed text and kept inside it. + func testDescriptionActionStartFollowsTheDisplayedText() { + let source = "08:48\r\n• Router" + func text(_ style: [String: Any]?) -> NativeListResolvedText { + NativeListResolvedText( + source, style: style, size: 14, color: .label, lineHeight: 20, lines: 2, + fonts: NativeListFontFamilies()) + } + let oneLine = text(["lines": 1]) + XCTAssertEqual(oneLine.text, "08:48 • Router") + XCTAssertEqual(oneLine.displayOffset(9, in: source), 8) + XCTAssertEqual(oneLine.displayOffset(-3, in: source), 0) + XCTAssertEqual(oneLine.displayOffset(99, in: source), 14) + let wrapping = text(nil) + XCTAssertEqual(wrapping.text, source) + XCTAssertEqual(wrapping.displayOffset(9, in: source), 9) + XCTAssertEqual(wrapping.displayOffset(99, in: source), 15) + } + func testSmallNumberRunsPreserveBaselineAcrossAmountsFiatAndFee() throws { func segments(_ prefix: String, _ suffix: String) -> [[String: Any]] { [["text": prefix], ["text": "5", "style": "subscript"], ["text": suffix]] diff --git a/native-views/react-native-native-list/native-tests/android/NativeListDescriptionActionTouchTest.kt b/native-views/react-native-native-list/native-tests/android/NativeListDescriptionActionTouchTest.kt new file mode 100644 index 000000000..314ccad8d --- /dev/null +++ b/native-views/react-native-native-list/native-tests/android/NativeListDescriptionActionTouchTest.kt @@ -0,0 +1,249 @@ +package com.margelo.nitro.nativelist + +import android.app.Activity +import android.content.Intent +import android.os.SystemClock +import android.test.InstrumentationTestCase +import android.view.MotionEvent +import android.view.View +import androidx.recyclerview.widget.RecyclerView +import com.facebook.react.bridge.BridgeReactContext +import com.facebook.react.soloader.OpenSourceMergedSoMapping +import com.facebook.react.uimanager.ThemedReactContext +import com.facebook.soloader.SoLoader +import com.margelo.nitro.nativelogger.OneKeyLog +import org.json.JSONArray +import org.json.JSONObject + +/** + * Real pointer dispatch for the Activity description action. Its text, from + * `descriptionActionStart` on, opens the action; the text before it and the + * unused width of the description line reach the row press. + */ +@Suppress("DEPRECATION") +class NativeListDescriptionActionTouchTest : InstrumentationTestCase() { + private lateinit var activity: Activity + private lateinit var list: NativeListView + private lateinit var recycler: RecyclerView + private val events = mutableListOf() + private var generation = 0 + + override fun setUp() { + super.setUp() + activity = instrumentation.startActivitySync( + Intent(instrumentation.context, NativeListReorderTestActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + ) + onMain { + SoLoader.init(activity, OpenSourceMergedSoMapping) + OneKeyLog.init(activity) + val context = ThemedReactContext(BridgeReactContext(activity), activity, "DescriptionActionTest", 1) + list = NativeListView(context) + list.onRowAction = { events.add(JSONObject(it)) } + activity.setContentView(list) + recycler = field(list, "recyclerView") + } + } + + override fun tearDown() { + onMain { + activity.setContentView(View(activity)) + list.dispose() + activity.finish() + } + super.tearDown() + } + + fun testWholeTextOpensTheActionWithoutAStart() { + // A label holding the separator a time prefix would use is one action. + val description = bind("Router • V2", "address-info") + val text = textRegion(description) + assertEquals(0, onMainValue { description.touchableTextStart }) + assertEquals(listOf("address-info:description"), tap(description, text.left + slop() + dp(4))) + assertEquals(listOf("address-info:description"), tap(description, text.right - slop() - dp(4))) + assertEquals(listOf("press"), tap(description, blankX(description, text))) + } + + fun testTextBeforeTheStartReachesTheRowPress() { + val prefix = "08:48 • " + val description = bind("${prefix}Router • V2", "address-info", prefix.length) + val text = textRegion(description) + assertTrue(text.left > dp(20)) + assertEquals(listOf("press"), tap(description, dp(4))) + assertEquals(listOf("address-info:description"), tap(description, text.left + dp(4))) + assertEquals(listOf("address-info:description"), tap(description, text.right - slop() - dp(4))) + assertEquals(listOf("press"), tap(description, blankX(description, text))) + } + + fun testPlainTextRightBeforeTheStartReachesTheRowPress() { + // "i" is narrower than the touch slop, so a slop that reached towards it + // would let this one plain character open the action. + val description = bind("iRouter", "address-info", 1) + val i = textWidth(description, "i") + assertTrue(i < slop()) + assertEquals(i, textRegion(description).left, 1.5f) + assertEquals(listOf("press"), tap(description, i / 2)) + assertEquals(listOf("address-info:description"), tap(description, i + textWidth(description, "R") / 2)) + // The slop still reaches into the blank after the text. + assertEquals(listOf("address-info:description"), tap(description, textWidth(description, "iRouter") + slop() / 2)) + } + + fun testMixedDirectionSuffixFollowsTheLaidOutRuns() { + // The suffix from offset 6 is the last Hebrew letter and " XYZ". The Hebrew + // run is drawn right to left, so that letter sits left of the two plain + // ones and the suffix is two runs with plain text between them. + val description = bind("ABC \u05D0\u05D1\u05D2 XYZ", "address-info", 6) + val abc = textWidth(description, "ABC ") + val last = textWidth(description, "\u05D2") + val plain = textWidth(description, "\u05D1\u05D0") + val xyz = textWidth(description, " XYZ") + assertEquals(2, onMainValue { description.touchableTextRegions }.size) + assertEquals(listOf("press"), tap(description, abc / 2)) + assertEquals(listOf("address-info:description"), tap(description, abc + last / 2)) + assertEquals(listOf("press"), tap(description, abc + last + plain / 2)) + assertEquals(listOf("address-info:description"), tap(description, abc + last + plain + xyz / 2)) + } + + fun testStartCountsUtf16UnitsOfTheDescription() { + val prefix = "🕘 08:48 • " + assertEquals(11, prefix.length) + val description = bind("${prefix}Router • V2", "address-info", prefix.length) + val text = textRegion(description) + assertEquals(listOf("press"), tap(description, dp(4))) + assertEquals(listOf("address-info:description"), tap(description, text.left + dp(4))) + assertEquals(listOf("address-info:description"), tap(description, text.right - slop() - dp(4))) + } + + fun testStartAtTheEndLeavesNoAction() { + // 4294967296 is a safe integer past Int range: narrowed it would wrap to + // 0 and make the whole text the action instead of clamping to the end. + for (start in listOf("08:48 • ".length.toLong(), 99L, 4_294_967_296L)) { + val description = bind("08:48 • ", "address-info", start) + assertTrue(onMainValue { description.touchableTextRegions.isEmpty() }) + assertEquals(listOf("press"), tap(description, dp(4))) + } + } + + fun testRebindingAndRemovingTheActionLeavesNoStaleStart() { + val prefix = "08:48 • " + var description = bind("${prefix}Router • V2", "address-info", prefix.length) + assertEquals(listOf("press"), tap(description, dp(4))) + + // The same row without a start: the whole text again. + description = bind("${prefix}Router • V2", "address-info") + assertEquals(0, onMainValue { description.touchableTextStart }) + assertEquals(listOf("address-info:description"), tap(description, dp(4))) + + // Without the action a start means nothing and every touch is the row's. + description = bind("${prefix}Router • V2", null, prefix.length) + assertNull(onMainValue { description.touchableTextStart }) + assertFalse(onMainValue { description.isClickable }) + assertEquals(listOf("press"), tap(description, dp(4))) + assertEquals(listOf("press"), tap(description, onMainValue { description.width } - dp(4))) + + description = bind("${prefix}Router • V2", "address-info", prefix.length) + assertEquals(prefix.length, onMainValue { description.touchableTextStart }) + onMain { field(holder().rowView, "details").recycle() } + assertNull(onMainValue { description.touchableTextStart }) + } + + private fun bind(description: String, actionKey: String?, actionStart: Number? = null): NativeListTextView { + val row = JSONObject().put("key", "tx").put("type", "activity").put("title", "Swap") + .put("description", description) + .put("leading", JSONObject().put("kind", "icon").put("name", "ArrowTopOutline")) + .put("amounts", JSONArray().put(JSONObject().put("key", "send").put("text", "-1"))) + actionKey?.let { row.put("descriptionActionKey", it) } + actionStart?.let { row.put("descriptionActionStart", it.toLong()) } + generation += 1 + val revision = generation + row.put("revision", revision) + onMain { + list.applySnapshot(JSONObject() + .put("schemaVersion", 1).put("generation", revision) + .put("layout", JSONObject().put("kind", "linear")) + .put("rows", JSONArray().put(row)).toString()) + } + repeat(100) { + val view = onMainValue { + val current = (recycler.findViewHolderForAdapterPosition(0) as? NativeListViewHolder)?.rowView + val item = current?.tag as? NativeListItem + if (current == null || recycler.isLayoutRequested || item?.json?.optInt("revision") != revision) null + else field(field(current, "details"), "description") + .takeIf { it.width > 0 && it.layout != null } + } + if (view != null) return view + SystemClock.sleep(50) + } + fail("Activity row did not bind: $description") + throw IllegalStateException() + } + + private fun holder(): NativeListViewHolder = + recycler.findViewHolderForAdapterPosition(0) as NativeListViewHolder + + /** The single touchable line of the bound description, in view coordinates and including the slop. */ + private fun textRegion(description: NativeListTextView): NativeListTouchRegion = + onMainValue { description.touchableTextRegions }.also { assertEquals(1, it.size) }.single() + + private fun textWidth(view: NativeListTextView, text: String): Float = + onMainValue { view.paint.measureText(text) } + + /** An x on the description line well clear of its text, inside the view. */ + private fun blankX(description: NativeListTextView, text: NativeListTouchRegion): Float { + val width = onMainValue { description.width } + assertTrue("the description needs blank width beside its text", width > text.right + dp(40)) + return width - dp(4) + } + + /** Taps the view at view-local [x] through the window; returns `actionKey[:source]` of each emitted action. */ + private fun tap(view: View, x: Float): List { + events.clear() + val point = onMainValue { + val location = IntArray(2) + view.getLocationOnScreen(location) + Pair(location[0] + x, location[1] + view.height / 2f) + } + val downTime = SystemClock.uptimeMillis() + instrumentation.sendPointerSync(MotionEvent.obtain( + downTime, downTime, MotionEvent.ACTION_DOWN, point.first, point.second, 0)) + instrumentation.sendPointerSync(MotionEvent.obtain( + downTime, SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, point.first, point.second, 0)) + instrumentation.waitForIdleSync() + return events.map { event -> + val source = event.optJSONObject("anchor")?.optString("source").orEmpty() + event.getString("actionKey") + if (source == "description") ":description" else "" + } + } + + private fun dp(value: Int): Float = value * activity.resources.displayMetrics.density + + private fun slop(): Float = dp(8) + + private fun onMain(block: () -> Unit) { + var failure: Throwable? = null + instrumentation.runOnMainSync { + try { block() } catch (error: Throwable) { failure = error } + } + failure?.let { throw it } + } + + private fun onMainValue(block: () -> T): T { + var value: T? = null + onMain { value = block() } + @Suppress("UNCHECKED_CAST") + return value as T + } + + @Suppress("UNCHECKED_CAST") + private fun field(owner: Any, name: String): T { + var type: Class<*>? = owner.javaClass + while (type != null) { + try { + return type.getDeclaredField(name).apply { isAccessible = true }.get(owner) as T + } catch (_: NoSuchFieldException) { + type = type.superclass + } + } + error("Missing production field $name") + } +} diff --git a/native-views/react-native-native-list/native-tests/android/README.md b/native-views/react-native-native-list/native-tests/android/README.md index 87d471bf7..40070d574 100644 --- a/native-views/react-native-native-list/native-tests/android/README.md +++ b/native-views/react-native-native-list/native-tests/android/README.md @@ -58,3 +58,19 @@ vertical drag, continued native scrolling, ordinary tap touch-end/click, ACTION_CANCEL cleanup, and removal/reattachment with the retained list and slot. It uses the existing platform runner without additional dependencies. It does not run JavaScript press handlers or establish physical-device gesture feel. + +## Activity description action hit area + +The same build command includes `NativeListDescriptionActionTouchTest`. Run it +with `-e class com.margelo.nitro.nativelist.NativeListDescriptionActionTouchTest` +and require `OK (7 tests)`. It binds rich Activity rows in a standalone +NativeListView and taps the description line with `sendPointerSync`, so the +events go through the window, the RecyclerView and the row. It checks that the +text from `descriptionActionStart` on emits the description action, that the +text before it and the blank width of the line emit the row press, also for a +one-character prefix narrower than the touch slop and for the plain text +between the two runs of a mixed-direction suffix. It covers UTF-16 offsets +behind an emoji prefix, a start at, past and far past the end (beyond Int +range), and that rebinding without a start, removing the action and recycling +leave no stale start. It does not run JavaScript validation or present the +caller's sheet. diff --git a/native-views/react-native-native-list/src/__tests__/NativeList.web.test.ts b/native-views/react-native-native-list/src/__tests__/NativeList.web.test.ts index 7aefaae33..4af72c0e8 100644 --- a/native-views/react-native-native-list/src/__tests__/NativeList.web.test.ts +++ b/native-views/react-native-native-list/src/__tests__/NativeList.web.test.ts @@ -1818,6 +1818,134 @@ describe('web row style', () => { } }); + it('takes the Activity description action text from descriptionActionStart, never from the string', () => { + const { document } = new JSDOM('').window; + const host = document.createElement('div'); + document.body.appendChild(host); + const row: ActivityRow = { + type: 'activity', + key: 'tx', + leading: { kind: 'image', image }, + title: 'Send', + amounts: [{ key: 'send', text: '-1 ETH' }], + description: 'Router • V2', + descriptionActionKey: 'address-info', + }; + const engine = new NativeListWebEngine( + host, + snapshot({ kind: 'sectioned' }, [row]), + {}, + false + ); + const body = host.querySelector( + '[data-nl-renderer="activity"]' + )!; + const description = () => + body.querySelector('[data-nl-slot="description"]')!; + const action = () => + description().querySelector('[data-native-list-action]'); + const bind = (changes: Partial) => + engine.applySnapshot( + snapshot({ kind: 'sectioned' }, [{ ...row, ...changes }]) + ); + try { + // A label holding the separator a time prefix would use is one action. + expect(action()?.dataset.nativeListAction).toBe('address-info'); + expect(action()?.textContent).toBe('Router • V2'); + expect(description().textContent).toBe('Router • V2'); + + bind({ description: '08:48 • Router • V2', descriptionActionStart: 8 }); + expect(action()?.textContent).toBe('Router • V2'); + expect(description().textContent).toBe('08:48 • Router • V2'); + + // UTF-16 units: the emoji counts two. + const prefix = '🕘 08:48 • '; + bind({ + description: `${prefix}Router`, + descriptionActionStart: prefix.length, + }); + expect(action()?.textContent).toBe('Router'); + expect(description().textContent).toBe(`${prefix}Router`); + + // A start at the end leaves no action text. + bind({ description: '08:48 • ', descriptionActionStart: 8 }); + expect(action()).toBeNull(); + expect(description().textContent).toBe('08:48 • '); + + // Without the key the offset splits nothing. + bind({ + description: '08:48 • Router', + descriptionActionStart: 8, + descriptionActionKey: undefined, + }); + expect(action()).toBeNull(); + expect(description().textContent).toBe('08:48 • Router'); + + bind({}); + expect(action()?.textContent).toBe('Router • V2'); + } finally { + engine.destroy(); + } + }); + + it('keeps room for the Activity description action behind a prefix wider than the row', () => { + const { document } = new JSDOM('').window; + const host = document.createElement('div'); + Object.defineProperty(host, 'clientWidth', { value: 160 }); + document.body.appendChild(host); + const prefix = 'Received from a very long counterparty name • '; + const row: ActivityRow = { + type: 'activity', + key: 'tx', + leading: { kind: 'image', image }, + title: 'Send', + amounts: [{ key: 'send', text: '-1 ETH' }], + description: `${prefix}Router`, + descriptionActionKey: 'address-info', + descriptionActionStart: prefix.length, + }; + const engine = new NativeListWebEngine( + host, + snapshot({ kind: 'sectioned' }, [row]), + {}, + false + ); + const description = host.querySelector( + '[data-nl-slot="description"]' + )!; + const [prefixNode, action] = Array.from( + description.children + ) as HTMLElement[]; + try { + expect(prefixNode!.textContent).toBe(prefix); + expect(action!.dataset.nativeListAction).toBe('address-info'); + // The prefix keeps its own width but can never take the whole line: it + // is capped short of the row and truncates, so the action after it + // cannot be squeezed to nothing. + expect(prefixNode!.style.flexShrink).toBe('0'); + expect(prefixNode!.style.maxWidth).toBe('calc(100% - 3em)'); + expect(prefixNode!.style.overflow).toBe('hidden'); + expect(prefixNode!.style.textOverflow).toBe('ellipsis'); + expect(action!.style.display).toBe('block'); + expect(action!.style.minWidth).toBe('0'); + + // Nothing is reserved when no action text follows the prefix. + engine.applySnapshot( + snapshot({ kind: 'sectioned' }, [ + { + ...row, + description: prefix, + descriptionActionStart: prefix.length, + }, + ]) + ); + expect(prefixNode!.style.maxWidth).toBe('100%'); + expect(action!.style.display).toBe('none'); + } finally { + engine.destroy(); + } + }); + it.each([false, true])( 'removes and restores the Activity leading slot on %s rich rows', (rich) => { diff --git a/native-views/react-native-native-list/src/__tests__/activityRich.test.ts b/native-views/react-native-native-list/src/__tests__/activityRich.test.ts index 393b5b844..7cd946699 100644 --- a/native-views/react-native-native-list/src/__tests__/activityRich.test.ts +++ b/native-views/react-native-native-list/src/__tests__/activityRich.test.ts @@ -1,5 +1,9 @@ import type { ActivityRow, NativeListSnapshot } from '../models'; -import { validatePatches, validateSnapshot } from '../validation'; +import { + applyOwnedNativePatches, + validatePatches, + validateSnapshot, +} from '../validation'; const row: ActivityRow = { type: 'activity', @@ -123,3 +127,136 @@ test('rich data fields are not style keys; activity accepts titleBadgeGap', () = }) ).toThrow(/is not a style key/); }); + +describe('descriptionActionStart', () => { + // The caller that assembles the description states where its action text + // starts. NativeList never reads that out of the displayed string. + const labelled: ActivityRow = { + ...row, + amounts: [{ key: 'send', text: '-1 ETH' }], + description: '08:48 • Router • V2', + descriptionActionKey: 'open-address', + }; + const patch = (changes: Record) => + [{ type: 'activity', key: row.key, changes }] as never; + + test('accepts an offset anywhere in the description, both ends included', () => { + for (const descriptionActionStart of [0, 8, labelled.description!.length]) + expect(() => + validateSnapshot(snapshot({ ...labelled, descriptionActionStart })) + ).not.toThrow(); + // UTF-16 code units, as `String.prototype.length` counts them. + const prefix = '🕘 08:48 • '; + expect(prefix.length).toBe(11); + expect(() => + validateSnapshot( + snapshot({ + ...labelled, + description: `${prefix}Router`, + descriptionActionStart: prefix.length, + }) + ) + ).not.toThrow(); + }); + + test('rejects an offset that is not an integer inside the description', () => { + for (const descriptionActionStart of [ + -1, + 1.5, + '8', + labelled.description!.length + 1, + ]) + expect(() => + validateSnapshot( + snapshot({ ...labelled, descriptionActionStart } as ActivityRow) + ) + ).toThrow(/descriptionActionStart/); + // Without a description there is nothing to offset into. + expect(() => + validateSnapshot(snapshot({ ...row, descriptionActionStart: 1 })) + ).toThrow(/descriptionActionStart/); + expect(() => + validatePatches(patch({ descriptionActionStart: -1 })) + ).toThrow(/descriptionActionStart/); + }); + + test('a patch that replaces the description resets an offset it does not restate', () => { + const initial = snapshot({ ...labelled, descriptionActionStart: 8 }); + const renamed = applyOwnedNativePatches( + initial, + patch({ description: 'Router • V2' }) + ); + expect(renamed.snapshot.rows[0]).toMatchObject({ + description: 'Router • V2', + }); + expect(renamed.snapshot.rows[0]).not.toHaveProperty( + 'descriptionActionStart' + ); + expect(JSON.parse(renamed.json)[0].changes).toEqual({ + description: 'Router • V2', + descriptionActionStart: null, + }); + + const restated = applyOwnedNativePatches( + initial, + patch({ description: '09:10 • Router', descriptionActionStart: 8 }) + ); + expect(restated.snapshot.rows[0]).toMatchObject({ + description: '09:10 • Router', + descriptionActionStart: 8, + }); + + // The same string again, or a patch of other fields, keeps the offset. + const untouched = applyOwnedNativePatches( + initial, + patch({ description: labelled.description, title: 'Swap' }) + ); + expect(untouched.snapshot.rows[0]).toMatchObject({ + title: 'Swap', + descriptionActionStart: 8, + }); + expect(JSON.parse(untouched.json)[0].changes).not.toHaveProperty( + 'descriptionActionStart' + ); + + // Clearing the description clears the offset with it. + const cleared = applyOwnedNativePatches( + initial, + patch({ description: null }) + ); + expect(cleared.snapshot.rows[0]).not.toHaveProperty('description'); + expect(cleared.snapshot.rows[0]).not.toHaveProperty( + 'descriptionActionStart' + ); + + // The merged row is checked: this offset is past the current description. + expect(() => + applyOwnedNativePatches(initial, patch({ descriptionActionStart: 40 })) + ).toThrow(/descriptionActionStart/); + }); + + test('production ignores a malformed offset instead of forwarding it', () => { + const environment = globalThis as typeof globalThis & { __DEV__: boolean }; + const original = environment.__DEV__; + environment.__DEV__ = false; + try { + for (const descriptionActionStart of [-1, 1.5, '8']) { + const [accepted] = validateSnapshot( + snapshot({ ...labelled, descriptionActionStart } as ActivityRow) + ).rows; + expect(accepted).toMatchObject({ description: labelled.description }); + expect(accepted).not.toHaveProperty('descriptionActionStart'); + } + expect( + validateSnapshot(snapshot({ ...labelled, descriptionActionStart: 8 })) + .rows[0] + ).toMatchObject({ descriptionActionStart: 8 }); + expect( + validatePatches(patch({ title: 'Swap', descriptionActionStart: -1 }))[0] + ?.changes + ).toEqual({ title: 'Swap' }); + } finally { + environment.__DEV__ = original; + } + }); +}); diff --git a/native-views/react-native-native-list/src/models.ts b/native-views/react-native-native-list/src/models.ts index 9ac00b54f..9b49adef8 100644 --- a/native-views/react-native-native-list/src/models.ts +++ b/native-views/react-native-native-list/src/models.ts @@ -616,6 +616,14 @@ export type ActivityRow = RowBase & hidden?: boolean; }>; descriptionActionKey?: string; + /** + * UTF-16 offset into `description` where the text that opens + * `descriptionActionKey` starts; the text before it stays plain. An integer + * in `0...description.length`: `0`, the default, makes the whole + * description the action and `description.length` leaves no action text. + * Ignored without `descriptionActionKey`. + */ + descriptionActionStart?: number; footerActions?: readonly FooterAction[]; style?: ActivityRowStyle; }>; @@ -1131,6 +1139,7 @@ export type RowPatch = | 'presentation' | 'fee' | 'descriptionActionKey' + | 'descriptionActionStart' | 'primaryAmount' | 'secondaryAmount' | 'leading' diff --git a/native-views/react-native-native-list/src/validation.ts b/native-views/react-native-native-list/src/validation.ts index 7e29386d3..bb6f101db 100644 --- a/native-views/react-native-native-list/src/validation.ts +++ b/native-views/react-native-native-list/src/validation.ts @@ -1621,6 +1621,11 @@ function assertVisual(row: RowModel, path: string): void { }); } +/** The type half of the `descriptionActionStart` contract; the range needs the row. */ +function isDescriptionActionStart(value: unknown): value is number { + return Number.isSafeInteger(value) && (value as number) >= 0; +} + function assertActivity(row: Partial, path: string): void { if (row.hideLeading !== undefined && typeof row.hideLeading !== 'boolean') fail(`${path}.hideLeading`, 'must be boolean'); @@ -1633,6 +1638,11 @@ function assertActivity(row: Partial, path: string): void { fail(`${path}.presentation`, 'must be stacked or table'); if (row.descriptionActionKey !== undefined) assertKey(row.descriptionActionKey, `${path}.descriptionActionKey`); + if ( + row.descriptionActionStart !== undefined && + !isDescriptionActionStart(row.descriptionActionStart) + ) + fail(`${path}.descriptionActionStart`, 'must be a non-negative integer'); if ((row.amounts?.length ?? 0) > 32) fail(`${path}.amounts`, 'supports at most 32 amount lines'); const amountKeys = new Set(); @@ -1899,6 +1909,13 @@ function assertRow( break; case 'activity': assertActivity(row, path); + // Checked on the complete row only: a patch may carry the offset + // without the description it points into. + if ((row.descriptionActionStart ?? 0) > (row.description?.length ?? 0)) + fail( + `${path}.descriptionActionStart`, + 'must not exceed the description length' + ); break; case 'message': if ( @@ -2449,6 +2466,7 @@ const ROW_FIELDS: Readonly> = { 'presentation', 'fee', 'descriptionActionKey', + 'descriptionActionStart', 'footerActions', ], message: [ @@ -2616,6 +2634,7 @@ const PATCH_FIELDS: Readonly> = { 'amounts', 'fee', 'descriptionActionKey', + 'descriptionActionStart', 'footerActions', ], message: [ @@ -3931,6 +3950,11 @@ function sanitizeRowForProduction(row: RowModel): RowModel { delete next[field]; continue; } + if (field === 'descriptionActionStart') { + // Renderers clamp an offset past the text; anything else has no meaning. + if (!isDescriptionActionStart(value)) delete next[field]; + continue; + } if (field === 'parent' && isRecord(value)) next[field] = sanitizeRowForProduction(value as unknown as RowModel); else if (field === 'children' && Array.isArray(value)) @@ -4862,6 +4886,16 @@ function mergeAndValidateSingleRow( ) changes.subtitle = null; } + // The offset points into one specific description string, so a patch that + // replaces the description without restating it falls back to the default. + if ( + previous.type === 'activity' && + 'description' in changes && + changes.description !== previous.description && + !('descriptionActionStart' in changes) && + previous.descriptionActionStart !== undefined + ) + changes.descriptionActionStart = null; const merged = { ...previous } as unknown as Record; for (const [field, value] of Object.entries(changes)) { if (value === null) delete merged[field]; diff --git a/native-views/react-native-native-list/src/web/templates/ActivityRowRenderer.ts b/native-views/react-native-native-list/src/web/templates/ActivityRowRenderer.ts index 437b3b07c..3ab2c3971 100644 --- a/native-views/react-native-native-list/src/web/templates/ActivityRowRenderer.ts +++ b/native-views/react-native-native-list/src/web/templates/ActivityRowRenderer.ts @@ -168,9 +168,10 @@ type HistoryViews = { title: HTMLElement; badges: HTMLElement; description: HTMLElement; - descriptionTime: HTMLElement; - descriptionDot: HTMLElement; - descriptionAddress: HTMLButtonElement; + /** Description text before the action, or nothing. */ + descriptionPrefix: HTMLElement; + /** Description text that opens the action; the whole text without one. */ + descriptionAction: HTMLButtonElement; amounts: HTMLElement; amountRows: Map; fee: HTMLElement; @@ -196,6 +197,8 @@ const isHistory = (row: ActivityRow) => row.presentation !== undefined || row.amounts !== undefined; const ellipsis = 'min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;'; +/** Width a description prefix always leaves for the action text after it. */ +const descriptionActionReserve = '3em'; function valueText( node: HTMLElement, text: string | undefined, @@ -221,14 +224,13 @@ function createHistory(body: HTMLElement, primitives: RowPrimitives) { const badges = node('badges'); const description = node('description'); description.dataset.nlSlot = 'description'; - const descriptionTime = createElement(document, 'span'); - const descriptionDot = createElement(document, 'span', undefined, '•'); - const descriptionAddress = createElement( + const descriptionPrefix = createElement(document, 'span'); + const descriptionAction = createElement( document, 'button' ) as HTMLButtonElement; - descriptionAddress.type = 'button'; - description.append(descriptionTime, descriptionDot, descriptionAddress); + descriptionAction.type = 'button'; + description.append(descriptionPrefix, descriptionAction); const amounts = node('amounts'); const fee = node('fee'); const feeLabel = node('fee-label'); @@ -252,9 +254,8 @@ function createHistory(body: HTMLElement, primitives: RowPrimitives) { title, badges, description, - descriptionTime, - descriptionDot, - descriptionAddress, + descriptionPrefix, + descriptionAction, amounts, amountRows: new Map(), fee, @@ -579,29 +580,38 @@ function bindHistory( ellipsis + 'display:flex;max-width:100%;color:var(--nl-secondary);font-family:inherit;font-size:14px;line-height:20px;font-weight:400;font-variant-numeric:tabular-nums;'; applyTextWeight(v.description, 400); - const split = row.description?.indexOf(' • ') ?? -1; - v.descriptionTime.textContent = - split >= 0 ? row.description!.slice(0, split) : ''; - v.descriptionTime.style.display = split >= 0 ? 'inline' : 'none'; - v.descriptionTime.style.flexShrink = '0'; - v.descriptionDot.style.cssText = `flex-shrink:0;margin:0 4px;display:${ - split >= 0 ? 'inline' : 'none' - }`; - v.descriptionAddress.style.cssText = - ellipsis + - 'appearance:none;display:block;max-width:100%;border:0;padding:0;background:transparent;text-align:left;color:inherit;font:inherit;font-variant-numeric:inherit;'; - v.descriptionAddress.textContent = - split >= 0 ? row.description!.slice(split + 3) : row.description ?? ''; + // The caller states where the action text starts; the string is not parsed. + const description = row.description ?? ''; + const actionStart = row.descriptionActionKey + ? Math.min(Math.max(row.descriptionActionStart ?? 0, 0), description.length) + : 0; + const actionText = description.slice(actionStart); + const boundAction = + row.descriptionActionKey && actionText ? row.descriptionActionKey : ''; + // `pre` keeps the space a prefix ends with; a line break stays a space. + v.descriptionPrefix.textContent = description + .slice(0, actionStart) + .replace(/\r\n|[\r\n]/g, ' '); + // The prefix keeps its width and the action truncates first, as the tail of + // the one native label does. A prefix wider than the row is capped instead, + // or it would squeeze the action to nothing and leave no pointer target. + v.descriptionPrefix.style.cssText = `${ellipsis}flex-shrink:0;max-width:${ + actionText ? `calc(100% - ${descriptionActionReserve})` : '100%' + };white-space:pre;display:${actionStart > 0 ? 'block' : 'none'}`; + v.descriptionAction.style.cssText = `${ellipsis}appearance:none;max-width:100%;border:0;padding:0;background:transparent;text-align:left;color:inherit;font:inherit;font-variant-numeric:inherit;display:${ + actionText ? 'block' : 'none' + };`; + v.descriptionAction.textContent = actionText; v.description.style.display = row.description ? 'flex' : 'none'; - v.descriptionAddress.tabIndex = row.descriptionActionKey ? 0 : -1; - if (row.descriptionActionKey) { - v.descriptionAddress.dataset.nativeListAction = row.descriptionActionKey; - markActionAnchorSource(v.descriptionAddress, 'description'); - v.descriptionAddress.style.cursor = 'pointer'; + v.descriptionAction.tabIndex = boundAction ? 0 : -1; + if (boundAction) { + v.descriptionAction.dataset.nativeListAction = boundAction; + markActionAnchorSource(v.descriptionAction, 'description'); + v.descriptionAction.style.cursor = 'pointer'; } else { - delete v.descriptionAddress.dataset.nativeListAction; - delete v.descriptionAddress.dataset.nativeListAnchorSource; - v.descriptionAddress.style.cursor = 'inherit'; + delete v.descriptionAction.dataset.nativeListAction; + delete v.descriptionAction.dataset.nativeListAnchorSource; + v.descriptionAction.style.cursor = 'inherit'; } if (row.style?.description) primitives.textStyle(v.description, row.style.description); diff --git a/native-views/react-native-pager-view/docs/SPEC.md b/native-views/react-native-pager-view/docs/SPEC.md index 7f13af100..21ec1ef6b 100644 --- a/native-views/react-native-pager-view/docs/SPEC.md +++ b/native-views/react-native-pager-view/docs/SPEC.md @@ -1095,6 +1095,24 @@ Status: implemented and verified by production-native UIKit regressions on iOS 27.1 for footer insertion, explicit-sibling priority and nested-pager delegation. Full App and physical-device visual acceptance are reported separately. +A NativeOverlay host is a discovery boundary on iOS as well. Overlay content +(popover, sheet, dialog) stays mounted inside its host view until the overlay +window presents it, and the host can sit anywhere in a page's subtree, including +beside the page's NativeList. Scroll views inside a host belong to the overlay: +they MUST NOT be resolved as the page's vertical scroll owner or receive its +insets, logical offsets or shared header. Without this boundary a staged sheet's +Fabric scroll view outranks a NativeList sibling, takes the collapsed-header +offset, and the sheet opens scrolled past its content. The host is recognised by +its component class; discovery is unchanged when the overlay package is absent, +and a scroll view outside a host keeps its existing priority. Android owner +discovery is not changed by this boundary. + +Status: implemented on iOS. Verified in the OneKey app on an iPhone SE (3rd +generation) simulator, iOS 26.5: with the Home header collapsed, a popover opened +from the History list showed an empty body before this boundary and its content +from the first frame after it. A UIKit regression covers the boundary; Android +was not inspected beyond the absence of the symptom. + When the active scroll owner is removed before its replacement becomes usable, the pager MUST retain bounded recovery (at most 12 retries per recovery round, spaced 100 ms apart). Clearing the completed mount's reattachment flag MUST NOT diff --git a/native-views/react-native-pager-view/ios/RNCCollapsiblePagerViewComponentView.mm b/native-views/react-native-pager-view/ios/RNCCollapsiblePagerViewComponentView.mm index 6ca0f11c6..3051d15d2 100644 --- a/native-views/react-native-pager-view/ios/RNCCollapsiblePagerViewComponentView.mm +++ b/native-views/react-native-pager-view/ios/RNCCollapsiblePagerViewComponentView.mm @@ -207,6 +207,21 @@ @interface RNCCollapsiblePagerTransitionEdgeOwner : NSObject @implementation RNCCollapsiblePagerTransitionEdgeOwner @end +// OneKey patch: overlay content (popover, sheet, dialog) stays mounted inside +// its host view until the overlay window presents it, so a host can sit in a +// page's subtree. That content is never the page's scroller: adopting its +// scroll view applies the collapsed-header offset to it, and the sheet then +// opens scrolled past its content. +static BOOL RNCIsNativeOverlayHost(UIView *view) +{ + // Looked up by name: the overlay package is optional here. Main thread only. + static Class overlayHostClass = Nil; + if (overlayHostClass == Nil) { + overlayHostClass = NSClassFromString(@"RCTNativeOverlayComponentView"); + } + return overlayHostClass != Nil && [view isKindOfClass:overlayHostClass]; +} + static UIView *RNCScrollComponentView(UIScrollView *scrollView) { for (UIView *view = scrollView; view != nil; view = view.superview) { @@ -5090,7 +5105,7 @@ - (RNCScrollCandidateResolution)resolveScrollCandidateForPageAtIndex:(NSInteger) - (RNCScrollCandidateResolution)resolveScrollCandidateInView:(UIView *)view { RNCScrollCandidateResolution resolution; - if (view == nil || view == _sharedHeaderHostView) return resolution; + if (view == nil || view == _sharedHeaderHostView || RNCIsNativeOverlayHost(view)) return resolution; if (view != self && [view isKindOfClass:RNCCollapsiblePagerViewComponentView.class]) { UIScrollView *nested = [(RNCCollapsiblePagerViewComponentView *)view @@ -5181,7 +5196,7 @@ - (RNCScrollCandidateResolution)resolveScrollCandidateInView:(UIView *)view - (UIScrollView *)findExplicitNativeScrollerInView:(UIView *)view { - if (view == _sharedHeaderHostView) return nil; + if (view == _sharedHeaderHostView || RNCIsNativeOverlayHost(view)) return nil; if (view != self && [view isKindOfClass:RNCCollapsiblePagerViewComponentView.class]) { return [(RNCCollapsiblePagerViewComponentView *)view @@ -5208,7 +5223,7 @@ - (UIScrollView *)findExplicitNativeScrollerInView:(UIView *)view - (UIScrollView *)findFabricScrollViewInView:(UIView *)view { - if (view == _sharedHeaderHostView) return nil; + if (view == _sharedHeaderHostView || RNCIsNativeOverlayHost(view)) return nil; if (view != self && [view isKindOfClass:RNCCollapsiblePagerViewComponentView.class]) { return [(RNCCollapsiblePagerViewComponentView *)view @@ -5231,7 +5246,7 @@ - (UIScrollView *)findFabricScrollViewInView:(UIView *)view - (UIScrollView *)findVerticalScrollViewInView:(UIView *)view { - if (view == _sharedHeaderHostView || + if (view == _sharedHeaderHostView || RNCIsNativeOverlayHost(view) || ([view isKindOfClass:UIScrollView.class] && [_mountingRemovedScrollViews containsObject:(UIScrollView *)view])) return nil; // A parent pager must follow the nested pager's active page instead of the diff --git a/native-views/react-native-pager-view/ios/tests/RNCCollapsiblePagerFirstFrameTests.mm b/native-views/react-native-pager-view/ios/tests/RNCCollapsiblePagerFirstFrameTests.mm index 01ecc7cfd..b05270727 100644 --- a/native-views/react-native-pager-view/ios/tests/RNCCollapsiblePagerFirstFrameTests.mm +++ b/native-views/react-native-pager-view/ios/tests/RNCCollapsiblePagerFirstFrameTests.mm @@ -1,4 +1,5 @@ #import +#import #import "RNCCollapsiblePagerViewComponentView.h" #import "RNCNativeScrollerComponentView.h" #import @@ -1035,6 +1036,53 @@ MountingTransaction transaction(1, 2, XCTAssertEqualWithAccuracy(footerList.scrollView.contentInset.top, 0, 0.01); } +// Overlay content (popover, sheet) stays mounted inside its host view until +// the overlay window presents it, and the host can sit beside the page's list. +// As a Fabric scroll view its scroller outranks the native list, so the pager +// used to adopt it and apply the collapsed-header offset to it: the sheet then +// opened scrolled past its content (OK-67220). +- (void)testStagedOverlayScrollViewCannotReplacePageOwner +{ + RNCCollapsiblePagerViewComponentView *pager = [self pagerWithPageCount:1]; + RCTViewComponentView *component = [self addNativeListToPager:pager]; + UICollectionView *list = nil; + for (UIView *child in component.contentView.subviews) { + if ([child isKindOfClass:UICollectionView.class]) { + list = (UICollectionView *)child; + break; + } + } + XCTAssertNotNil(list); + XCTAssertEqual([pager verticalScrollViewForPageAtIndex:0], list); + + // The overlay package is not linked into this target; stand in for its host. + Class overlayHostClass = NSClassFromString(@"RCTNativeOverlayComponentView"); + if (overlayHostClass == Nil) { + overlayHostClass = objc_allocateClassPair(UIView.class, "RCTNativeOverlayComponentView", 0); + objc_registerClassPair(overlayHostClass); + } + UIView *overlayHost = [overlayHostClass new]; + RCTScrollViewComponentView *sheetScroller = [RCTScrollViewComponentView new]; + sheetScroller.frame = CGRectMake(0, 0, 320, 60); + sheetScroller.scrollView.frame = sheetScroller.bounds; + sheetScroller.scrollView.contentSize = CGSizeMake(320, 60); + sheetScroller.scrollView.alwaysBounceHorizontal = NO; + [overlayHost addSubview:sheetScroller]; + UIViewController *page = [pager valueForKey:@"pageControllers"][0]; + [page.view addSubview:overlayHost]; + + XCTAssertEqual([pager verticalScrollViewForPageAtIndex:0], list); + XCTAssertNil([pager findVerticalScrollViewInView:overlayHost]); + [pager attachScrollObserverForCurrentPage]; + XCTAssertEqual([pager valueForKey:@"observedScrollView"], list); + XCTAssertEqualWithAccuracy(sheetScroller.scrollView.contentOffset.y, 0, 0.01); + + // The same scroll view outside an overlay host is still a page scroller. + [sheetScroller removeFromSuperview]; + [page.view addSubview:sheetScroller]; + XCTAssertEqual([pager verticalScrollViewForPageAtIndex:0], sheetScroller.scrollView); +} + - (void)testExplicitScrollerSiblingStillPrecedesNativeList { RNCCollapsiblePagerViewComponentView *pager = [self pagerWithPageCount:1];