Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -98,12 +98,20 @@ internal class NativeListActivityDetailsView(private val reactContext: ThemedRea
setClipping(nativeListActivityHostClips(leadingOverhangs))
amounts.layoutParams = if (table) LayoutParams(0, -2, 1f).apply { marginStart = gap } else LayoutParams(-2, -2).apply { marginStart = gap }
text(title, data.optString("title"), style.optJSONObject("title"), 16f, color("primary", theme), 24, "medium")
text(description, data.optString("description"), style.optJSONObject("description"), 14f, color("secondary", theme), 20, lines = 2)
val descriptionText = text(description, data.optString("description"), style.optJSONObject("description"), 14f, color("secondary", theme), 20, lines = 2)
text(status, data.optString("status"), style.optJSONObject("status"), 12f, color("secondary", theme), 16)
description.setOnClickListener(null)
val descriptionKey = data.optString("descriptionActionKey")
description.isClickable = descriptionKey.isNotEmpty()
if (descriptionKey.isNotEmpty()) description.setOnClickListener { onAction?.invoke(descriptionKey, description, "description", 0) }
// The view spans the identity column, so with an action only its text from
// the caller's `descriptionActionStart` on takes touches. The start is
// never read out of the string, and one at the end leaves no action.
val actionStart =
if (descriptionKey.isEmpty()) null
else descriptionText.displayOffset(data.optLong("descriptionActionStart"), data.optString("description"))
val hasActionText = actionStart != null && actionStart < descriptionText.text.length
description.touchableTextStart = actionStart
description.isClickable = hasActionText
if (hasActionText) description.setOnClickListener { onAction?.invoke(descriptionKey, description, "description", 0) }
for (view in listOf(description, status)) (view.layoutParams as LayoutParams).topMargin = if (style.has("lineGap")) px(style.optDouble("lineGap")) else 0
badges.forEach(titleLine::removeView); badges.clear()
val badgeData = data.optJSONArray("badges")
Expand Down Expand Up @@ -172,6 +180,7 @@ internal class NativeListActivityDetailsView(private val reactContext: ThemedRea
}
fun recycle() {
visual.recycle(); visual.visibility = VISIBLE; amountViews.forEach { it.recycle() }; description.setOnClickListener(null); actions.removeAllViews()
description.touchableTextStart = null
leadingOverhangs = false
setClipping(true)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,66 @@ internal fun nativeListLeadingVisualOverhangsFrame(
*/
internal fun nativeListActivityHostClips(leadingOverhangs: Boolean): Boolean = !leadingOverhangs

/** A one-line text view shows each line break of its text as one space. */
internal fun nativeListFoldLineBreaks(text: String): String = text.replace(Regex("\\r\\n|[\\r\\n]"), " ")

/**
* Offset into the displayed text for [sourceOffset], a UTF-16 offset into the
* caller's [source], kept within the text. Folding line breaks
* ([nativeListFoldLineBreaks]) moves every offset after a CRLF. The offset is a
* Long because JSON carries any safe integer; narrowing it first would wrap a
* value past Int range instead of clamping it to the end.
*/
internal fun nativeListDisplayOffset(source: String, sourceOffset: Long, foldsLineBreaks: Boolean): Int {
val clamped = sourceOffset.coerceIn(0L, source.length.toLong()).toInt()
return if (foldsLineBreaks) nativeListFoldLineBreaks(source.substring(0, clamped)).length else clamped
}

/** A horizontal run of laid-out text on one line, in view coordinates. */
internal data class NativeListTextRun(val left: Float, val right: Float)

/**
* One laid-out line of a text view, in view coordinates: its vertical extent,
* the runs of [touchable] text and the runs of [plain] text before it. A line
* holds one run of each, or several where mixed-direction text puts plain text
* between touchable text.
*/
internal data class NativeListTextLine(
val top: Float,
val bottom: Float,
val touchable: List<NativeListTextRun>,
val plain: List<NativeListTextRun> = emptyList(),
)

internal data class NativeListTouchRegion(val left: Float, val top: Float, val right: Float, val bottom: Float) {
fun contains(x: Float, y: Float): Boolean = x in left..right && y in top..bottom
}

/** Runs are read back from pixel regions, so neighbours can be a pixel apart. */
private const val TEXT_RUN_EDGE = 1f

/**
* Parts of a stretched text view that take touches: every run of touchable
* text, widened by [slop] into blank space only. The widening stops at plain
* text on the same line, so text before the touchable text never takes the
* touch, however narrow it is. Touches outside the regions fall through to the
* row behind the view (OK-67219).
*/
internal fun nativeListTouchableTextRegions(
lines: List<NativeListTextLine>,
slop: Float,
): List<NativeListTouchRegion> = lines.flatMap { line ->
line.touchable.map { run ->
var left = run.left - slop
var right = run.right + slop
for (other in line.plain) {
if (other.right <= run.left + TEXT_RUN_EDGE) left = maxOf(left, other.right)
if (other.left >= run.right - TEXT_RUN_EDGE) right = minOf(right, other.left)
}
NativeListTouchRegion(left, line.top, right, line.bottom)
}
}

internal data class NativeListSlotFrame(val x: Int, val y: Int, val width: Int, val height: Int)

/** Side of one member of an Activity token pair inside a [frame]-unit box (24 in 40). */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ internal data class NativeListResolvedText(
val gravity: Int,
val offset: Float,
) {
/** Offset into [text] for a UTF-16 offset into the [source] it was resolved from. */
fun displayOffset(sourceOffset: Long, source: String): Int =
nativeListDisplayOffset(source, sourceOffset, foldsLineBreaks = lines == 1 && explicitTruncation)

fun bind(view: NativeListTextView) {
view.includeFontPadding = false
view.fontFeatureSettings = "tnum"
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,16 @@ package com.margelo.nitro.nativelist
import android.graphics.Canvas
import android.graphics.DashPathEffect
import android.graphics.Paint
import android.graphics.Path
import android.graphics.Rect
import android.graphics.RectF
import android.graphics.Region
import android.graphics.RegionIterator
import android.text.Layout
import android.view.MotionEvent
import android.widget.TextView
import kotlin.math.ceil
import kotlin.math.floor

internal open class NativeListTextView(context: android.content.Context) : TextView(context) {
var helpBindingGeneration = 0
Expand Down Expand Up @@ -33,9 +40,73 @@ internal open class NativeListTextView(context: android.content.Context) : TextV
)
}

/**
* Character offset the touchable text starts at. `null` keeps the view's own
* hit testing, its whole bounds. With an offset only the drawn text from
* there on takes touches, plus a small horizontal slop, so text before the
* offset and the unused width of a stretched view fall through to the row
* behind it: `0` covers all of the text, the text length leaves nothing to
* touch.
*/
var touchableTextStart: Int? = null

val touchableTextRegions: List<NativeListTouchRegion>
get() {
val textStart = touchableTextStart ?: return emptyList()
val textLayout = layout ?: return emptyList()
// Lines past the line cap are laid out but never drawn.
val count = minOf(textLayout.lineCount, maxLines.takeIf { it > 0 } ?: Int.MAX_VALUE)
if (count == 0) return emptyList()
val originX = totalPaddingLeft.toFloat()
val originY = totalPaddingTop + opticalOffsetY
val lines = (0 until count).map { line ->
val lineStart = textLayout.getLineStart(line)
val lineEnd = textLayout.getLineEnd(line)
// An ellipsis hides the rest of its line. Once it hides the touchable
// text as well it also stands for plain text, so nothing is left to touch.
val visibleEnd =
if (textLayout.getEllipsisCount(line) > 0) lineStart + textLayout.getEllipsisStart(line) else lineEnd
val touchableStart = maxOf(textStart, lineStart)
NativeListTextLine(
// The outer lines also take the view's own vertical padding.
top = if (line == 0) 0f else originY + textLayout.getLineTop(line),
bottom = if (line == count - 1) height.toFloat() else originY + textLayout.getLineBottom(line),
touchable =
if (touchableStart < visibleEnd) textRuns(textLayout, line, touchableStart, lineEnd, originX)
else emptyList(),
plain = textRuns(textLayout, line, lineStart, minOf(textStart, lineEnd), originX),
)
}
return nativeListTouchableTextRegions(lines, TOUCH_SLOP_DP * resources.displayMetrics.density)
}

/**
* Horizontal extents the layout gives characters `[from, to)` of [line]: the
* layout's own selection, so mixed-direction text yields one run per
* direction run instead of one box around all of them.
*/
private fun textRuns(textLayout: Layout, line: Int, from: Int, to: Int, originX: Float): List<NativeListTextRun> {
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<NativeListTextRun>()
val iterator = RegionIterator(Region().apply { setPath(selection, lineBounds) })
val run = Rect()
while (iterator.next(run)) runs += NativeListTextRun(originX + run.left, originX + run.right)
return runs
}

override fun onTouchEvent(event: MotionEvent): Boolean {
if (primaryHelpOnly && event.actionMasked == MotionEvent.ACTION_DOWN &&
helpAnchorBounds?.contains(event.x, event.y) != true) return false
if (touchableTextStart != null && event.actionMasked == MotionEvent.ACTION_DOWN &&
touchableTextRegions.none { it.contains(event.x, event.y) }) return false
if (guardsHelpTouches) {
if (event.actionMasked == MotionEvent.ACTION_DOWN) helpDownGeneration = helpBindingGeneration
if (event.actionMasked == MotionEvent.ACTION_UP && helpDownGeneration != helpBindingGeneration) {
Expand Down Expand Up @@ -76,4 +147,8 @@ internal open class NativeListTextView(context: android.content.Context) : TextV
drawHelpUnderline(canvas)
canvas.restoreToCount(checkpoint)
}

private companion object {
const val TOUCH_SLOP_DP = 8f
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
package com.margelo.nitro.nativelist

import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test

class NativeListDescriptionTouchPolicyTest {
private fun hit(regions: List<NativeListTouchRegion>, x: Float, y: Float) = regions.any { it.contains(x, y) }

private fun run(left: Float, right: Float) = NativeListTextRun(left, right)

private fun regions(vararg lines: NativeListTextLine) = nativeListTouchableTextRegions(lines.toList(), slop = 8f)

// The description view spans the identity column, so a tap anywhere on its
// line used to open the description action. Only the text opens it now; the
// blank rest of the line belongs to the row press (OK-67219).
@Test
fun onlyTheDrawnTextTakesTouches() {
val text = regions(NativeListTextLine(top = 0f, bottom = 20f, touchable = listOf(run(0f, 60f))))

assertTrue(hit(text, 30f, 10f))
// The slop reaches into the blank on both sides of the text.
assertTrue(hit(text, 66f, 10f))
assertTrue(hit(text, -6f, 10f))
assertFalse(hit(text, 120f, 10f))
}

// The caller states where the action text starts; the text before it, a
// time for one, is not part of the action.
@Test
fun textBeforeTheStartIsNotPartOfTheAction() {
val ltr = regions(
NativeListTextLine(top = 0f, bottom = 20f, touchable = listOf(run(50f, 160f)), plain = listOf(run(0f, 50f))),
)
assertFalse(hit(ltr, 20f, 10f))
assertTrue(hit(ltr, 100f, 10f))

// Right to left the plain text sits on the right of the touchable text.
val rtl = regions(
NativeListTextLine(top = 0f, bottom = 20f, touchable = listOf(run(40f, 150f)), plain = listOf(run(150f, 200f))),
)
assertTrue(hit(rtl, 100f, 10f))
assertFalse(hit(rtl, 180f, 10f))
}

// The slop is for blank space. It must not reach into plain text beside the
// touchable text, or a prefix narrower than the slop, like the "i" of
// "iRouter", would open the action it is not part of.
@Test
fun theSlopStopsAtPlainTextBesideTheTouchableText() {
val short = regions(
NativeListTextLine(top = 0f, bottom = 20f, touchable = listOf(run(3f, 46f)), plain = listOf(run(0f, 3f))),
)
assertFalse(hit(short, 1.5f, 10f))
assertFalse(hit(short, -4f, 10f))
assertTrue(hit(short, 4f, 10f))
assertTrue(hit(short, 52f, 10f))
assertEquals(3f, short.single().left)
assertEquals(54f, short.single().right)

// Neighbouring runs read back from pixel regions may be a pixel apart.
val apart = regions(
NativeListTextLine(top = 0f, bottom = 20f, touchable = listOf(run(4f, 46f)), plain = listOf(run(0f, 3f))),
)
assertEquals(3f, apart.single().left)
}

// Mixed-direction text can split one logical suffix into several visual
// runs with plain text between them: "ABC אבג XYZ" from the last Hebrew
// letter on draws that letter left of the two plain ones. Each run is its
// own region, and the plain text between them takes no touches.
@Test
fun aSuffixSplitByMixedDirectionTextIsSeveralRuns() {
val mixed = regions(
NativeListTextLine(
top = 0f, bottom = 20f,
touchable = listOf(run(32f, 38f), run(55f, 86f)),
plain = listOf(run(0f, 32f), run(38f, 55f)),
),
)

assertEquals(2, mixed.size)
assertFalse(hit(mixed, 16f, 10f))
assertTrue(hit(mixed, 35f, 10f))
assertFalse(hit(mixed, 46f, 10f))
assertTrue(hit(mixed, 70f, 10f))
// Only the outer edge of the last run faces blank space.
assertTrue(hit(mixed, 92f, 10f))
assertEquals(32f, mixed[0].left)
assertEquals(38f, mixed[0].right)
assertEquals(55f, mixed[1].left)
}

// A narrow row wraps the description. The time stays outside the action on
// its line, while the address is hit on both lines, also at the x the time
// occupies one line above.
@Test
fun aWrappedDescriptionKeepsTheTimeOutsideTheAction() {
val wrapped = regions(
NativeListTextLine(top = 0f, bottom = 20f, touchable = listOf(run(55f, 110f)), plain = listOf(run(0f, 55f))),
NativeListTextLine(top = 20f, bottom = 40f, touchable = listOf(run(0f, 100f))),
)
assertFalse(hit(wrapped, 20f, 10f))
assertTrue(hit(wrapped, 80f, 10f))
assertTrue(hit(wrapped, 20f, 30f))
assertFalse(hit(wrapped, 130f, 30f))

// The whole time sits on the first line: that line takes no touches at all.
val timeOnItsOwnLine = regions(
NativeListTextLine(top = 0f, bottom = 20f, touchable = emptyList(), plain = listOf(run(0f, 55f))),
NativeListTextLine(top = 20f, bottom = 40f, touchable = listOf(run(0f, 100f))),
)
assertFalse(hit(timeOnItsOwnLine, 20f, 10f))
// Nor does the address line reach up into it.
assertFalse(hit(timeOnItsOwnLine, 20f, 19f))
assertTrue(hit(timeOnItsOwnLine, 20f, 30f))
}

// A start at the end of the text leaves nothing to touch.
@Test
fun aLineWithoutTouchableTextLeavesNoRegion() {
val none = regions(NativeListTextLine(top = 0f, bottom = 20f, touchable = emptyList(), plain = listOf(run(0f, 55f))))

assertTrue(none.isEmpty())
}

// `descriptionActionStart` is a UTF-16 offset into the caller's string. It is
// kept within the text, and follows the line breaks a one-line view folds.
@Test
fun theCallersStartIsMappedOntoTheDisplayedText() {
val label = "Router • V2"
assertEquals(0, nativeListDisplayOffset(label, 0, foldsLineBreaks = false))
assertEquals(8, nativeListDisplayOffset("08:48 • $label", 8, foldsLineBreaks = false))
assertEquals(0, nativeListDisplayOffset(label, -3, foldsLineBreaks = false))
assertEquals(label.length, nativeListDisplayOffset(label, 99, foldsLineBreaks = false))
// Any safe integer arrives over JSON. One past Int range still clamps to
// the end; narrowed to Int first it would wrap to 0, the whole text.
assertEquals(label.length, nativeListDisplayOffset(label, 4_294_967_296L, foldsLineBreaks = false))
assertEquals(label.length, nativeListDisplayOffset(label, Long.MAX_VALUE, foldsLineBreaks = true))

// The emoji takes two UTF-16 units, as in the JavaScript string.
val emojiPrefix = "🕘 08:48 • "
assertEquals(11, emojiPrefix.length)
assertEquals(label, "$emojiPrefix$label".substring(nativeListDisplayOffset("$emojiPrefix$label", 11, foldsLineBreaks = false)))

val broken = "08:48\r\n• Router"
assertEquals("08:48 • Router", nativeListFoldLineBreaks(broken))
assertEquals(8, nativeListDisplayOffset(broken, 9, foldsLineBreaks = true))
assertEquals(9, nativeListDisplayOffset(broken, 9, foldsLineBreaks = false))
assertEquals(14, nativeListDisplayOffset(broken, 99, foldsLineBreaks = true))
}
}
5 changes: 4 additions & 1 deletion native-views/react-native-native-list/docs/ROW_TEMPLATES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading