From 0a3406b48f25a4370047bec8705c781626823929 Mon Sep 17 00:00:00 2001 From: weatherstar Date: Fri, 13 Nov 2026 11:15:34 +0800 Subject: [PATCH 01/10] fix(pager-view): keep staged overlay content out of the page scroller lookup Overlay content (popover, sheet, dialog) stays mounted inside its host view until the overlay window presents it, and the host can sit in a page's subtree. A Fabric scroll view outranks a verified native list in the candidate tiers, so the collapsible pager adopted the staged sheet scroller as the page owner and applied the collapsed-header offset to it. The sheet then opened scrolled past its content until a drag bounced it back. Every scroll view lookup now skips overlay host subtrees. --- .../react-native-pager-view/docs/SPEC.md | 18 +++++++ .../RNCCollapsiblePagerViewComponentView.mm | 23 +++++++-- .../RNCCollapsiblePagerFirstFrameTests.mm | 48 +++++++++++++++++++ 3 files changed, 85 insertions(+), 4 deletions(-) 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]; From 0ee022058aa73165d0cb445934f4f5b0a5e95195 Mon Sep 17 00:00:00 2001 From: weatherstar Date: Fri, 13 Nov 2026 11:15:35 +0800 Subject: [PATCH 02/10] fix(native-list): limit the activity description action to its text MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The description label spans the identity column and took the action for a tap anywhere on its line, so tapping the blank area beside a contract label opened the label instead of the row. iOS and Android now take touches on the drawn text only (plus a small slop), and of a "time • address" description only on the address, as the Web renderer does. Other touches fall through to the row press. --- .../NativeListActivityDetailsView.kt | 5 ++ .../com/onekey/nativelist/NativeListModels.kt | 31 ++++++++++++ .../onekey/nativelist/NativeListTextView.kt | 42 ++++++++++++++++ .../NativeListDescriptionTouchPolicyTest.kt | 41 ++++++++++++++++ .../react-native-native-list/docs/SPEC.md | 5 +- .../ios/NativeListActivityDetailsView.swift | 7 +++ .../ios/NativeListTextLabel.swift | 41 ++++++++++++++++ .../NativeListActivityPresentationTests.swift | 49 +++++++++++++++++++ 8 files changed, 220 insertions(+), 1 deletion(-) create mode 100644 native-views/react-native-native-list/android/src/test/java/com/margelo/nitro/nativelist/NativeListDescriptionTouchPolicyTest.kt 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..732aad9af 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 @@ -103,6 +103,10 @@ internal class NativeListActivityDetailsView(private val reactContext: ThemedRea description.setOnClickListener(null) val descriptionKey = data.optString("descriptionActionKey") description.isClickable = descriptionKey.isNotEmpty() + // The view spans the identity column; only its text opens the action, and of + // a "time • address" description only the address, as on Web. + description.touchesTextOnly = descriptionKey.isNotEmpty() + description.touchableTextStart = nativeListDescriptionActionTextStart(data.optString("description")) if (descriptionKey.isNotEmpty()) 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() @@ -172,6 +176,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.touchesTextOnly = false; description.touchableTextStart = 0 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..bcd99f677 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,37 @@ internal fun nativeListLeadingVisualOverhangsFrame( */ internal fun nativeListActivityHostClips(leadingOverhangs: Boolean): Boolean = !leadingOverhangs +/** + * Character offset an Activity description's action starts at. A description is + * either the address or `time • address`; only the address opens the action, as + * on Web, so the offset skips the time and its separator. + */ +internal fun nativeListDescriptionActionTextStart(description: String): Int { + val separator = description.indexOf(" • ") + return if (separator < 0) 0 else separator + 3 +} + +/** + * Horizontal span of a stretched text view that takes touches: the drawn lines + * from [lineLeft] to [lineRight], without the part before [textStart] when one + * is given, widened by [slop] on both sides. Touches outside the span fall + * through to the row behind the view (OK-67219). + */ +internal fun nativeListTouchableTextSpan( + lineLeft: Float, + lineRight: Float, + textStart: Float?, + isRtl: Boolean, + slop: Float, +): ClosedFloatingPointRange { + var left = lineLeft + var right = lineRight + if (textStart != null) { + if (isRtl) right = minOf(right, textStart) else left = maxOf(left, textStart) + } + return (left - slop)..(right + slop) +} + 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/NativeListTextView.kt b/native-views/react-native-native-list/android/src/main/java/com/onekey/nativelist/NativeListTextView.kt index 2a26f062b..7501a2b8b 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 @@ -4,6 +4,7 @@ import android.graphics.Canvas import android.graphics.DashPathEffect import android.graphics.Paint import android.graphics.RectF +import android.text.Layout import android.view.MotionEvent import android.widget.TextView @@ -33,9 +34,46 @@ internal open class NativeListTextView(context: android.content.Context) : TextV ) } + /** + * Limits touches to the drawn text plus a small horizontal slop, so the unused + * width of a stretched view falls through to the row behind it. + */ + var touchesTextOnly = false + /** Character offset the touchable text starts at; a single-line view ignores touches before it. */ + var touchableTextStart = 0 + + val touchableTextBounds: RectF? + get() { + val textLayout = layout ?: return null + val lines = textLayout.lineCount + if (lines == 0) return null + var left = Float.MAX_VALUE + var right = -Float.MAX_VALUE + for (line in 0 until lines) { + left = minOf(left, textLayout.getLineLeft(line)) + right = maxOf(right, textLayout.getLineRight(line)) + } + val startsInside = lines == 1 && touchableTextStart > 0 && touchableTextStart < textLayout.text.length + val span = nativeListTouchableTextSpan( + lineLeft = left, + lineRight = right, + textStart = if (startsInside) textLayout.getPrimaryHorizontal(touchableTextStart) else null, + isRtl = textLayout.getParagraphDirection(0) == Layout.DIR_RIGHT_TO_LEFT, + slop = TOUCH_SLOP_DP * resources.displayMetrics.density, + ) + return RectF( + totalPaddingLeft + span.start, + 0f, + totalPaddingLeft + span.endInclusive, + height.toFloat(), + ) + } + override fun onTouchEvent(event: MotionEvent): Boolean { if (primaryHelpOnly && event.actionMasked == MotionEvent.ACTION_DOWN && helpAnchorBounds?.contains(event.x, event.y) != true) return false + if (touchesTextOnly && event.actionMasked == MotionEvent.ACTION_DOWN && + touchableTextBounds?.contains(event.x, event.y) != true) return false if (guardsHelpTouches) { if (event.actionMasked == MotionEvent.ACTION_DOWN) helpDownGeneration = helpBindingGeneration if (event.actionMasked == MotionEvent.ACTION_UP && helpDownGeneration != helpBindingGeneration) { @@ -76,4 +114,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..652d7782c --- /dev/null +++ b/native-views/react-native-native-list/android/src/test/java/com/margelo/nitro/nativelist/NativeListDescriptionTouchPolicyTest.kt @@ -0,0 +1,41 @@ +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 { + // 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 span = nativeListTouchableTextSpan( + lineLeft = 0f, lineRight = 60f, textStart = null, isRtl = false, slop = 8f, + ) + + assertTrue(30f in span) + assertTrue(66f in span) + assertFalse(120f in span) + } + + // Of `time • address` only the address opens the action, as on Web. + @Test + fun aLeadingTimeIsNotPartOfTheAction() { + assertEquals(0, nativeListDescriptionActionTextStart("0x35e6cb…cd1f0e")) + assertEquals(8, nativeListDescriptionActionTextStart("08:48 • Uniswap")) + + val ltr = nativeListTouchableTextSpan( + lineLeft = 0f, lineRight = 160f, textStart = 50f, isRtl = false, slop = 8f, + ) + assertFalse(20f in ltr) + assertTrue(100f in ltr) + + val rtl = nativeListTouchableTextSpan( + lineLeft = 40f, lineRight = 200f, textStart = 150f, isRtl = true, slop = 8f, + ) + assertTrue(100f in rtl) + assertFalse(180f in rtl) + } +} diff --git a/native-views/react-native-native-list/docs/SPEC.md b/native-views/react-native-native-list/docs/SPEC.md index 3e3964292..468281bc4 100644 --- a/native-views/react-native-native-list/docs/SPEC.md +++ b/native-views/react-native-native-list/docs/SPEC.md @@ -1785,7 +1785,10 @@ and secondary text with their own segments; `hidden` preserves its column width while hiding its contents. Up to four uniquely keyed title badges use declared 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. +disabled behavior. All actions use the current host binding epoch. The action +is hit on the description text only: of a `time • address` description on the +address, and never on the unused width of the description line, which belongs +to the row press. iOS and Android add a small touch slop around the text. 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 diff --git a/native-views/react-native-native-list/ios/NativeListActivityDetailsView.swift b/native-views/react-native-native-list/ios/NativeListActivityDetailsView.swift index 7f11094ee..ad3dea397 100644 --- a/native-views/react-native-native-list/ios/NativeListActivityDetailsView.swift +++ b/native-views/react-native-native-list/ios/NativeListActivityDetailsView.swift @@ -197,6 +197,12 @@ final class NativeListActivityDetailsView: UIStackView { ).bind(status) descriptionKey = data.string("descriptionActionKey") descriptionLabel.isUserInteractionEnabled = !descriptionKey.isEmpty + // The label spans the identity column; only its text opens the action, and + // of a "time • address" description only the address, as on Web. + descriptionLabel.touchesTextOnly = !descriptionKey.isEmpty + let descriptionText = data.string("description") as NSString + let separator = descriptionText.range(of: " • ") + descriptionLabel.touchableTextStart = separator.location == NSNotFound ? 0 : NSMaxRange(separator) descriptionLabel.accessibilityTraits = descriptionKey.isEmpty ? .staticText : .button for badge in badgeViews { titleLine.removeArrangedSubview(badge); badge.removeFromSuperview() } badgeViews = data.dictionaries("badges").map { descriptor in @@ -269,6 +275,7 @@ final class NativeListActivityDetailsView: UIStackView { } func recycle() { visual.recycle(); visual.isHidden = false; amountViews.forEach { $0.recycle() }; actionKeys = []; descriptionKey = "" + descriptionLabel.touchesTextOnly = false; descriptionLabel.touchableTextStart = 0 } } diff --git a/native-views/react-native-native-list/ios/NativeListTextLabel.swift b/native-views/react-native-native-list/ios/NativeListTextLabel.swift index ee982e3de..955b2e45d 100644 --- a/native-views/react-native-native-list/ios/NativeListTextLabel.swift +++ b/native-views/react-native-native-list/ios/NativeListTextLabel.swift @@ -3,6 +3,47 @@ import UIKit class NativeListTextLabel: UILabel { var rowVerticalAlignment: String? { didSet { setNeedsDisplay() } } var rowOffsetY: CGFloat = 0 { didSet { setNeedsDisplay() } } + /// Limits touches to the drawn text plus a small slop, so the unused width of + /// a stretched label falls through to the row behind it. + var touchesTextOnly = false + /// UTF-16 offset the touchable text starts at; a single-line label does not + /// take touches on the text before it. + var touchableTextStart = 0 + private static let touchSlop = CGSize(width: 8, height: 6) + + var touchableTextBounds: CGRect { + let text = textRect(forBounds: bounds, limitedToNumberOfLines: numberOfLines) + var minX = text.minX + var maxX = text.maxX + if touchableTextStart > 0, let attributed = attributedText, + touchableTextStart < attributed.length, text.height < font.lineHeight * 1.5 { + let leading = ceil( + attributed.attributedSubstring(from: NSRange(location: 0, length: touchableTextStart)) + .boundingRect( + with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: .greatestFiniteMagnitude), + options: [.usesLineFragmentOrigin], context: nil + ).width) + if effectiveUserInterfaceLayoutDirection == .rightToLeft { maxX -= leading } else { minX += leading } + } + return CGRect(x: minX, y: bounds.minY, width: max(0, maxX - minX), height: bounds.height) + .insetBy(dx: -Self.touchSlop.width, dy: -Self.touchSlop.height) + } + + override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { + guard touchesTextOnly else { return super.point(inside: point, with: event) } + return touchableTextBounds.contains(point) + } + + // Assistive activation taps this point; the label's center can be blank. + override var accessibilityActivationPoint: CGPoint { + get { + guard touchesTextOnly else { return super.accessibilityActivationPoint } + let target = UIAccessibility.convertToScreenCoordinates( + touchableTextBounds.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..3a602d2b7 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,55 @@ 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 text opens it now; the + // blank rest of the line belongs to the row press (OK-67219). + func testDescriptionActionTakesTouchesOnItsTextOnly() throws { + let details = NativeListActivityDetailsView() + let container = UIView(frame: CGRect(x: 0, y: 0, width: 366, 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?) 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 } + 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) + } + + let address = try bind(description: "Uniswap", actionKey: "address-info") + XCTAssertGreaterThan(address.bounds.width, address.touchableTextBounds.maxX + 40) + XCTAssertTrue(hit(address, x: 4)) + XCTAssertFalse(hit(address, x: address.bounds.maxX - 4)) + + // Of "time • address" only the address opens the action, as on Web. + let timed = try bind(description: "08:48 • Uniswap", actionKey: "address-info") + XCTAssertFalse(hit(timed, x: 4)) + XCTAssertTrue(hit(timed, x: timed.touchableTextBounds.maxX - 12)) + XCTAssertFalse(hit(timed, x: timed.bounds.maxX - 4)) + + // A reused view without the action takes no special touch handling. + let plain = try bind(description: "Uniswap", actionKey: nil) + XCTAssertFalse(plain.touchesTextOnly) + XCTAssertTrue(hit(plain, x: plain.bounds.maxX - 4)) + } + func testSmallNumberRunsPreserveBaselineAcrossAmountsFiatAndFee() throws { func segments(_ prefix: String, _ suffix: String) -> [[String: Any]] { [["text": prefix], ["text": "5", "style": "subscript"], ["text": suffix]] From a0057ad15902094f28f59b0ffbd3e4448948b7a1 Mon Sep 17 00:00:00 2001 From: weatherstar Date: Fri, 13 Nov 2026 11:44:05 +0800 Subject: [PATCH 03/10] fix(native-list): keep the time prefix outside the description action on wrapped rows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The touch area excluded the leading time only on a single-line description; once "time • address" wrapped, the whole text took the action again, on iOS and Android. The touchable area is now computed per laid-out line: a line before the address takes no touches, the line that holds the separator takes them from the address on, and later lines take them on their text. The vertical slop only grows away from the text, so it cannot reach into the time's line. --- .../com/onekey/nativelist/NativeListModels.kt | 46 ++++++++---- .../onekey/nativelist/NativeListTextView.kt | 47 ++++++------ .../NativeListDescriptionTouchPolicyTest.kt | 62 ++++++++++++---- .../ios/NativeListTextLabel.swift | 72 +++++++++++++------ .../NativeListActivityPresentationTests.swift | 23 +++++- 5 files changed, 176 insertions(+), 74 deletions(-) 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 bcd99f677..856dbc304 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 @@ -72,25 +72,41 @@ internal fun nativeListDescriptionActionTextStart(description: String): Int { return if (separator < 0) 0 else separator + 3 } +/** One laid-out line of a text view, in view coordinates; `[start, end)` are character offsets. */ +internal data class NativeListTextLine( + val start: Int, + val end: Int, + val left: Float, + val top: Float, + val right: Float, + val bottom: Float, + val isRtl: Boolean = false, +) + +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 +} + /** - * Horizontal span of a stretched text view that takes touches: the drawn lines - * from [lineLeft] to [lineRight], without the part before [textStart] when one - * is given, widened by [slop] on both sides. Touches outside the span fall - * through to the row behind the view (OK-67219). + * Parts of a stretched text view that take touches: on every line the drawn + * text from character [textStart] on, widened horizontally by [slop]. A line + * that ends before [textStart] takes none, and the line that holds it takes + * none before [textStartX], however the text wraps. Touches outside the regions + * fall through to the row behind the view (OK-67219). */ -internal fun nativeListTouchableTextSpan( - lineLeft: Float, - lineRight: Float, - textStart: Float?, - isRtl: Boolean, +internal fun nativeListTouchableTextRegions( + lines: List, + textStart: Int, + textStartX: Float, slop: Float, -): ClosedFloatingPointRange { - var left = lineLeft - var right = lineRight - if (textStart != null) { - if (isRtl) right = minOf(right, textStart) else left = maxOf(left, textStart) +): List = lines.mapNotNull { line -> + if (line.end <= textStart) return@mapNotNull null + var left = line.left + var right = line.right + if (line.start < textStart) { + if (line.isRtl) right = minOf(right, textStartX) else left = maxOf(left, textStartX) } - return (left - slop)..(right + slop) + NativeListTouchRegion(left - slop, line.top, right + slop, line.bottom) } internal data class NativeListSlotFrame(val x: Int, val y: Int, val width: Int, val height: Int) 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 7501a2b8b..6f6ab4e59 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 @@ -39,41 +39,42 @@ internal open class NativeListTextView(context: android.content.Context) : TextV * width of a stretched view falls through to the row behind it. */ var touchesTextOnly = false - /** Character offset the touchable text starts at; a single-line view ignores touches before it. */ + /** Character offset the touchable text starts at; text before it takes no touches on any line. */ var touchableTextStart = 0 - val touchableTextBounds: RectF? + val touchableTextRegions: List get() { - val textLayout = layout ?: return null - val lines = textLayout.lineCount - if (lines == 0) return null - var left = Float.MAX_VALUE - var right = -Float.MAX_VALUE - for (line in 0 until lines) { - left = minOf(left, textLayout.getLineLeft(line)) - right = maxOf(right, textLayout.getLineRight(line)) + val textLayout = layout ?: return emptyList() + val count = textLayout.lineCount + if (count == 0) return emptyList() + val originX = totalPaddingLeft.toFloat() + val originY = totalPaddingTop + opticalOffsetY + val lines = (0 until count).map { line -> + NativeListTextLine( + start = textLayout.getLineStart(line), + end = textLayout.getLineEnd(line), + left = originX + textLayout.getLineLeft(line), + // The outer lines also take the view's own vertical padding. + top = if (line == 0) 0f else originY + textLayout.getLineTop(line), + right = originX + textLayout.getLineRight(line), + bottom = if (line == count - 1) height.toFloat() else originY + textLayout.getLineBottom(line), + isRtl = textLayout.getParagraphDirection(line) == Layout.DIR_RIGHT_TO_LEFT, + ) } - val startsInside = lines == 1 && touchableTextStart > 0 && touchableTextStart < textLayout.text.length - val span = nativeListTouchableTextSpan( - lineLeft = left, - lineRight = right, - textStart = if (startsInside) textLayout.getPrimaryHorizontal(touchableTextStart) else null, - isRtl = textLayout.getParagraphDirection(0) == Layout.DIR_RIGHT_TO_LEFT, + val startsInside = touchableTextStart > 0 && touchableTextStart < textLayout.text.length + return nativeListTouchableTextRegions( + lines = lines, + textStart = touchableTextStart, + textStartX = if (startsInside) originX + textLayout.getPrimaryHorizontal(touchableTextStart) else 0f, slop = TOUCH_SLOP_DP * resources.displayMetrics.density, ) - return RectF( - totalPaddingLeft + span.start, - 0f, - totalPaddingLeft + span.endInclusive, - height.toFloat(), - ) } override fun onTouchEvent(event: MotionEvent): Boolean { if (primaryHelpOnly && event.actionMasked == MotionEvent.ACTION_DOWN && helpAnchorBounds?.contains(event.x, event.y) != true) return false if (touchesTextOnly && event.actionMasked == MotionEvent.ACTION_DOWN && - touchableTextBounds?.contains(event.x, event.y) != true) return false + 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) { 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 index 652d7782c..b11f29a73 100644 --- 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 @@ -6,18 +6,21 @@ 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) } + // 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 span = nativeListTouchableTextSpan( - lineLeft = 0f, lineRight = 60f, textStart = null, isRtl = false, slop = 8f, + val regions = nativeListTouchableTextRegions( + lines = listOf(NativeListTextLine(start = 0, end = 7, left = 0f, top = 0f, right = 60f, bottom = 20f)), + textStart = 0, textStartX = 0f, slop = 8f, ) - assertTrue(30f in span) - assertTrue(66f in span) - assertFalse(120f in span) + assertTrue(hit(regions, 30f, 10f)) + assertTrue(hit(regions, 66f, 10f)) + assertFalse(hit(regions, 120f, 10f)) } // Of `time • address` only the address opens the action, as on Web. @@ -26,16 +29,49 @@ class NativeListDescriptionTouchPolicyTest { assertEquals(0, nativeListDescriptionActionTextStart("0x35e6cb…cd1f0e")) assertEquals(8, nativeListDescriptionActionTextStart("08:48 • Uniswap")) - val ltr = nativeListTouchableTextSpan( - lineLeft = 0f, lineRight = 160f, textStart = 50f, isRtl = false, slop = 8f, + val ltr = nativeListTouchableTextRegions( + lines = listOf(NativeListTextLine(start = 0, end = 15, left = 0f, top = 0f, right = 160f, bottom = 20f)), + textStart = 8, textStartX = 50f, slop = 8f, + ) + assertFalse(hit(ltr, 20f, 10f)) + assertTrue(hit(ltr, 100f, 10f)) + + val rtl = nativeListTouchableTextRegions( + lines = listOf( + NativeListTextLine(start = 0, end = 15, left = 40f, top = 0f, right = 200f, bottom = 20f, isRtl = true), + ), + textStart = 8, textStartX = 150f, slop = 8f, + ) + assertTrue(hit(rtl, 100f, 10f)) + assertFalse(hit(rtl, 180f, 10f)) + } + + // 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 = nativeListTouchableTextRegions( + lines = listOf( + NativeListTextLine(start = 0, end = 16, left = 0f, top = 0f, right = 110f, bottom = 20f), + NativeListTextLine(start = 16, end = 32, left = 0f, top = 20f, right = 100f, bottom = 40f), + ), + textStart = 8, textStartX = 55f, slop = 8f, ) - assertFalse(20f in ltr) - assertTrue(100f in ltr) + assertFalse(hit(wrapped, 20f, 10f)) + assertTrue(hit(wrapped, 80f, 10f)) + assertTrue(hit(wrapped, 20f, 30f)) + assertFalse(hit(wrapped, 130f, 30f)) - val rtl = nativeListTouchableTextSpan( - lineLeft = 40f, lineRight = 200f, textStart = 150f, isRtl = true, slop = 8f, + // The whole time sits on the first line: that line takes no touches at all. + val timeOnItsOwnLine = nativeListTouchableTextRegions( + lines = listOf( + NativeListTextLine(start = 0, end = 8, left = 0f, top = 0f, right = 55f, bottom = 20f), + NativeListTextLine(start = 8, end = 24, left = 0f, top = 20f, right = 100f, bottom = 40f), + ), + textStart = 8, textStartX = 0f, slop = 8f, ) - assertTrue(100f in rtl) - assertFalse(180f in rtl) + assertFalse(hit(timeOnItsOwnLine, 20f, 10f)) + assertTrue(hit(timeOnItsOwnLine, 20f, 30f)) } } diff --git a/native-views/react-native-native-list/ios/NativeListTextLabel.swift b/native-views/react-native-native-list/ios/NativeListTextLabel.swift index 955b2e45d..c34dd57df 100644 --- a/native-views/react-native-native-list/ios/NativeListTextLabel.swift +++ b/native-views/react-native-native-list/ios/NativeListTextLabel.swift @@ -6,40 +6,70 @@ class NativeListTextLabel: UILabel { /// Limits touches to the drawn text plus a small slop, so the unused width of /// a stretched label falls through to the row behind it. var touchesTextOnly = false - /// UTF-16 offset the touchable text starts at; a single-line label does not - /// take touches on the text before it. + /// UTF-16 offset the touchable text starts at; text before it takes no + /// touches on any line. var touchableTextStart = 0 private static let touchSlop = CGSize(width: 8, height: 6) - var touchableTextBounds: CGRect { - let text = textRect(forBounds: bounds, limitedToNumberOfLines: numberOfLines) - var minX = text.minX - var maxX = text.maxX - if touchableTextStart > 0, let attributed = attributedText, - touchableTextStart < attributed.length, text.height < font.lineHeight * 1.5 { - let leading = ceil( - attributed.attributedSubstring(from: NSRange(location: 0, length: touchableTextStart)) - .boundingRect( - with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: .greatestFiniteMagnitude), - options: [.usesLineFragmentOrigin], context: nil - ).width) - if effectiveUserInterfaceLayoutDirection == .rightToLeft { maxX -= leading } else { minX += leading } + /// One rect per laid-out line that holds touchable text, in label coordinates. + /// The label's own layout is not public, so the lines come from a text + /// container with the label's width, line cap and truncation. + var touchableTextRegions: [CGRect] { + guard let attributed = attributedText, attributed.length > 0, 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 + let start = touchableTextStart + var lines: [CGRect] = [] + manager.enumerateLineFragments(forGlyphRange: glyphs) { _, usedRect, _, lineGlyphs, _ in + let characters = manager.characterRange(forGlyphRange: lineGlyphs, actualGlyphRange: nil) + guard NSMaxRange(characters) > start else { return } + var rect = usedRect + if characters.location < start { + let touchable = NSRange(location: start, length: NSMaxRange(characters) - start) + rect = manager.boundingRect( + forGlyphRange: manager.glyphRange(forCharacterRange: touchable, actualCharacterRange: nil), + in: container) + } + lines.append(rect.offsetBy(dx: 0, dy: originY)) + } + // The slop widens every line, but grows vertically only away from the + // text, so it never reaches into a neighbouring line. + return lines.enumerated().map { index, rect in + let top = index == 0 ? Self.touchSlop.height : 0 + let bottom = index == lines.count - 1 ? Self.touchSlop.height : 0 + return CGRect( + x: rect.minX - Self.touchSlop.width, y: rect.minY - top, + width: rect.width + Self.touchSlop.width * 2, height: rect.height + top + bottom) } - return CGRect(x: minX, y: bounds.minY, width: max(0, maxX - minX), height: bounds.height) - .insetBy(dx: -Self.touchSlop.width, dy: -Self.touchSlop.height) } override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { guard touchesTextOnly else { return super.point(inside: point, with: event) } - return touchableTextBounds.contains(point) + return touchableTextRegions.contains { $0.contains(point) } } // Assistive activation taps this point; the label's center can be blank. override var accessibilityActivationPoint: CGPoint { get { - guard touchesTextOnly else { return super.accessibilityActivationPoint } - let target = UIAccessibility.convertToScreenCoordinates( - touchableTextBounds.intersection(bounds), in: self) + guard touchesTextOnly, 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 } 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 3a602d2b7..fca351662 100644 --- a/native-views/react-native-native-list/ios/tests/NativeListActivityPresentationTests.swift +++ b/native-views/react-native-native-list/ios/tests/NativeListActivityPresentationTests.swift @@ -93,16 +93,35 @@ final class NativeListActivityPresentationTests: XCTestCase { } let address = try bind(description: "Uniswap", actionKey: "address-info") - XCTAssertGreaterThan(address.bounds.width, address.touchableTextBounds.maxX + 40) + let addressText = try XCTUnwrap(address.touchableTextRegions.first) + XCTAssertEqual(address.touchableTextRegions.count, 1) + XCTAssertGreaterThan(address.bounds.width, addressText.maxX + 40) XCTAssertTrue(hit(address, x: 4)) XCTAssertFalse(hit(address, x: address.bounds.maxX - 4)) // Of "time • address" only the address opens the action, as on Web. let timed = try bind(description: "08:48 • Uniswap", actionKey: "address-info") + let timedText = try XCTUnwrap(timed.touchableTextRegions.first) + XCTAssertEqual(timed.touchableTextRegions.count, 1) XCTAssertFalse(hit(timed, x: 4)) - XCTAssertTrue(hit(timed, x: timed.touchableTextBounds.maxX - 12)) + XCTAssertTrue(hit(timed, x: timedText.maxX - 12)) XCTAssertFalse(hit(timed, x: timed.bounds.maxX - 4)) + // 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. + container.frame.size.width = 220 + let wrapped = try bind( + description: "08:48 • Uniswap Universal Router", actionKey: "address-info") + let lines = wrapped.touchableTextRegions + XCTAssertEqual(lines.count, 2) + XCTAssertFalse(wrapped.point(inside: CGPoint(x: 4, y: lines[0].midY), with: nil)) + XCTAssertTrue(wrapped.point(inside: CGPoint(x: lines[0].maxX - 12, y: lines[0].midY), with: nil)) + XCTAssertTrue(wrapped.point(inside: CGPoint(x: 4, y: lines[1].midY), with: nil)) + XCTAssertFalse( + wrapped.point(inside: CGPoint(x: wrapped.bounds.maxX - 2, y: lines[1].midY), with: nil)) + container.frame.size.width = 366 + // A reused view without the action takes no special touch handling. let plain = try bind(description: "Uniswap", actionKey: nil) XCTAssertFalse(plain.touchesTextOnly) From e6aff7bbceaa5025b5ffcf1f7795d86796977124 Mon Sep 17 00:00:00 2001 From: weatherstar Date: Fri, 13 Nov 2026 12:15:00 +0800 Subject: [PATCH 04/10] test(native-list): size the description touch cases independently of the row's column split MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The row-level cases assumed the identity column keeps most of a 366pt row. With a short amount the amounts column takes its full half, the label is about 119pt wide, and the blank area beside "08:48 • Uniswap" is narrower than the touch slop, so the right-edge assertions failed on the test geometry, not on the hit area. The row-level cases now use a row wide enough to leave blank space in any split and assert it, and the wrapped case sizes the label directly. --- .../NativeListActivityPresentationTests.swift | 47 ++++++++++++------- 1 file changed, 31 insertions(+), 16 deletions(-) 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 fca351662..ce0be91b5 100644 --- a/native-views/react-native-native-list/ios/tests/NativeListActivityPresentationTests.swift +++ b/native-views/react-native-native-list/ios/tests/NativeListActivityPresentationTests.swift @@ -65,7 +65,9 @@ final class NativeListActivityPresentationTests: XCTestCase { // blank rest of the line belongs to the row press (OK-67219). func testDescriptionActionTakesTouchesOnItsTextOnly() throws { let details = NativeListActivityDetailsView() - let container = UIView(frame: CGRect(x: 0, y: 0, width: 366, height: 300)) + // 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([ @@ -103,31 +105,44 @@ final class NativeListActivityPresentationTests: XCTestCase { let timed = try bind(description: "08:48 • Uniswap", actionKey: "address-info") let timedText = try XCTUnwrap(timed.touchableTextRegions.first) XCTAssertEqual(timed.touchableTextRegions.count, 1) + XCTAssertGreaterThan(timed.bounds.width, timedText.maxX + 40) XCTAssertFalse(hit(timed, x: 4)) XCTAssertTrue(hit(timed, x: timedText.maxX - 12)) XCTAssertFalse(hit(timed, x: timed.bounds.maxX - 4)) - // 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. - container.frame.size.width = 220 - let wrapped = try bind( - description: "08:48 • Uniswap Universal Router", actionKey: "address-info") - let lines = wrapped.touchableTextRegions - XCTAssertEqual(lines.count, 2) - XCTAssertFalse(wrapped.point(inside: CGPoint(x: 4, y: lines[0].midY), with: nil)) - XCTAssertTrue(wrapped.point(inside: CGPoint(x: lines[0].maxX - 12, y: lines[0].midY), with: nil)) - XCTAssertTrue(wrapped.point(inside: CGPoint(x: 4, y: lines[1].midY), with: nil)) - XCTAssertFalse( - wrapped.point(inside: CGPoint(x: wrapped.bounds.maxX - 2, y: lines[1].midY), with: nil)) - container.frame.size.width = 366 - // A reused view without the action takes no special touch handling. let plain = try bind(description: "Uniswap", actionKey: nil) XCTAssertFalse(plain.touchesTextOnly) XCTAssertTrue(hit(plain, x: plain.bounds.maxX - 4)) } + // 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.touchesTextOnly = true + 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)) + } + func testSmallNumberRunsPreserveBaselineAcrossAmountsFiatAndFee() throws { func segments(_ prefix: String, _ suffix: String) -> [[String: Any]] { [["text": prefix], ["text": "5", "style": "subscript"], ["text": suffix]] From e3d5ee8f9d2ca6c2eb4b2c907a205446310836b1 Mon Sep 17 00:00:00 2001 From: weatherstar Date: Fri, 13 Nov 2026 14:48:45 +0800 Subject: [PATCH 05/10] fix(native-list): take the description action start from the caller MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The first " • " of the description decided which part of it opens descriptionActionKey: on Web before, and on iOS and Android since this branch. A label is free text, so "Router • V2" lost its first word, and any change of the description format needed a native release. ActivityRow.descriptionActionStart is the UTF-16 offset the action text starts at; absent means the whole text. Web, iOS and Android consume it and no renderer parses the string. Validation checks the type and, on a complete row, the range; production drops a malformed value and the renderers clamp. A patch that changes the description without restating the offset clears it. The native text views hold one optional start in place of a switch and a start, so the two cannot disagree. --- .../NativeListActivityDetailsView.kt | 26 ++-- .../com/onekey/nativelist/NativeListModels.kt | 20 ++- .../nativelist/NativeListResolvedText.kt | 6 +- .../onekey/nativelist/NativeListTextView.kt | 21 +-- .../NativeListDescriptionTouchPolicyTest.kt | 43 +++++- .../docs/ROW_TEMPLATES.md | 5 +- .../react-native-native-list/docs/SPEC.md | 36 ++++- .../ios/NativeListActivityDetailsView.swift | 25 ++-- .../ios/NativeListResolvedText.swift | 19 ++- .../ios/NativeListTextLabel.swift | 21 +-- .../NativeListActivityPresentationTests.swift | 94 ++++++++++-- .../src/__tests__/NativeList.web.test.ts | 70 +++++++++ .../src/__tests__/activityRich.test.ts | 139 +++++++++++++++++- .../react-native-native-list/src/models.ts | 9 ++ .../src/validation.ts | 34 +++++ .../src/web/templates/ActivityRowRenderer.ts | 67 +++++---- 16 files changed, 523 insertions(+), 112 deletions(-) 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 732aad9af..eca63c1ee 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,16 +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() - // The view spans the identity column; only its text opens the action, and of - // a "time • address" description only the address, as on Web. - description.touchesTextOnly = descriptionKey.isNotEmpty() - description.touchableTextStart = nativeListDescriptionActionTextStart(data.optString("description")) - 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.optInt("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") @@ -176,7 +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.touchesTextOnly = false; description.touchableTextStart = 0 + 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 856dbc304..bb4c6bf01 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,14 +62,17 @@ 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]"), " ") + /** - * Character offset an Activity description's action starts at. A description is - * either the address or `time • address`; only the address opens the action, as - * on Web, so the offset skips the time and its separator. + * 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. */ -internal fun nativeListDescriptionActionTextStart(description: String): Int { - val separator = description.indexOf(" • ") - return if (separator < 0) 0 else separator + 3 +internal fun nativeListDisplayOffset(source: String, sourceOffset: Int, foldsLineBreaks: Boolean): Int { + val clamped = sourceOffset.coerceIn(0, source.length) + return if (foldsLineBreaks) nativeListFoldLineBreaks(source.substring(0, clamped)).length else clamped } /** One laid-out line of a text view, in view coordinates; `[start, end)` are character offsets. */ @@ -91,8 +94,9 @@ internal data class NativeListTouchRegion(val left: Float, val top: Float, val r * Parts of a stretched text view that take touches: on every line the drawn * text from character [textStart] on, widened horizontally by [slop]. A line * that ends before [textStart] takes none, and the line that holds it takes - * none before [textStartX], however the text wraps. Touches outside the regions - * fall through to the row behind the view (OK-67219). + * none before [textStartX], however the text wraps; a [textStart] at the end + * of the text leaves no region. Touches outside the regions fall through to + * the row behind the view (OK-67219). */ internal fun nativeListTouchableTextRegions( lines: List, 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..427e248dc 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: Int, 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 6f6ab4e59..7526cfe61 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 @@ -35,15 +35,18 @@ internal open class NativeListTextView(context: android.content.Context) : TextV } /** - * Limits touches to the drawn text plus a small horizontal slop, so the unused - * width of a stretched view falls through to the row behind it. + * 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 touchesTextOnly = false - /** Character offset the touchable text starts at; text before it takes no touches on any line. */ - var touchableTextStart = 0 + var touchableTextStart: Int? = null val touchableTextRegions: List get() { + val textStart = touchableTextStart ?: return emptyList() val textLayout = layout ?: return emptyList() val count = textLayout.lineCount if (count == 0) return emptyList() @@ -61,11 +64,11 @@ internal open class NativeListTextView(context: android.content.Context) : TextV isRtl = textLayout.getParagraphDirection(line) == Layout.DIR_RIGHT_TO_LEFT, ) } - val startsInside = touchableTextStart > 0 && touchableTextStart < textLayout.text.length + val startsInside = textStart > 0 && textStart < textLayout.text.length return nativeListTouchableTextRegions( lines = lines, - textStart = touchableTextStart, - textStartX = if (startsInside) originX + textLayout.getPrimaryHorizontal(touchableTextStart) else 0f, + textStart = textStart, + textStartX = if (startsInside) originX + textLayout.getPrimaryHorizontal(textStart) else 0f, slop = TOUCH_SLOP_DP * resources.displayMetrics.density, ) } @@ -73,7 +76,7 @@ internal open class NativeListTextView(context: android.content.Context) : TextV override fun onTouchEvent(event: MotionEvent): Boolean { if (primaryHelpOnly && event.actionMasked == MotionEvent.ACTION_DOWN && helpAnchorBounds?.contains(event.x, event.y) != true) return false - if (touchesTextOnly && event.actionMasked == MotionEvent.ACTION_DOWN && + 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 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 index b11f29a73..4147960a0 100644 --- 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 @@ -23,12 +23,10 @@ class NativeListDescriptionTouchPolicyTest { assertFalse(hit(regions, 120f, 10f)) } - // Of `time • address` only the address opens the action, as on Web. + // The caller states where the action text starts; the text before it, a + // time for one, is not part of the action. @Test - fun aLeadingTimeIsNotPartOfTheAction() { - assertEquals(0, nativeListDescriptionActionTextStart("0x35e6cb…cd1f0e")) - assertEquals(8, nativeListDescriptionActionTextStart("08:48 • Uniswap")) - + fun textBeforeTheStartIsNotPartOfTheAction() { val ltr = nativeListTouchableTextRegions( lines = listOf(NativeListTextLine(start = 0, end = 15, left = 0f, top = 0f, right = 160f, bottom = 20f)), textStart = 8, textStartX = 50f, slop = 8f, @@ -72,6 +70,41 @@ class NativeListDescriptionTouchPolicyTest { textStart = 8, textStartX = 0f, slop = 8f, ) 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 aStartAtTheEndOfTheTextLeavesNoRegion() { + val regions = nativeListTouchableTextRegions( + lines = listOf(NativeListTextLine(start = 0, end = 8, left = 0f, top = 0f, right = 55f, bottom = 20f)), + textStart = 8, textStartX = 0f, slop = 8f, + ) + + assertTrue(regions.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)) + + // The emoji takes two UTF-16 units, as in the JavaScript string. + val emojiPrefix = "\uD83D\uDD58 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 468281bc4..9f9426dae 100644 --- a/native-views/react-native-native-list/docs/SPEC.md +++ b/native-views/react-native-native-list/docs/SPEC.md @@ -1785,10 +1785,38 @@ and secondary text with their own segments; `hidden` preserves its column width while hiding its contents. Up to four uniquely keyed title badges use declared 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. The action -is hit on the description text only: of a `time • address` description on the -address, and never on the unused width of the description line, which belongs -to the row press. iOS and Android add a small touch slop around the text. +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 lines. 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. iOS and Android add a small touch slop around + the 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 diff --git a/native-views/react-native-native-list/ios/NativeListActivityDetailsView.swift b/native-views/react-native-native-list/ios/NativeListActivityDetailsView.swift index ad3dea397..665ee7369 100644 --- a/native-views/react-native-native-list/ios/NativeListActivityDetailsView.swift +++ b/native-views/react-native-native-list/ios/NativeListActivityDetailsView.swift @@ -187,23 +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 - // The label spans the identity column; only its text opens the action, and - // of a "time • address" description only the address, as on Web. - descriptionLabel.touchesTextOnly = !descriptionKey.isEmpty - let descriptionText = data.string("description") as NSString - let separator = descriptionText.range(of: " • ") - descriptionLabel.touchableTextStart = separator.location == NSNotFound ? 0 : NSMaxRange(separator) - 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() @@ -275,7 +276,7 @@ final class NativeListActivityDetailsView: UIStackView { } func recycle() { visual.recycle(); visual.isHidden = false; amountViews.forEach { $0.recycle() }; actionKeys = []; descriptionKey = "" - descriptionLabel.touchesTextOnly = false; descriptionLabel.touchableTextStart = 0 + 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 c34dd57df..fd4a3384b 100644 --- a/native-views/react-native-native-list/ios/NativeListTextLabel.swift +++ b/native-views/react-native-native-list/ios/NativeListTextLabel.swift @@ -3,19 +3,21 @@ import UIKit class NativeListTextLabel: UILabel { var rowVerticalAlignment: String? { didSet { setNeedsDisplay() } } var rowOffsetY: CGFloat = 0 { didSet { setNeedsDisplay() } } - /// Limits touches to the drawn text plus a small slop, so the unused width of - /// a stretched label falls through to the row behind it. - var touchesTextOnly = false - /// UTF-16 offset the touchable text starts at; text before it takes no - /// touches on any line. - var touchableTextStart = 0 + /// 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 line that holds touchable text, in label coordinates. /// The label's own layout is not public, so the lines come from a text /// container with the label's width, line cap and truncation. var touchableTextRegions: [CGRect] { - guard let attributed = attributedText, attributed.length > 0, bounds.width > 0 else { return [] } + guard let start = touchableTextStart, let attributed = attributedText, attributed.length > 0, + bounds.width > 0 + else { return [] } let storage = NSTextStorage(attributedString: attributed) let manager = NSLayoutManager() let container = NSTextContainer( @@ -33,7 +35,6 @@ class NativeListTextLabel: UILabel { originY = alignment == "top" ? 0 : alignment == "bottom" ? bounds.height - textHeight : originY } originY += rowOffsetY - let start = touchableTextStart var lines: [CGRect] = [] manager.enumerateLineFragments(forGlyphRange: glyphs) { _, usedRect, _, lineGlyphs, _ in let characters = manager.characterRange(forGlyphRange: lineGlyphs, actualGlyphRange: nil) @@ -59,14 +60,14 @@ class NativeListTextLabel: UILabel { } override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { - guard touchesTextOnly else { return super.point(inside: point, with: event) } + 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 touchesTextOnly, let region = touchableTextRegions.first else { + guard let region = touchableTextRegions.first else { return super.accessibilityActivationPoint } let target = UIAccessibility.convertToScreenCoordinates(region.intersection(bounds), in: self) 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 ce0be91b5..0050f24f5 100644 --- a/native-views/react-native-native-list/ios/tests/NativeListActivityPresentationTests.swift +++ b/native-views/react-native-native-list/ios/tests/NativeListActivityPresentationTests.swift @@ -61,8 +61,10 @@ 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 text opens it now; the - // blank rest of the line belongs to the row press (OK-67219). + // 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 @@ -75,13 +77,14 @@ final class NativeListActivityPresentationTests: XCTestCase { details.trailingAnchor.constraint(equalTo: container.trailingAnchor), details.topAnchor.constraint(equalTo: container.topAnchor), ]) - func bind(description: String, actionKey: String?) throws -> NativeListTextLabel { + 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? { @@ -94,26 +97,68 @@ final class NativeListActivityPresentationTests: XCTestCase { label.point(inside: CGPoint(x: x, y: label.bounds.midY), with: nil) } - let address = try bind(description: "Uniswap", actionKey: "address-info") - let addressText = try XCTUnwrap(address.touchableTextRegions.first) - XCTAssertEqual(address.touchableTextRegions.count, 1) - XCTAssertGreaterThan(address.bounds.width, addressText.maxX + 40) - XCTAssertTrue(hit(address, x: 4)) - XCTAssertFalse(hit(address, x: address.bounds.maxX - 4)) + // 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)) - // Of "time • address" only the address opens the action, as on Web. - let timed = try bind(description: "08:48 • Uniswap", actionKey: "address-info") + // 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) + XCTAssertEqual(timedText.width, labelText.width, accuracy: 1) XCTAssertFalse(hit(timed, x: 4)) + XCTAssertTrue(hit(timed, x: timedText.minX + 12)) XCTAssertTrue(hit(timed, x: timedText.maxX - 12)) XCTAssertFalse(hit(timed, x: timed.bounds.maxX - 4)) - // A reused view without the action takes no special touch handling. - let plain = try bind(description: "Uniswap", actionKey: nil) - XCTAssertFalse(plain.touchesTextOnly) + // 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, accuracy: 1) + XCTAssertFalse(hit(emoji, x: 4)) + XCTAssertTrue(hit(emoji, x: emojiText.minX + 12)) + XCTAssertTrue(hit(emoji, x: emojiText.maxX - 12)) + + // A start at the end of the text, or clamped to it, leaves nothing to tap. + for start in [(prefix as NSString).length, 99] { + 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 @@ -128,7 +173,6 @@ final class NativeListActivityPresentationTests: XCTestCase { fonts: NativeListFontFamilies() ).bind(label) label.frame = CGRect(x: 0, y: 0, width: 142, height: 40) - label.touchesTextOnly = true label.touchableTextStart = ("08:48 • " as NSString).length func hit(_ x: CGFloat, _ y: CGFloat) -> Bool { label.point(inside: CGPoint(x: x, y: y), with: nil) @@ -143,6 +187,26 @@ final class NativeListActivityPresentationTests: XCTestCase { XCTAssertFalse(hit(label.bounds.maxX - 2, lines[1].midY)) } + // 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/src/__tests__/NativeList.web.test.ts b/native-views/react-native-native-list/src/__tests__/NativeList.web.test.ts index 7aefaae33..2fb8b5e79 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,76 @@ 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.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..54711860d 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; @@ -221,14 +222,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 +252,8 @@ function createHistory(body: HTMLElement, primitives: RowPrimitives) { title, badges, description, - descriptionTime, - descriptionDot, - descriptionAddress, + descriptionPrefix, + descriptionAction, amounts, amountRows: new Map(), fee, @@ -579,29 +578,35 @@ 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' + // 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, ' '); + v.descriptionPrefix.style.cssText = `${ellipsis}flex-shrink:0;max-width:100%;white-space:pre;display:${ + actionStart > 0 ? 'block' : '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 ?? ''; + 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); From 7ed4558e4bbb25d0a38388963cc559fa6886aea8 Mon Sep 17 00:00:00 2001 From: weatherstar Date: Fri, 13 Nov 2026 14:48:56 +0800 Subject: [PATCH 06/10] fix(native-list): keep the description action slop out of the line above on iOS The vertical slop was added after the lines without action text had been dropped. With the time alone on the first line, the address line became the first touchable line and reached 6pt up into the time, which is not part of the action. The slop now belongs to the first and last line of the whole layout, so it never reaches into another line, touchable or not. --- .../react-native-native-list/docs/SPEC.md | 7 +++-- .../ios/NativeListTextLabel.swift | 25 ++++++++--------- .../NativeListActivityPresentationTests.swift | 27 +++++++++++++++++++ 3 files changed, 45 insertions(+), 14 deletions(-) diff --git a/native-views/react-native-native-list/docs/SPEC.md b/native-views/react-native-native-list/docs/SPEC.md index 9f9426dae..3c1a224c6 100644 --- a/native-views/react-native-native-list/docs/SPEC.md +++ b/native-views/react-native-native-list/docs/SPEC.md @@ -1811,8 +1811,11 @@ its wording; a caller that composes `prefix + label` records `prefix.length`. folds each line break into one space, so offsets after a CRLF move by one. - The hit area follows the laid-out lines. 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. iOS and Android add a small touch slop around - the text. + lines take them on their text. iOS and Android widen each line by 8 units. + 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. - 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 diff --git a/native-views/react-native-native-list/ios/NativeListTextLabel.swift b/native-views/react-native-native-list/ios/NativeListTextLabel.swift index fd4a3384b..271eb60c7 100644 --- a/native-views/react-native-native-list/ios/NativeListTextLabel.swift +++ b/native-views/react-native-native-list/ios/NativeListTextLabel.swift @@ -35,26 +35,27 @@ class NativeListTextLabel: UILabel { originY = alignment == "top" ? 0 : alignment == "bottom" ? bounds.height - textHeight : originY } originY += rowOffsetY - var lines: [CGRect] = [] + var lines: [(used: CGRect, characters: NSRange)] = [] manager.enumerateLineFragments(forGlyphRange: glyphs) { _, usedRect, _, lineGlyphs, _ in - let characters = manager.characterRange(forGlyphRange: lineGlyphs, actualGlyphRange: nil) - guard NSMaxRange(characters) > start else { return } - var rect = usedRect - if characters.location < start { - let touchable = NSRange(location: start, length: NSMaxRange(characters) - start) + lines.append( + (usedRect, manager.characterRange(forGlyphRange: lineGlyphs, actualGlyphRange: nil))) + } + return lines.enumerated().compactMap { index, line in + guard NSMaxRange(line.characters) > start else { return nil } + var rect = line.used + if line.characters.location < start { + let touchable = NSRange(location: start, length: NSMaxRange(line.characters) - start) rect = manager.boundingRect( forGlyphRange: manager.glyphRange(forCharacterRange: touchable, actualCharacterRange: nil), in: container) } - lines.append(rect.offsetBy(dx: 0, dy: originY)) - } - // The slop widens every line, but grows vertically only away from the - // text, so it never reaches into a neighbouring line. - return lines.enumerated().map { index, rect in + // The slop widens every line. Vertically it grows only past the first + // and last line of the whole layout, so it never reaches into another + // line, including one that holds no touchable text. let top = index == 0 ? Self.touchSlop.height : 0 let bottom = index == lines.count - 1 ? Self.touchSlop.height : 0 return CGRect( - x: rect.minX - Self.touchSlop.width, y: rect.minY - top, + x: rect.minX - Self.touchSlop.width, y: rect.minY + originY - top, width: rect.width + Self.touchSlop.width * 2, height: rect.height + top + bottom) } } 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 0050f24f5..574378863 100644 --- a/native-views/react-native-native-list/ios/tests/NativeListActivityPresentationTests.swift +++ b/native-views/react-native-native-list/ios/tests/NativeListActivityPresentationTests.swift @@ -187,6 +187,33 @@ final class NativeListActivityPresentationTests: XCTestCase { 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)) + } + // 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() { From b72dc48475e16ef35bb67eebe5d070d08eec51c7 Mon Sep 17 00:00:00 2001 From: weatherstar Date: Fri, 13 Nov 2026 14:48:57 +0800 Subject: [PATCH 07/10] test(native-list): tap the Activity description through real touch dispatch on Android The JVM test covers the geometry only. This instrumented case binds rich Activity rows in a NativeListView and taps the description line with sendPointerSync: the text from descriptionActionStart on emits the description action, the text before it and the blank width emit the row press. It also covers an emoji prefix, a start at or past the end, and rebinding, removing the action and recycling. --- .../NativeListDescriptionActionTouchTest.kt | 215 ++++++++++++++++++ .../native-tests/android/README.md | 13 ++ 2 files changed, 228 insertions(+) create mode 100644 native-views/react-native-native-list/native-tests/android/NativeListDescriptionActionTouchTest.kt 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..994048155 --- /dev/null +++ b/native-views/react-native-native-list/native-tests/android/NativeListDescriptionActionTouchTest.kt @@ -0,0 +1,215 @@ +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 + slop() > dp(20)) + assertEquals(listOf("press"), tap(description, dp(4))) + 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 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 + slop() + dp(4))) + assertEquals(listOf("address-info:description"), tap(description, text.right - slop() - dp(4))) + } + + fun testStartAtTheEndLeavesNoAction() { + for (start in listOf("08:48 • ".length, 99)) { + 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: Int? = 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) } + 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() + + /** 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..3970c649c 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,16 @@ 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 (5 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, UTF-16 +offsets behind an emoji prefix, a start at or past the end, 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. From 630c179849416e1da75f722f8542ce02637dbd0a Mon Sep 17 00:00:00 2001 From: weatherstar Date: Fri, 13 Nov 2026 15:12:19 +0800 Subject: [PATCH 08/10] fix(native-list): keep room for the Web description action behind a long prefix The prefix element did not shrink and could take the whole line, so a prefix wider than the row squeezed a non-empty action button to zero width and left it without a pointer target. While action text follows, the prefix is capped at the row width less 3em and truncates itself. A prefix that fits keeps its width and the action still truncates first, as the tail of the native label does. --- .../react-native-native-list/docs/SPEC.md | 8 +++ .../src/__tests__/NativeList.web.test.ts | 58 +++++++++++++++++++ .../src/web/templates/ActivityRowRenderer.ts | 11 +++- 3 files changed, 74 insertions(+), 3 deletions(-) diff --git a/native-views/react-native-native-list/docs/SPEC.md b/native-views/react-native-native-list/docs/SPEC.md index 3c1a224c6..490708e38 100644 --- a/native-views/react-native-native-list/docs/SPEC.md +++ b/native-views/react-native-native-list/docs/SPEC.md @@ -1816,6 +1816,14 @@ its wording; a caller that composes `prefix + label` records `prefix.length`. 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. +- 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. - 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 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 2fb8b5e79..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 @@ -1888,6 +1888,64 @@ describe('web row style', () => { } }); + 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/web/templates/ActivityRowRenderer.ts b/native-views/react-native-native-list/src/web/templates/ActivityRowRenderer.ts index 54711860d..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 @@ -197,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, @@ -590,9 +592,12 @@ function bindHistory( v.descriptionPrefix.textContent = description .slice(0, actionStart) .replace(/\r\n|[\r\n]/g, ' '); - v.descriptionPrefix.style.cssText = `${ellipsis}flex-shrink:0;max-width:100%;white-space:pre;display:${ - actionStart > 0 ? 'block' : 'none' - }`; + // 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' };`; From 3df79b6a0eabd920023780856b02e2f2c79de545 Mon Sep 17 00:00:00 2001 From: weatherstar Date: Fri, 13 Nov 2026 15:53:15 +0800 Subject: [PATCH 09/10] fix(native-list): clamp a description action start past Int range on Android The start was read with optInt. JSON carries any safe integer, and one past Int range, 4294967296 for example, came back as 0: the whole description became the action instead of none of it. The start is read as a Long and clamped to the description length before it is narrowed. iOS reads a 64-bit Int and Web a number, so only Android was affected; all three have a case for it now. --- .../onekey/nativelist/NativeListActivityDetailsView.kt | 2 +- .../main/java/com/onekey/nativelist/NativeListModels.kt | 8 +++++--- .../java/com/onekey/nativelist/NativeListResolvedText.kt | 2 +- .../nativelist/NativeListDescriptionTouchPolicyTest.kt | 4 ++++ .../ios/tests/NativeListActivityPresentationTests.swift | 3 ++- .../android/NativeListDescriptionActionTouchTest.kt | 8 +++++--- 6 files changed, 18 insertions(+), 9 deletions(-) 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 eca63c1ee..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 @@ -107,7 +107,7 @@ internal class NativeListActivityDetailsView(private val reactContext: ThemedRea // never read out of the string, and one at the end leaves no action. val actionStart = if (descriptionKey.isEmpty()) null - else descriptionText.displayOffset(data.optInt("descriptionActionStart"), data.optString("description")) + else descriptionText.displayOffset(data.optLong("descriptionActionStart"), data.optString("description")) val hasActionText = actionStart != null && actionStart < descriptionText.text.length description.touchableTextStart = actionStart description.isClickable = hasActionText 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 bb4c6bf01..23217f731 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 @@ -68,10 +68,12 @@ internal fun nativeListFoldLineBreaks(text: String): String = text.replace(Regex /** * 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. + * ([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: Int, foldsLineBreaks: Boolean): Int { - val clamped = sourceOffset.coerceIn(0, source.length) +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 } 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 427e248dc..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 @@ -44,7 +44,7 @@ internal data class NativeListResolvedText( val offset: Float, ) { /** Offset into [text] for a UTF-16 offset into the [source] it was resolved from. */ - fun displayOffset(sourceOffset: Int, source: String): Int = + fun displayOffset(sourceOffset: Long, source: String): Int = nativeListDisplayOffset(source, sourceOffset, foldsLineBreaks = lines == 1 && explicitTruncation) fun bind(view: NativeListTextView) { 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 index 4147960a0..32d6c2fce 100644 --- 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 @@ -95,6 +95,10 @@ class NativeListDescriptionTouchPolicyTest { 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 = "\uD83D\uDD58 08:48 • " 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 574378863..03e132f30 100644 --- a/native-views/react-native-native-list/ios/tests/NativeListActivityPresentationTests.swift +++ b/native-views/react-native-native-list/ios/tests/NativeListActivityPresentationTests.swift @@ -135,7 +135,8 @@ final class NativeListActivityPresentationTests: XCTestCase { XCTAssertTrue(hit(emoji, x: emojiText.maxX - 12)) // A start at the end of the text, or clamped to it, leaves nothing to tap. - for start in [(prefix as NSString).length, 99] { + // 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) 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 index 994048155..b5e0c7448 100644 --- a/native-views/react-native-native-list/native-tests/android/NativeListDescriptionActionTouchTest.kt +++ b/native-views/react-native-native-list/native-tests/android/NativeListDescriptionActionTouchTest.kt @@ -86,7 +86,9 @@ class NativeListDescriptionActionTouchTest : InstrumentationTestCase() { } fun testStartAtTheEndLeavesNoAction() { - for (start in listOf("08:48 • ".length, 99)) { + // 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))) @@ -116,13 +118,13 @@ class NativeListDescriptionActionTouchTest : InstrumentationTestCase() { assertNull(onMainValue { description.touchableTextStart }) } - private fun bind(description: String, actionKey: String?, actionStart: Int? = null): NativeListTextView { + 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) } + actionStart?.let { row.put("descriptionActionStart", it.toLong()) } generation += 1 val revision = generation row.put("revision", revision) From f7022197e6dd79830edf73ad4aca6f0b562d22fa Mon Sep 17 00:00:00 2001 From: weatherstar Date: Fri, 13 Nov 2026 15:53:16 +0800 Subject: [PATCH 10/10] fix(native-list): keep the description action slop out of plain text The horizontal slop widened the action area by 8 units on both sides, also on the side where the plain text before descriptionActionStart sits. A prefix narrower than the slop, the "i" of "iRouter" with start 1, opened the action it is not part of. The slop now reaches into blank space only and stops at plain text on the same line. The area is built from the layout engine's own rects for the action's character range (TextKit enclosing rects, the Android layout's selection) instead of one box per line, so a suffix that mixed-direction text splits into several visual runs is hit on each run and not on the plain text between them. An ellipsis belongs to the action while action text is visible before it; once truncation hides the action text, nothing is left to touch. --- .../com/onekey/nativelist/NativeListModels.kt | 49 ++++---- .../onekey/nativelist/NativeListTextView.kt | 55 ++++++--- .../NativeListDescriptionTouchPolicyTest.kt | 107 ++++++++++++------ .../react-native-native-list/docs/SPEC.md | 29 +++-- .../ios/NativeListTextLabel.swift | 77 +++++++++---- .../NativeListActivityPresentationTests.swift | 103 ++++++++++++++++- .../NativeListDescriptionActionTouchTest.kt | 38 ++++++- .../native-tests/android/README.md | 13 ++- 8 files changed, 361 insertions(+), 110 deletions(-) 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 23217f731..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 @@ -77,42 +77,49 @@ internal fun nativeListDisplayOffset(source: String, sourceOffset: Long, foldsLi return if (foldsLineBreaks) nativeListFoldLineBreaks(source.substring(0, clamped)).length else clamped } -/** One laid-out line of a text view, in view coordinates; `[start, end)` are character offsets. */ +/** 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 start: Int, - val end: Int, - val left: Float, val top: Float, - val right: Float, val bottom: Float, - val isRtl: Boolean = false, + 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: on every line the drawn - * text from character [textStart] on, widened horizontally by [slop]. A line - * that ends before [textStart] takes none, and the line that holds it takes - * none before [textStartX], however the text wraps; a [textStart] at the end - * of the text leaves no region. Touches outside the regions fall through to - * the row behind the view (OK-67219). + * 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, - textStart: Int, - textStartX: Float, slop: Float, -): List = lines.mapNotNull { line -> - if (line.end <= textStart) return@mapNotNull null - var left = line.left - var right = line.right - if (line.start < textStart) { - if (line.isRtl) right = minOf(right, textStartX) else left = maxOf(left, textStartX) +): 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) } - NativeListTouchRegion(left - slop, line.top, right + slop, line.bottom) } internal data class NativeListSlotFrame(val x: Int, val y: Int, val width: Int, val height: Int) 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 7526cfe61..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,10 +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 @@ -48,31 +54,54 @@ internal open class NativeListTextView(context: android.content.Context) : TextV get() { val textStart = touchableTextStart ?: return emptyList() val textLayout = layout ?: return emptyList() - val count = textLayout.lineCount + // 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( - start = textLayout.getLineStart(line), - end = textLayout.getLineEnd(line), - left = originX + textLayout.getLineLeft(line), // The outer lines also take the view's own vertical padding. top = if (line == 0) 0f else originY + textLayout.getLineTop(line), - right = originX + textLayout.getLineRight(line), bottom = if (line == count - 1) height.toFloat() else originY + textLayout.getLineBottom(line), - isRtl = textLayout.getParagraphDirection(line) == Layout.DIR_RIGHT_TO_LEFT, + touchable = + if (touchableStart < visibleEnd) textRuns(textLayout, line, touchableStart, lineEnd, originX) + else emptyList(), + plain = textRuns(textLayout, line, lineStart, minOf(textStart, lineEnd), originX), ) } - val startsInside = textStart > 0 && textStart < textLayout.text.length - return nativeListTouchableTextRegions( - lines = lines, - textStart = textStart, - textStartX = if (startsInside) originX + textLayout.getPrimaryHorizontal(textStart) else 0f, - slop = TOUCH_SLOP_DP * resources.displayMetrics.density, - ) + 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 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 index 32d6c2fce..3addf0224 100644 --- 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 @@ -8,53 +8,98 @@ 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 regions = nativeListTouchableTextRegions( - lines = listOf(NativeListTextLine(start = 0, end = 7, left = 0f, top = 0f, right = 60f, bottom = 20f)), - textStart = 0, textStartX = 0f, slop = 8f, - ) + val text = regions(NativeListTextLine(top = 0f, bottom = 20f, touchable = listOf(run(0f, 60f)))) - assertTrue(hit(regions, 30f, 10f)) - assertTrue(hit(regions, 66f, 10f)) - assertFalse(hit(regions, 120f, 10f)) + 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 = nativeListTouchableTextRegions( - lines = listOf(NativeListTextLine(start = 0, end = 15, left = 0f, top = 0f, right = 160f, bottom = 20f)), - textStart = 8, textStartX = 50f, slop = 8f, + 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)) - val rtl = nativeListTouchableTextRegions( - lines = listOf( - NativeListTextLine(start = 0, end = 15, left = 40f, top = 0f, right = 200f, bottom = 20f, isRtl = true), - ), - textStart = 8, textStartX = 150f, slop = 8f, + // 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 = nativeListTouchableTextRegions( - lines = listOf( - NativeListTextLine(start = 0, end = 16, left = 0f, top = 0f, right = 110f, bottom = 20f), - NativeListTextLine(start = 16, end = 32, left = 0f, top = 20f, right = 100f, bottom = 40f), - ), - textStart = 8, textStartX = 55f, slop = 8f, + 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)) @@ -62,12 +107,9 @@ class NativeListDescriptionTouchPolicyTest { assertFalse(hit(wrapped, 130f, 30f)) // The whole time sits on the first line: that line takes no touches at all. - val timeOnItsOwnLine = nativeListTouchableTextRegions( - lines = listOf( - NativeListTextLine(start = 0, end = 8, left = 0f, top = 0f, right = 55f, bottom = 20f), - NativeListTextLine(start = 8, end = 24, left = 0f, top = 20f, right = 100f, bottom = 40f), - ), - textStart = 8, textStartX = 0f, slop = 8f, + 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. @@ -77,13 +119,10 @@ class NativeListDescriptionTouchPolicyTest { // A start at the end of the text leaves nothing to touch. @Test - fun aStartAtTheEndOfTheTextLeavesNoRegion() { - val regions = nativeListTouchableTextRegions( - lines = listOf(NativeListTextLine(start = 0, end = 8, left = 0f, top = 0f, right = 55f, bottom = 20f)), - textStart = 8, textStartX = 0f, slop = 8f, - ) + fun aLineWithoutTouchableTextLeavesNoRegion() { + val none = regions(NativeListTextLine(top = 0f, bottom = 20f, touchable = emptyList(), plain = listOf(run(0f, 55f)))) - assertTrue(regions.isEmpty()) + assertTrue(none.isEmpty()) } // `descriptionActionStart` is a UTF-16 offset into the caller's string. It is @@ -101,7 +140,7 @@ class NativeListDescriptionTouchPolicyTest { assertEquals(label.length, nativeListDisplayOffset(label, Long.MAX_VALUE, foldsLineBreaks = true)) // The emoji takes two UTF-16 units, as in the JavaScript string. - val emojiPrefix = "\uD83D\uDD58 08:48 • " + val emojiPrefix = "🕘 08:48 • " assertEquals(11, emojiPrefix.length) assertEquals(label, "$emojiPrefix$label".substring(nativeListDisplayOffset("$emojiPrefix$label", 11, foldsLineBreaks = false))) diff --git a/native-views/react-native-native-list/docs/SPEC.md b/native-views/react-native-native-list/docs/SPEC.md index 490708e38..c82d2c521 100644 --- a/native-views/react-native-native-list/docs/SPEC.md +++ b/native-views/react-native-native-list/docs/SPEC.md @@ -1809,13 +1809,23 @@ its wording; a caller that composes `prefix + label` records `prefix.length`. 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 lines. 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. iOS and Android widen each line by 8 units. - 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. +- 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 @@ -1823,7 +1833,10 @@ its wording; a caller that composes `prefix + label` records `prefix.length`. 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. + 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 diff --git a/native-views/react-native-native-list/ios/NativeListTextLabel.swift b/native-views/react-native-native-list/ios/NativeListTextLabel.swift index 271eb60c7..53f01619a 100644 --- a/native-views/react-native-native-list/ios/NativeListTextLabel.swift +++ b/native-views/react-native-native-list/ios/NativeListTextLabel.swift @@ -11,11 +11,12 @@ class NativeListTextLabel: UILabel { var touchableTextStart: Int? private static let touchSlop = CGSize(width: 8, height: 6) - /// One rect per laid-out line that holds touchable text, in label coordinates. - /// The label's own layout is not public, so the lines come from a text - /// container with the label's width, line cap and truncation. + /// 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 > 0, + guard let start = touchableTextStart, let attributed = attributedText, attributed.length > start, bounds.width > 0 else { return [] } let storage = NSTextStorage(attributedString: attributed) @@ -35,28 +36,60 @@ class NativeListTextLabel: UILabel { originY = alignment == "top" ? 0 : alignment == "bottom" ? bounds.height - textHeight : originY } originY += rowOffsetY - var lines: [(used: CGRect, characters: NSRange)] = [] + var lines: [CGRect] = [] + var visibleEnd = attributed.length manager.enumerateLineFragments(forGlyphRange: glyphs) { _, usedRect, _, lineGlyphs, _ in - lines.append( - (usedRect, manager.characterRange(forGlyphRange: lineGlyphs, actualGlyphRange: nil))) + 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 } - return lines.enumerated().compactMap { index, line in - guard NSMaxRange(line.characters) > start else { return nil } - var rect = line.used - if line.characters.location < start { - let touchable = NSRange(location: start, length: NSMaxRange(line.characters) - start) - rect = manager.boundingRect( - forGlyphRange: manager.glyphRange(forCharacterRange: touchable, actualCharacterRange: nil), - in: container) + 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) } } - // The slop widens every line. Vertically it grows only past the first - // and last line of the whole layout, so it never reaches into another - // line, including one that holds no touchable text. - let top = index == 0 ? Self.touchSlop.height : 0 - let bottom = index == lines.count - 1 ? Self.touchSlop.height : 0 + // 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: rect.minX - Self.touchSlop.width, y: rect.minY + originY - top, - width: rect.width + Self.touchSlop.width * 2, height: rect.height + top + bottom) + x: minX, y: run.minY + originY - top, width: maxX - minX, + height: run.height + top + bottom) } } 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 03e132f30..9cbcc5b98 100644 --- a/native-views/react-native-native-list/ios/tests/NativeListActivityPresentationTests.swift +++ b/native-views/react-native-native-list/ios/tests/NativeListActivityPresentationTests.swift @@ -117,9 +117,11 @@ final class NativeListActivityPresentationTests: XCTestCase { let timedText = try XCTUnwrap(timed.touchableTextRegions.first) XCTAssertEqual(timed.touchableTextRegions.count, 1) XCTAssertGreaterThan(timed.bounds.width, timedText.maxX + 40) - XCTAssertEqual(timedText.width, labelText.width, accuracy: 1) + // 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)) - XCTAssertTrue(hit(timed, x: timedText.minX + 12)) + 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)) @@ -129,9 +131,10 @@ final class NativeListActivityPresentationTests: XCTestCase { 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, accuracy: 1) + XCTAssertEqual(emojiText.width, labelText.width - 8, accuracy: 1) XCTAssertFalse(hit(emoji, x: 4)) - XCTAssertTrue(hit(emoji, x: emojiText.minX + 12)) + 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. @@ -215,6 +218,98 @@ final class NativeListActivityPresentationTests: XCTestCase { 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() { 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 index b5e0c7448..314ccad8d 100644 --- a/native-views/react-native-native-list/native-tests/android/NativeListDescriptionActionTouchTest.kt +++ b/native-views/react-native-native-list/native-tests/android/NativeListDescriptionActionTouchTest.kt @@ -68,20 +68,49 @@ class NativeListDescriptionActionTouchTest : InstrumentationTestCase() { val prefix = "08:48 • " val description = bind("${prefix}Router • V2", "address-info", prefix.length) val text = textRegion(description) - assertTrue(text.left + slop() > dp(20)) + assertTrue(text.left > dp(20)) assertEquals(listOf("press"), tap(description, dp(4))) - assertEquals(listOf("address-info:description"), tap(description, text.left + slop() + 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 + slop() + 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))) } @@ -156,6 +185,9 @@ class NativeListDescriptionActionTouchTest : InstrumentationTestCase() { 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 } 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 3970c649c..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 @@ -63,11 +63,14 @@ not run JavaScript press handlers or establish physical-device gesture feel. The same build command includes `NativeListDescriptionActionTouchTest`. Run it with `-e class com.margelo.nitro.nativelist.NativeListDescriptionActionTouchTest` -and require `OK (5 tests)`. It binds rich Activity rows in a standalone +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, UTF-16 -offsets behind an emoji prefix, a start at or past the end, 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. +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.