@onekeyfe/react-native-native-list 6.7.0-alpha.466 → 6.7.0-alpha.475

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -31,6 +31,8 @@ internal class NativeListIdentityRowView(context: ThemedReactContext, fonts: Nat
31
31
  private val titleLine = PackedTitleLineLayout(context)
32
32
  private val title = NativeListTextView(context)
33
33
  private val titleIcon = OneKeyIconView(context)
34
+ private val titleLeadingIcon = OneKeyIconView(context)
35
+ private val titleSegments = NativeListTitleSegmentsView(context)
34
36
  private var titleImage: NativeListImageSlot? = null
35
37
  private val subtitle = NativeListTextView(context)
36
38
  private val tertiary = NativeListTextView(context)
@@ -109,8 +111,13 @@ internal class NativeListIdentityRowView(context: ThemedReactContext, fonts: Nat
109
111
  mainColumn.gravity = Gravity.CENTER_VERTICAL
110
112
  titleLine.orientation = HORIZONTAL
111
113
  titleLine.gravity = Gravity.CENTER_VERTICAL
114
+ titleLine.addView(titleLeadingIcon, LayoutParams(dp(16), dp(16)).apply { marginEnd = dp(6) })
112
115
  titleLine.addView(title, LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f))
116
+ titleLine.addView(titleSegments, LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f))
113
117
  titleLine.addView(titleIcon, LayoutParams(dp(20), dp(20)).apply { marginStart = dp(4) })
118
+ titleLine.titleChild = title
119
+ titleLeadingIcon.visibility = GONE
120
+ titleSegments.visibility = GONE
114
121
  titleLine.addView(badgeLine)
115
122
  trailingColumn.onAction = { key, view, slot, target ->
116
123
  emitAction(key, view, "trailingAccessory", slot, target, trailingColumn.anchorInset(view))
@@ -223,6 +230,12 @@ internal class NativeListIdentityRowView(context: ThemedReactContext, fonts: Nat
223
230
  titleIcon.visibility = GONE
224
231
  titleIcon.contentDescription = null
225
232
  titleIcon.setOnClickListener(null)
233
+ titleLeadingIcon.visibility = GONE
234
+ titleLeadingIcon.contentDescription = null
235
+ titleSegments.visibility = GONE
236
+ titleSegments.clearRuns()
237
+ titleSegments.layoutParams = LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f)
238
+ titleLine.titleChild = title
226
239
  for (view in listOf(title, subtitle, tertiary, badgeLine)) {
227
240
  view.text = ""
228
241
  view.visibility = GONE
@@ -343,6 +356,46 @@ internal class NativeListIdentityRowView(context: ThemedReactContext, fonts: Nat
343
356
  }
344
357
  // Legacy: overhanging selector icons/checkboxes must not be clipped by row padding.
345
358
  if (trailingColumn.parent === this && trailingColumn.requestsUnclippedHost) clipToPadding = false
359
+ if (titleSegments.visibility == VISIBLE) bindTitleRuns(item, theme)
360
+ }
361
+
362
+ // Runs take the title's final text appearance and color unless they set
363
+ // their own tone or weight.
364
+ private fun bindTitleRuns(item: NativeListItem, theme: JSONObject?) {
365
+ titleSegments.typeface = title.typeface
366
+ titleSegments.setTextSize(android.util.TypedValue.COMPLEX_UNIT_PX, title.textSize)
367
+ titleSegments.includeFontPadding = title.includeFontPadding
368
+ titleSegments.letterSpacing = title.letterSpacing
369
+ titleSegments.opticalOffsetY = title.opticalOffsetY
370
+ titleSegments.maxLines = 1
371
+ titleSegments.ellipsize = TextUtils.TruncateAt.END
372
+ TextViewCompat.setLineHeight(titleSegments, title.lineHeight)
373
+ val baseColor = title.currentTextColor
374
+ titleSegments.setTextColor(baseColor)
375
+ val segments = item.json.optJSONArray("titleSegments") ?: return
376
+ val runs =
377
+ (0 until segments.length()).mapNotNull { index ->
378
+ val segment = segments.optJSONObject(index) ?: return@mapNotNull null
379
+ NativeListTitleSegmentsView.Run(
380
+ text = segment.optString("text"),
381
+ typeface =
382
+ when (segment.optString("fontWeight")) {
383
+ "medium" -> fonts.medium(context)
384
+ "regular" -> fonts.regular(context)
385
+ else -> null
386
+ },
387
+ color =
388
+ when (segment.optString("tone")) {
389
+ "secondary" -> color(theme, "secondaryText", "#0000009B")
390
+ "primary" -> color(theme, "primaryText", "#000000DF")
391
+ else -> baseColor
392
+ },
393
+ shrink = segment.optBoolean("shrink", false),
394
+ maxWidthRatio =
395
+ if (segment.has("maxWidthRatio")) segment.optDouble("maxWidthRatio").toFloat() else null,
396
+ )
397
+ }
398
+ titleSegments.setRuns(runs, item.json.optString("title"))
346
399
  }
347
400
 
348
401
  private fun styleGap(column: LinearLayout, gap: Int) {
@@ -476,7 +529,8 @@ internal class NativeListIdentityRowView(context: ThemedReactContext, fonts: Nat
476
529
  val imageWidth = titleImage?.view?.takeIf { it.visibility == VISIBLE }?.let {
477
530
  it.layoutParams.width + dp(4)
478
531
  } ?: 0
479
- val icon = (if (titleIcon.visibility == VISIBLE) dp(24) else 0) + imageWidth
532
+ val icon = (if (titleIcon.visibility == VISIBLE) dp(24) else 0) + imageWidth +
533
+ (if (titleLeadingIcon.visibility == VISIBLE) dp(22) else 0)
480
534
  (inner * ratio).roundToInt()
481
535
  .minus(leading.width + leading.marginEnd + icon)
482
536
  .coerceAtLeast(0)
@@ -487,9 +541,10 @@ internal class NativeListIdentityRowView(context: ThemedReactContext, fonts: Nat
487
541
  super.onMeasure(widthMeasureSpec, heightMeasureSpec)
488
542
  if (titleSuffixLabels.isNotEmpty()) {
489
543
  val fixedWidth =
490
- (1 until titleLine.childCount).sumOf { index ->
544
+ (0 until titleLine.childCount).sumOf { index ->
491
545
  val view = titleLine.getChildAt(index)
492
- if (view.visibility == GONE || titleSuffixLabels.any { it === view }) 0
546
+ if (view.visibility == GONE || view === titleLine.titleChild ||
547
+ titleSuffixLabels.any { it === view }) 0
493
548
  else {
494
549
  val margins = view.layoutParams as MarginLayoutParams
495
550
  view.measuredWidth + margins.leftMargin + margins.rightMargin
@@ -753,6 +808,35 @@ internal class NativeListIdentityRowView(context: ThemedReactContext, fonts: Nat
753
808
  titleLine.packsChildrenAtStart = true
754
809
  title.ellipsize = TextUtils.TruncateAt.END
755
810
  showText(title, item.json.optString("title"), item.json.optInt("titleLines", 1))
811
+ // Runs replace the drawn title except where `title` itself is highlighted;
812
+ // their content is bound once the title style is final.
813
+ if (nativeListShowsTitleRuns(
814
+ item.json.optString("presentation"),
815
+ item.json.optJSONArray("titleSegments")?.length() ?: 0,
816
+ item.json.optJSONArray("titleMatch")?.length() ?: 0,
817
+ )
818
+ ) {
819
+ title.visibility = GONE
820
+ titleSegments.visibility = VISIBLE
821
+ titleLine.titleChild = titleSegments
822
+ }
823
+ val leadingIcon = item.json.optJSONObject("titleLeadingIcon")
824
+ ?.takeIf { nativeListAllowsTitleDecorations(item.json.optString("presentation")) }
825
+ leadingIcon?.let { icon ->
826
+ titleLeadingIcon.iconName = icon.optString("name")
827
+ titleLeadingIcon.glyphSizeDp = 16
828
+ titleLeadingIcon.useSourceScale = sourceScale
829
+ titleLeadingIcon.tintColor = safeColor(
830
+ icon.optString("tintColor").takeIf(String::isNotEmpty),
831
+ color(theme, "iconSubdued", "#00000072"),
832
+ )
833
+ titleLeadingIcon.contentDescription =
834
+ icon.optString("accessibilityLabel").takeIf(String::isNotEmpty)
835
+ titleLeadingIcon.importantForAccessibility =
836
+ if (titleLeadingIcon.contentDescription == null) View.IMPORTANT_FOR_ACCESSIBILITY_NO
837
+ else View.IMPORTANT_FOR_ACCESSIBILITY_YES
838
+ titleLeadingIcon.visibility = VISIBLE
839
+ }
756
840
  item.json.optJSONArray("titleSuffixes")?.let { suffixes ->
757
841
  for (index in 0 until suffixes.length()) {
758
842
  val suffix = suffixes.optJSONObject(index) ?: continue
@@ -26,6 +26,8 @@ import com.facebook.react.modules.network.OkHttpClientProvider
26
26
  import com.facebook.react.uimanager.ThemedReactContext
27
27
  import okhttp3.JavaNetCookieJar
28
28
  import org.json.JSONObject
29
+ import com.margelo.nitro.onekeyimage.OneKeyMediaPreviewCache
30
+ import java.util.UUID
29
31
 
30
32
  /**
31
33
  * Uses Media3 like native Video, but never starts playback or requests audio focus. A player
@@ -35,9 +37,10 @@ import org.json.JSONObject
35
37
  internal class NativeListMediaPreviewSlot(private val context: ThemedReactContext) {
36
38
  val view: FrameLayout = object : FrameLayout(context) {
37
39
  override fun onAttachedToWindow() { super.onAttachedToWindow(); observeViewport(); updateVisibility() }
38
- override fun onDetachedFromWindow() { stopObservingViewport(); releasePlayer(); super.onDetachedFromWindow() }
40
+ override fun onDetachedFromWindow() { stopObservingViewport(); cancelPreview(); super.onDetachedFromWindow() }
41
+ override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh); updateVisibility() }
39
42
  override fun onWindowVisibilityChanged(visibility: Int) { super.onWindowVisibilityChanged(visibility); updateVisibility() }
40
- override fun onVisibilityAggregated(isVisible: Boolean) { super.onVisibilityAggregated(isVisible); if (isVisible) updateVisibility() else releasePlayer() }
43
+ override fun onVisibilityAggregated(isVisible: Boolean) { super.onVisibilityAggregated(isVisible); if (isVisible) updateVisibility() else cancelPreview() }
41
44
  }
42
45
  private val image = NativeListImageSlot(context)
43
46
  private val video = AspectRatioFrameLayout(context)
@@ -51,6 +54,10 @@ internal class NativeListMediaPreviewSlot(private val context: ThemedReactContex
51
54
  private var completion: ((Boolean) -> Unit)? = null
52
55
  private var pendingCompletion: Runnable? = null
53
56
  private var player: ExoPlayer? = null
57
+ private var subscription: OneKeyMediaPreviewCache.Subscription? = null
58
+ private var extractionLease: UUID? = null
59
+ private var requestedEdge: Int? = null
60
+ private val previewCache by lazy { OneKeyMediaPreviewCache.get(context) }
54
61
  private var resumeVideo: (() -> Unit)? = null
55
62
  private var viewportObserver: ViewTreeObserver? = null
56
63
  private val visibleRect = Rect()
@@ -99,7 +106,7 @@ internal class NativeListMediaPreviewSlot(private val context: ThemedReactContex
99
106
  val candidate = candidateGeneration
100
107
  resumeVideo = null
101
108
  stopObservingViewport()
102
- releasePlayer()
109
+ cancelPreview()
103
110
  if (attempt >= order.size) {
104
111
  result = false
105
112
  completion?.invoke(false)
@@ -133,8 +140,36 @@ internal class NativeListMediaPreviewSlot(private val context: ThemedReactContex
133
140
  val uri = source.optString("uri")
134
141
  if (uri.isBlank()) { finished(false); return }
135
142
  val headers = source.optJSONObject("headers")?.let { values -> values.keys().asSequence().associateWith { values.optString(it) } } ?: emptyMap()
143
+ val fitKey = if ((fit ?: source.optString("contentFit")) == "cover") "cover" else "contain"
136
144
  resumeVideo = start@{
137
- if (epoch != token || candidateGeneration != candidate || player != null) return@start
145
+ if (epoch != token || candidateGeneration != candidate || subscription != null || frame.drawable != null ||
146
+ video.width <= 0 || video.height <= 0) return@start
147
+ val edge = OneKeyMediaPreviewCache.targetEdge(maxOf(view.width, view.height))
148
+ requestedEdge = edge
149
+ subscription = previewCache.request(uri, headers, edge, fitKey, source.optString("cachePolicy", "memory-disk"),
150
+ onImage = { still ->
151
+ if (epoch == token && candidateGeneration == candidate) {
152
+ subscription = null
153
+ video.setAspectRatio(still.width.toFloat() / still.height)
154
+ frame.setImageBitmap(still); frame.visibility = View.VISIBLE
155
+ stopObservingViewport(); finished(true)
156
+ }
157
+ }, onExtract = { lease ->
158
+ if (epoch == token && candidateGeneration == candidate) {
159
+ extractionLease = lease
160
+ updateVisibility()
161
+ if (extractionLease == lease && requestedEdge == edge) startPlayer(uri, headers, token, candidate, edge, lease)
162
+ }
163
+ }, onRevoked = { extractionLease = null; releasePlayer() },
164
+ onFailure = {
165
+ if (epoch == token && candidateGeneration == candidate) { subscription = null; finished(false) }
166
+ })
167
+ }
168
+ observeViewport()
169
+ updateVisibility()
170
+ }
171
+
172
+ private fun startPlayer(uri: String, headers: Map<String, String>, token: Int, candidate: Int, edge: Int, lease: UUID) {
138
173
  playerGeneration++
139
174
  val generation = playerGeneration
140
175
  try {
@@ -158,10 +193,11 @@ internal class NativeListMediaPreviewSlot(private val context: ThemedReactContex
158
193
  next.addListener(object : Player.Listener {
159
194
  override fun onRenderedFirstFrame() {
160
195
  if (playerGeneration != generation) return
161
- finished(true, generation)
162
- captureFirstFrame(token, candidate, generation, FIRST_FRAME_CAPTURE_ATTEMPTS)
196
+ captureFirstFrame(token, candidate, generation, FIRST_FRAME_CAPTURE_ATTEMPTS, edge, lease)
197
+ }
198
+ override fun onPlayerError(error: PlaybackException) {
199
+ view.post { if (playerGeneration == generation) previewCache.fail(lease) }
163
200
  }
164
- override fun onPlayerError(error: PlaybackException) { if (playerGeneration == generation) finished(false, generation) }
165
201
  override fun onVideoSizeChanged(size: VideoSize) {
166
202
  if (playerGeneration == generation && size.height > 0) video.setAspectRatio(size.width * size.pixelWidthHeightRatio / size.height)
167
203
  }
@@ -170,39 +206,26 @@ internal class NativeListMediaPreviewSlot(private val context: ThemedReactContex
170
206
  next.prepare()
171
207
  next.pause()
172
208
  } catch (_: Exception) {
173
- releasePlayer()
174
- finished(false)
209
+ previewCache.fail(lease)
175
210
  }
176
- }
177
- observeViewport()
178
- updateVisibility()
179
211
  }
180
212
 
181
- /**
182
- * The rendered frame reaches the TextureView asynchronously, so a transparent copy is
183
- * retried on later frames. If no frame can be copied the paused player stays attached.
184
- */
185
- private fun captureFirstFrame(token: Int, candidate: Int, generation: Int, attemptsLeft: Int) {
213
+ /** TextureView requires UI access; request bounded pixels before background encoding. */
214
+ private fun captureFirstFrame(token: Int, candidate: Int, generation: Int, attemptsLeft: Int, edge: Int, lease: UUID) {
186
215
  view.postOnAnimation {
187
216
  if (epoch != token || candidateGeneration != candidate || playerGeneration != generation) return@postOnAnimation
188
- // Releasing first would make the queued success completion drop itself as stale.
189
- if (result != true) {
190
- captureFirstFrame(token, candidate, generation, attemptsLeft)
191
- return@postOnAnimation
192
- }
193
217
  val still = if (texture.isAvailable && texture.width > 0 && texture.height > 0) {
194
- runCatching { texture.getBitmap(texture.width, texture.height) }.getOrNull()
218
+ val scale = minOf(1.0, edge.toDouble() / maxOf(texture.width, texture.height))
219
+ runCatching { texture.getBitmap(maxOf(1, (texture.width * scale).toInt()), maxOf(1, (texture.height * scale).toInt())) }.getOrNull()
195
220
  } else null
196
221
  if (still == null || !hasVisiblePixels(still)) {
197
222
  still?.recycle()
198
- if (attemptsLeft > 1) captureFirstFrame(token, candidate, generation, attemptsLeft - 1)
223
+ if (attemptsLeft > 1) captureFirstFrame(token, candidate, generation, attemptsLeft - 1, edge, lease)
224
+ else previewCache.fail(lease)
199
225
  return@postOnAnimation
200
226
  }
201
- frame.setImageBitmap(still)
202
- frame.visibility = View.VISIBLE
203
- resumeVideo = null
204
- stopObservingViewport()
205
227
  releasePlayer()
228
+ previewCache.complete(lease, still)
206
229
  }
207
230
  }
208
231
 
@@ -213,7 +236,7 @@ internal class NativeListMediaPreviewSlot(private val context: ThemedReactContex
213
236
  }
214
237
 
215
238
  private fun observeViewport() {
216
- if (viewportObserver != null || resumeVideo == null || !view.isAttachedToWindow) return
239
+ if (viewportObserver != null || resumeVideo == null || frame.drawable != null || !view.isAttachedToWindow) return
217
240
  view.viewTreeObserver.takeIf { it.isAlive }?.let {
218
241
  it.addOnScrollChangedListener(scrollListener)
219
242
  it.addOnGlobalLayoutListener(layoutListener)
@@ -230,6 +253,13 @@ internal class NativeListMediaPreviewSlot(private val context: ThemedReactContex
230
253
  viewportObserver = null
231
254
  }
232
255
  private fun updateVisibility() {
256
+ requestedEdge?.let { previous ->
257
+ if (video.width > 0 && video.height > 0 && OneKeyMediaPreviewCache.targetEdge(maxOf(view.width, view.height)) != previous) {
258
+ cancelPreview(); requestedEdge = null
259
+ frame.setImageDrawable(null); frame.visibility = View.GONE; result = null
260
+ observeViewport()
261
+ }
262
+ }
233
263
  var ancestor: View? = view
234
264
  var opaque = true
235
265
  while (ancestor != null) {
@@ -238,7 +268,11 @@ internal class NativeListMediaPreviewSlot(private val context: ThemedReactContex
238
268
  }
239
269
  if (opaque && view.isAttachedToWindow && view.windowVisibility == View.VISIBLE && view.isShown &&
240
270
  view.getGlobalVisibleRect(visibleRect) && !visibleRect.isEmpty) resumeVideo?.invoke()
241
- else releasePlayer()
271
+ else cancelPreview()
272
+ }
273
+ private fun cancelPreview() {
274
+ val previous = subscription; subscription = null
275
+ previewCache.cancel(previous); extractionLease = null; releasePlayer()
242
276
  }
243
277
  private fun releasePlayer() {
244
278
  playerGeneration++
@@ -251,11 +285,12 @@ internal class NativeListMediaPreviewSlot(private val context: ThemedReactContex
251
285
  pendingCompletion = null
252
286
  resumeVideo = null
253
287
  stopObservingViewport()
254
- releasePlayer()
288
+ cancelPreview()
255
289
  image.recycle()
256
290
  image.view.visibility = View.VISIBLE
257
291
  video.visibility = View.GONE
258
292
  video.setAspectRatio(0f)
293
+ requestedEdge = null
259
294
  frame.setImageDrawable(null)
260
295
  frame.visibility = View.GONE
261
296
  identity = null; result = null; completion = null
@@ -109,6 +109,9 @@ internal class PackedTitleLineLayout(context: android.content.Context) : LinearL
109
109
  var packsChildrenAtStart = false
110
110
  // OneKey patch: optional cap for the Market subtitle's localized name.
111
111
  var leadingTextMaxWidth = Int.MAX_VALUE
112
+ // The text view that takes what the other children leave; the first child
113
+ // when unset, so a glyph may precede the title once this names it.
114
+ var titleChild: TextView? = null
112
115
 
113
116
  override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
114
117
  if (!packsChildrenAtStart || childCount < 2) {
@@ -116,13 +119,13 @@ internal class PackedTitleLineLayout(context: android.content.Context) : LinearL
116
119
  return
117
120
  }
118
121
 
119
- val title = getChildAt(0)
122
+ val title = titleChild?.takeIf { it.parent === this } ?: getChildAt(0)
120
123
  val widthMode = MeasureSpec.getMode(widthMeasureSpec)
121
124
  val widthSize = MeasureSpec.getSize(widthMeasureSpec)
122
125
  var accessoryWidth = 0
123
- for (index in 1 until childCount) {
126
+ for (index in 0 until childCount) {
124
127
  val child = getChildAt(index)
125
- if (child.visibility == GONE) continue
128
+ if (child === title || child.visibility == GONE) continue
126
129
  measureChildWithMargins(
127
130
  child,
128
131
  widthMeasureSpec,
@@ -0,0 +1,49 @@
1
+ package com.margelo.nitro.nativelist
2
+
3
+ /**
4
+ * Widths for identity title runs (docs/SPEC.md, "Identity title segments and
5
+ * leading title icon"). A run's base width is its natural width under its cap;
6
+ * the one shrinking run takes what the others leave; runs that do not shrink
7
+ * and still overflow are cut from the end of the line.
8
+ */
9
+ internal fun nativeListTitleSegmentWidths(
10
+ natural: List<Float>,
11
+ shrink: List<Boolean>,
12
+ maxWidthRatio: List<Float?>,
13
+ available: Float,
14
+ ): List<Float> {
15
+ val line = available.coerceAtLeast(0f)
16
+ val widths =
17
+ natural.indices
18
+ .map { index ->
19
+ val width = natural[index].coerceAtLeast(0f)
20
+ val ratio = maxWidthRatio.getOrNull(index)
21
+ if (ratio == null) width else minOf(width, ratio * line)
22
+ }
23
+ .toMutableList()
24
+ val shrinking = shrink.indexOf(true)
25
+ if (shrinking in widths.indices) {
26
+ val others = widths.indices.filter { it != shrinking }.sumOf { widths[it].toDouble() }.toFloat()
27
+ widths[shrinking] = minOf(widths[shrinking], line - others).coerceAtLeast(0f)
28
+ }
29
+ var overflow = widths.sum() - line
30
+ var index = widths.lastIndex
31
+ while (overflow > 0f && index >= 0) {
32
+ val cut = minOf(widths[index], overflow)
33
+ widths[index] -= cut
34
+ overflow -= cut
35
+ index -= 1
36
+ }
37
+ return widths
38
+ }
39
+
40
+ /** Wallet sidebar rows keep the plain title: no runs and no leading glyph (docs/SPEC.md). */
41
+ internal fun nativeListAllowsTitleDecorations(presentation: String): Boolean =
42
+ presentation != "walletSidebar"
43
+
44
+ /**
45
+ * Whether the runs replace `title`: not where `title` itself is highlighted
46
+ * (`titleMatch` indexes it), and never on a wallet sidebar row.
47
+ */
48
+ internal fun nativeListShowsTitleRuns(presentation: String, runCount: Int, matchCount: Int): Boolean =
49
+ runCount > 0 && matchCount == 0 && nativeListAllowsTitleDecorations(presentation)
@@ -0,0 +1,105 @@
1
+ package com.margelo.nitro.nativelist
2
+
3
+ import android.graphics.Typeface
4
+ import android.text.SpannableStringBuilder
5
+ import android.text.Spanned
6
+ import android.text.TextPaint
7
+ import android.text.TextUtils
8
+ import android.text.style.ForegroundColorSpan
9
+ import android.text.style.MetricAffectingSpan
10
+
11
+ /**
12
+ * Identity title runs on one line. The text is rebuilt for each measured width
13
+ * from the widths `nativeListTitleSegmentWidths` allocates, so a run gives up
14
+ * width without the others; accessibility reads the row's `title` instead.
15
+ */
16
+ internal class NativeListTitleSegmentsView(context: android.content.Context) :
17
+ NativeListTextView(context) {
18
+ class Run(
19
+ val text: String,
20
+ // Null keeps the view's typeface, which follows the title's.
21
+ val typeface: Typeface?,
22
+ val color: Int,
23
+ val shrink: Boolean,
24
+ val maxWidthRatio: Float?,
25
+ )
26
+
27
+ private var runs: List<Run> = emptyList()
28
+ private var builtForWidth = -1
29
+
30
+ fun setRuns(runs: List<Run>, spokenText: String) {
31
+ this.runs = runs
32
+ builtForWidth = -1
33
+ contentDescription = spokenText.takeIf(String::isNotEmpty)
34
+ text = runs.joinToString("") { it.text }
35
+ requestLayout()
36
+ }
37
+
38
+ fun clearRuns() {
39
+ runs = emptyList()
40
+ builtForWidth = -1
41
+ contentDescription = null
42
+ text = ""
43
+ }
44
+
45
+ override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
46
+ if (runs.isEmpty()) {
47
+ super.onMeasure(widthMeasureSpec, heightMeasureSpec)
48
+ return
49
+ }
50
+ var outer =
51
+ if (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.UNSPECIFIED) Int.MAX_VALUE
52
+ else MeasureSpec.getSize(widthMeasureSpec)
53
+ if (maxWidth in 0 until outer) outer = maxWidth
54
+ val available =
55
+ if (outer == Int.MAX_VALUE) outer
56
+ else (outer - compoundPaddingLeft - compoundPaddingRight).coerceAtLeast(0)
57
+ if (available != builtForWidth) {
58
+ builtForWidth = available
59
+ // The same width rebuilds the same text, so the relayout this asks for
60
+ // measures once more and stops.
61
+ setText(build(available), BufferType.SPANNABLE)
62
+ }
63
+ super.onMeasure(widthMeasureSpec, heightMeasureSpec)
64
+ // The runs fill what the title line leaves, so a ratio is a share of it.
65
+ if (outer != Int.MAX_VALUE) setMeasuredDimension(outer, measuredHeight)
66
+ }
67
+
68
+ private fun build(available: Int): CharSequence {
69
+ val paints = runs.map { run -> TextPaint(paint).apply { run.typeface?.let { typeface = it } } }
70
+ val natural = runs.mapIndexed { index, run -> paints[index].measureText(run.text) }
71
+ val widths =
72
+ nativeListTitleSegmentWidths(
73
+ natural,
74
+ runs.map { it.shrink },
75
+ runs.map { it.maxWidthRatio },
76
+ if (available == Int.MAX_VALUE) Float.MAX_VALUE else available.toFloat(),
77
+ )
78
+ val built = SpannableStringBuilder()
79
+ runs.forEachIndexed { index, run ->
80
+ val width = widths[index]
81
+ if (width <= 0f) return@forEachIndexed
82
+ val shown =
83
+ if (width >= natural[index]) run.text
84
+ else TextUtils.ellipsize(run.text, paints[index], width, TextUtils.TruncateAt.END)
85
+ if (shown.isEmpty()) return@forEachIndexed
86
+ val start = built.length
87
+ built.append(shown)
88
+ built.setSpan(ForegroundColorSpan(run.color), start, built.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
89
+ run.typeface?.let {
90
+ built.setSpan(TypefaceRunSpan(it), start, built.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
91
+ }
92
+ }
93
+ return built
94
+ }
95
+ }
96
+
97
+ private class TypefaceRunSpan(private val typeface: Typeface) : MetricAffectingSpan() {
98
+ override fun updateMeasureState(paint: TextPaint) {
99
+ paint.typeface = typeface
100
+ }
101
+
102
+ override fun updateDrawState(paint: TextPaint) {
103
+ paint.typeface = typeface
104
+ }
105
+ }
@@ -0,0 +1,80 @@
1
+ package com.margelo.nitro.nativelist
2
+
3
+ import org.junit.Assert.assertEquals
4
+ import org.junit.Assert.assertFalse
5
+ import org.junit.Assert.assertTrue
6
+ import org.junit.Test
7
+
8
+ class NativeListTitleSegmentLayoutTest {
9
+ // Wallet / Account as recipient rows send it: the wallet shrinks, the
10
+ // account is capped at 70% of the line.
11
+ private fun walletFirst(wallet: Float, account: Float, line: Float) =
12
+ nativeListTitleSegmentWidths(
13
+ listOf(wallet, 20f, account),
14
+ listOf(true, false, false),
15
+ listOf(null, null, 0.7f),
16
+ line,
17
+ )
18
+
19
+ private fun assertWidths(expected: List<Float>, actual: List<Float>) {
20
+ assertEquals(expected.size, actual.size)
21
+ expected.zip(actual).forEach { (want, got) -> assertEquals(want, got, 0.001f) }
22
+ }
23
+
24
+ @Test
25
+ fun keepsNaturalWidthsWhenTheyFit() = assertWidths(listOf(80f, 20f, 90f), walletFirst(80f, 90f, 300f))
26
+
27
+ @Test
28
+ fun theShrinkingRunGivesWayFirst() = assertWidths(listOf(130f, 20f, 100f), walletFirst(200f, 100f, 250f))
29
+
30
+ @Test
31
+ fun aCappedRunStopsAtItsShareOfTheLine() = assertWidths(listOf(70f, 20f, 210f), walletFirst(100f, 400f, 300f))
32
+
33
+ @Test
34
+ fun theAccountShrinksWhenTheWalletMustStayWhole() =
35
+ assertWidths(
36
+ listOf(210f, 20f, 70f),
37
+ nativeListTitleSegmentWidths(
38
+ listOf(300f, 20f, 150f),
39
+ listOf(false, false, true),
40
+ listOf(0.7f, null, null),
41
+ 300f,
42
+ ),
43
+ )
44
+
45
+ @Test
46
+ fun runsThatDoNotShrinkAreCutFromTheEnd() {
47
+ assertWidths(
48
+ listOf(100f, 50f, 0f),
49
+ nativeListTitleSegmentWidths(
50
+ listOf(100f, 100f, 100f),
51
+ listOf(false, false, true),
52
+ listOf(null, null, null),
53
+ 150f,
54
+ ),
55
+ )
56
+ assertWidths(
57
+ listOf(100f, 20f),
58
+ nativeListTitleSegmentWidths(listOf(100f, 100f), listOf(false, false), listOf(null, null), 120f),
59
+ )
60
+ }
61
+
62
+ @Test
63
+ fun aNonPositiveLineLeavesNothing() {
64
+ assertWidths(listOf(0f, 0f, 0f), walletFirst(80f, 90f, 0f))
65
+ assertWidths(listOf(0f, 0f, 0f), walletFirst(80f, 90f, -10f))
66
+ }
67
+
68
+ // Runs replace `title` except where `title` is highlighted; wallet sidebar
69
+ // rows keep the plain title without runs or a leading glyph.
70
+ @Test
71
+ fun titleDecorationsFollowTheRowContract() {
72
+ assertTrue(nativeListShowsTitleRuns("", 2, 0))
73
+ assertTrue(nativeListShowsTitleRuns("accountSelector", 2, 0))
74
+ assertFalse(nativeListShowsTitleRuns("", 0, 0))
75
+ assertFalse(nativeListShowsTitleRuns("", 2, 1))
76
+ assertFalse(nativeListShowsTitleRuns("walletSidebar", 2, 0))
77
+ assertTrue(nativeListAllowsTitleDecorations(""))
78
+ assertFalse(nativeListAllowsTitleDecorations("walletSidebar"))
79
+ }
80
+ }
@@ -54,7 +54,14 @@ separately from source implementation in STYLE_SPEC §9.
54
54
 
55
55
  - **Use:** an identifiable asset, account, wallet, network or setting.
56
56
  - **Required data:** `leading`, `title`; optional `subtitle`, `tertiary`, `badges`,
57
- `trailing`, `leadingAction`, `titleIcon`, Web-only `secondaryTitleIcon`, match ranges and structured subtitle segments.
57
+ `trailing`, `leadingAction`, `titleIcon`, Web-only `secondaryTitleIcon`, `titleSegments`,
58
+ `titleLeadingIcon`, match ranges and structured subtitle segments.
59
+ - **Title runs:** optional `titleSegments` draw 1...4 runs with their own tone and
60
+ weight in place of `title`, on one line. One run may shrink; the others keep
61
+ their width under an optional `maxWidthRatio` cap. `title` stays the spoken
62
+ text. See SPEC.md.
63
+ - **Leading title icon:** optional `titleLeadingIcon` draws a 16-point glyph 6
64
+ points before the title; it is decorative unless labelled.
58
65
  - **Static title icon:** optional 20-point icon immediately after the title with
59
66
  a 4-point gap. It has no click action; an optional Web `hoverActionKey`
60
67
  emits an icon-anchored tooltip request on hover or touch. A trailing `button` is the fixed small