@onekeyfe/react-native-pager-view 6.7.0-6 → 6.7.0-60

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.
Files changed (49) hide show
  1. package/README.md +159 -115
  2. package/android/build.gradle +1 -0
  3. package/android/src/androidTest/AndroidManifest.xml +7 -0
  4. package/android/src/androidTest/java/com/reactnativepagerview/CollapsiblePagerTabReservationTest.kt +476 -0
  5. package/android/src/main/java/com/reactnativepagerview/CollapsiblePagerHost.kt +233 -43
  6. package/android/src/main/java/com/reactnativepagerview/CollapsiblePagerNativeHeaders.kt +596 -27
  7. package/android/src/main/java/com/reactnativepagerview/CollapsiblePagerViewManager.kt +40 -0
  8. package/android/src/main/java/com/reactnativepagerview/NativeScrollerScrollAwayInsets.kt +19 -0
  9. package/android/src/main/java/com/reactnativepagerview/NativeScrollerView.kt +50 -6
  10. package/android/src/main/java/com/reactnativepagerview/NestedScrollableHost.kt +8 -2
  11. package/android/src/main/java/com/reactnativepagerview/event/NativeHeaderPressEvent.kt +8 -0
  12. package/android/src/test/java/com/reactnativepagerview/NativeScrollerScrollAwayInsetsTest.kt +40 -0
  13. package/docs/SPEC.md +716 -10
  14. package/ios/RNCCollapsiblePagerViewComponentView.mm +2246 -97
  15. package/ios/RNCNativeScrollerComponentView.h +2 -0
  16. package/ios/RNCNativeScrollerComponentView.mm +42 -0
  17. package/ios/tests/RNCCollapsiblePagerFirstFrameTests.mm +723 -1
  18. package/ios/tests/RNCCollapsiblePagerHitTestTests.mm +1116 -0
  19. package/ios/tests/RNCCollapsiblePagerPressCancellationTests.mm +74 -9
  20. package/ios/tests/RNCCollapsiblePagerRefreshControlTests.mm +50 -0
  21. package/lib/module/CollapsiblePagerView.js +75 -11
  22. package/lib/module/CollapsiblePagerView.web.js +653 -8
  23. package/lib/module/CollapsiblePagerViewNativeComponent.ts +57 -42
  24. package/lib/module/NativeScroller.web.js +3 -0
  25. package/lib/module/NativeScrollerNativeComponent.ts +42 -46
  26. package/lib/module/PagerViewNativeComponent.ts +20 -25
  27. package/lib/module/WebCollapsiblePagerPage.js +7 -2
  28. package/lib/typescript/src/CollapsiblePagerView.d.ts +62 -4
  29. package/lib/typescript/src/CollapsiblePagerView.web.d.ts +56 -2
  30. package/lib/typescript/src/CollapsiblePagerViewNativeComponent.d.ts +54 -38
  31. package/lib/typescript/src/NativeScroller.d.ts +5 -3
  32. package/lib/typescript/src/NativeScroller.web.d.ts +1 -1
  33. package/lib/typescript/src/NativeScrollerNativeComponent.d.ts +47 -48
  34. package/lib/typescript/src/PagerView.d.ts +1 -1
  35. package/lib/typescript/src/PagerView.web.d.ts +1 -1
  36. package/lib/typescript/src/PagerViewNativeComponent.d.ts +20 -21
  37. package/lib/typescript/src/WebCollapsiblePagerPage.d.ts +1 -1
  38. package/lib/typescript/src/usePagerView.d.ts +2 -2
  39. package/lib/typescript/src/utils.d.ts +2 -2
  40. package/package.json +20 -7
  41. package/react-native-pager-view.podspec +1 -0
  42. package/src/CollapsiblePagerView.tsx +208 -12
  43. package/src/CollapsiblePagerView.web.tsx +587 -7
  44. package/src/CollapsiblePagerViewNativeComponent.ts +57 -42
  45. package/src/NativeScroller.tsx +14 -4
  46. package/src/NativeScroller.web.tsx +15 -1
  47. package/src/NativeScrollerNativeComponent.ts +42 -46
  48. package/src/PagerViewNativeComponent.ts +20 -25
  49. package/src/WebCollapsiblePagerPage.tsx +7 -2
@@ -2,8 +2,12 @@ package com.reactnativepagerview
2
2
 
3
3
  import android.content.Context
4
4
  import android.graphics.Color
5
+ import android.graphics.Bitmap
5
6
  import android.graphics.Typeface
6
7
  import android.graphics.drawable.GradientDrawable
8
+ import android.graphics.drawable.StateListDrawable
9
+ import android.widget.ImageView
10
+ import com.margelo.nitro.onekeyimage.OneKeyNamedSVG
7
11
  import android.text.TextUtils
8
12
  import android.util.TypedValue
9
13
  import android.view.Gravity
@@ -65,7 +69,11 @@ private class CollapsiblePagerHorizontalItemsView(
65
69
  ) : HorizontalScrollView(context) {
66
70
  private val density = resources.displayMetrics.density
67
71
  private val content = FrameLayout(context)
72
+ private val track = View(context)
68
73
  private val indicator = View(context)
74
+ private val trackBackground = GradientDrawable().apply {
75
+ shape = GradientDrawable.RECTANGLE
76
+ }
69
77
  private val indicatorBackground = GradientDrawable().apply {
70
78
  shape = GradientDrawable.RECTANGLE
71
79
  }
@@ -75,6 +83,12 @@ private class CollapsiblePagerHorizontalItemsView(
75
83
  private var selectedKey = ""
76
84
  private var rowHeightPx = dp(if (showsProgressIndicator) 44.0 else 42.0)
77
85
  private var contentPaddingPx = dp(20.0)
86
+ private var contentPaddingVerticalPx = 0
87
+ private var segmented = false
88
+ private var textVariant = false
89
+ private var pillVariant = false
90
+ private var itemPaddingHorizontalDp: Double? = null
91
+ private var pillAnimationEnabled = true
78
92
  private var itemSpacingPx = dp(8.0)
79
93
  private var fontSize = if (showsProgressIndicator) 16.0 else 14.0
80
94
  private var fontFamily: String? = null
@@ -85,6 +99,12 @@ private class CollapsiblePagerHorizontalItemsView(
85
99
  private var indicatorHeightPx = dp(2.0)
86
100
  private var indicatorBottomPx = 0
87
101
  private var progress = 0f
102
+ private var mappedSource: Int? = null
103
+ private var mappedDestination: Int? = null
104
+ private var mappedFraction = 0f
105
+ private var activeFontFamily: String? = null
106
+ private var controlledSelectedKey: String? = null
107
+ private var validControlledPageMapping = false
88
108
  private var centerSelectionWhenIdle = true
89
109
  private var isTouchDragging = false
90
110
 
@@ -96,7 +116,9 @@ private class CollapsiblePagerHorizontalItemsView(
96
116
  isFillViewport = true
97
117
  overScrollMode = OVER_SCROLL_NEVER
98
118
  clipToPadding = false
119
+ track.background = trackBackground
99
120
  indicator.background = indicatorBackground
121
+ content.addView(track, FrameLayout.LayoutParams(0, 0))
100
122
  content.addView(indicator, FrameLayout.LayoutParams(0, 0))
101
123
  addView(
102
124
  content,
@@ -149,17 +171,26 @@ private class CollapsiblePagerHorizontalItemsView(
149
171
  fontFamily: String?,
150
172
  indicatorHeight: Double = 0.0,
151
173
  indicatorBottom: Double = 0.0,
174
+ variant: String = "underline",
175
+ contentPaddingVertical: Double = 0.0,
152
176
  ) {
153
177
  rowHeightPx = max(1, dp(rowHeight))
154
178
  contentPaddingPx = max(0, dp(contentPadding))
179
+ contentPaddingVerticalPx = max(0, dp(contentPaddingVertical))
180
+ val wasSegmented = segmented
181
+ segmented = showsProgressIndicator && variant == "segmented"
182
+ textVariant = showsProgressIndicator && variant == "text"
183
+ pillVariant = showsProgressIndicator && variant == "pill"
155
184
  itemSpacingPx = max(0, dp(itemSpacing))
156
185
  this.fontSize = max(1.0, fontSize)
157
186
  this.fontFamily = fontFamily
158
187
  if (showsProgressIndicator) {
159
188
  indicatorHeightPx = max(0, dp(indicatorHeight))
160
189
  indicatorBottomPx = max(0, dp(indicatorBottom))
161
- indicatorBackground.cornerRadius = indicatorHeightPx / 2f
190
+ indicatorBackground.cornerRadius = if (segmented) dp(14.0).toFloat() else indicatorHeightPx / 2f
162
191
  }
192
+ track.visibility = if (segmented) VISIBLE else GONE
193
+ if (segmented && !wasSegmented) scrollTo(0, 0)
163
194
  applyTypeface()
164
195
  requestLayout()
165
196
  }
@@ -171,8 +202,9 @@ private class CollapsiblePagerHorizontalItemsView(
171
202
  selectedBackgroundColor: Int,
172
203
  indicatorColor: Int,
173
204
  ) {
174
- setBackgroundColor(backgroundColor)
175
- content.setBackgroundColor(backgroundColor)
205
+ setBackgroundColor(if (segmented) Color.TRANSPARENT else backgroundColor)
206
+ content.setBackgroundColor(if (segmented) Color.TRANSPARENT else backgroundColor)
207
+ trackBackground.setColor(backgroundColor)
176
208
  this.activeTextColor = activeTextColor
177
209
  this.inactiveTextColor = inactiveTextColor
178
210
  this.selectedBackgroundColor = selectedBackgroundColor
@@ -181,7 +213,39 @@ private class CollapsiblePagerHorizontalItemsView(
181
213
  updatePresentation()
182
214
  }
183
215
 
184
- fun setProgress(value: Float) {
216
+ fun setControlledSelectedKey(value: String?, validPageMapping: Boolean) {
217
+ controlledSelectedKey = value
218
+ validControlledPageMapping = validPageMapping
219
+ updatePresentation()
220
+ }
221
+
222
+ fun usesTextVariant(): Boolean = textVariant
223
+
224
+ // Variants whose label colors (and pill) follow controlled pager progress.
225
+ fun usesProgressDrivenItems(): Boolean = textVariant || (pillVariant && pillAnimationEnabled)
226
+
227
+ fun setPillAnimationEnabled(value: Boolean) {
228
+ if (pillAnimationEnabled == value) return
229
+ pillAnimationEnabled = value
230
+ updatePresentation()
231
+ }
232
+
233
+ fun pillAnimationDisabled(): Boolean = pillVariant && !pillAnimationEnabled
234
+
235
+ fun setItemPaddingHorizontal(value: Double?) {
236
+ if (itemPaddingHorizontalDp == value) return
237
+ itemPaddingHorizontalDp = value
238
+ requestLayout()
239
+ }
240
+
241
+ private fun itemPaddingPx(): Int = dp(itemPaddingHorizontalDp ?: if (textVariant) 10.0 else if (pillVariant) 14.0 else 8.0)
242
+
243
+ fun setActiveFontFamily(value: String?) { activeFontFamily = value; requestLayout() }
244
+
245
+ fun setProgress(value: Float, source: Int? = null, destination: Int? = null, fraction: Float = 0f) {
246
+ mappedSource = source
247
+ mappedDestination = destination
248
+ mappedFraction = fraction
185
249
  if (!showsProgressIndicator || items.isEmpty()) return
186
250
  val next = value.coerceIn(0f, (items.size - 1).toFloat())
187
251
  if (kotlin.math.abs(progress - next) >= 0.001f) centerSelectionWhenIdle = true
@@ -189,10 +253,30 @@ private class CollapsiblePagerHorizontalItemsView(
189
253
  updatePresentation()
190
254
  }
191
255
 
256
+ private fun selectedTypeface(): Typeface = activeFontFamily?.takeIf(String::isNotEmpty)?.let { resolveHeaderTypeface(context, it) }
257
+ ?: fontFamily?.takeIf(String::isNotEmpty)?.let { family ->
258
+ val normal = resolveHeaderTypeface(context, family)
259
+ if (android.os.Build.VERSION.SDK_INT >= 28) Typeface.create(normal, 600, normal.isItalic)
260
+ else Typeface.create(normal, Typeface.BOLD)
261
+ }
262
+ ?: if (android.os.Build.VERSION.SDK_INT >= 28) Typeface.create(Typeface.create("sans-serif", Typeface.NORMAL), 600, false)
263
+ else Typeface.create("sans-serif", Typeface.BOLD)
264
+
265
+ private fun visualFontOwnerIndex(semanticIndex: Int): Int {
266
+ val source = mappedSource
267
+ val destination = mappedDestination
268
+ if (textVariant && controlledSelectedKey != null && validControlledPageMapping && source != null && destination != null) {
269
+ return if (mappedFraction < 0.5f) source else destination
270
+ }
271
+ return semanticIndex
272
+ }
273
+
192
274
  private fun applyTypeface() {
193
275
  val typeface = resolveHeaderTypeface(context, fontFamily)
194
- buttons.forEach { button ->
195
- button.typeface = typeface
276
+ val fontOwner = visualFontOwnerIndex(buttons.indexOfFirst { it.isSelected })
277
+ buttons.forEachIndexed { index, button ->
278
+ button.typeface = if (textVariant && index == fontOwner) selectedTypeface() else typeface
279
+ button.setPadding(itemPaddingPx(), 0, itemPaddingPx(), 0)
196
280
  button.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize.toFloat())
197
281
  }
198
282
  }
@@ -213,9 +297,57 @@ private class CollapsiblePagerHorizontalItemsView(
213
297
  }
214
298
  applyTypeface()
215
299
  itemFrames.clear()
300
+ if (segmented) {
301
+ val actualPaddingHorizontal = min(contentPaddingPx, width / 2)
302
+ val actualPaddingVertical = min(contentPaddingVerticalPx, height / 2)
303
+ val trackLeft = actualPaddingHorizontal
304
+ val trackRight = max(trackLeft, width - contentPaddingPx)
305
+ val trackTop = actualPaddingVertical
306
+ val trackBottom = max(trackTop, height - contentPaddingVerticalPx)
307
+ val trackWidth = trackRight - trackLeft
308
+ val trackHeight = trackBottom - trackTop
309
+ trackBackground.cornerRadius = trackHeight / 2f
310
+ indicatorBackground.cornerRadius = max(0, trackHeight - dp(4.0)) / 2f
311
+ track.layoutParams = FrameLayout.LayoutParams(trackWidth, trackHeight).apply {
312
+ gravity = Gravity.TOP or Gravity.LEFT
313
+ leftMargin = trackLeft
314
+ topMargin = trackTop
315
+ }
316
+ buttons.forEachIndexed { index, button ->
317
+ val count = buttons.size
318
+ val first = trackLeft + trackWidth * index / count
319
+ val last = trackLeft + trackWidth * (index + 1) / count
320
+ val start = if (layoutDirection == View.LAYOUT_DIRECTION_RTL) trackRight - (last - trackLeft) else first
321
+ val end = if (layoutDirection == View.LAYOUT_DIRECTION_RTL) trackRight - (first - trackLeft) else last
322
+ val buttonWidth = max(0, end - start)
323
+ val thumbInset = dp(2.0)
324
+ itemFrames.add(intArrayOf(start, buttonWidth, start + thumbInset, max(0, buttonWidth - 2 * thumbInset)))
325
+ button.layoutParams = FrameLayout.LayoutParams(buttonWidth, trackHeight).apply {
326
+ gravity = Gravity.TOP or Gravity.LEFT
327
+ leftMargin = start
328
+ topMargin = trackTop
329
+ }
330
+ }
331
+ content.layoutParams = LayoutParams(width, height)
332
+ content.measure(
333
+ MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
334
+ MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY),
335
+ )
336
+ setMeasuredDimension(width, height)
337
+ return
338
+ }
339
+ track.layoutParams = FrameLayout.LayoutParams(0, 0)
216
340
  var x = contentPaddingPx
217
341
  buttons.forEachIndexed { index, button ->
218
- val textWidth = ceil(button.paint.measureText(button.text.toString()).toDouble()).toInt()
342
+ var textWidth = ceil(button.paint.measureText(button.text.toString()).toDouble()).toInt()
343
+ if (textVariant) {
344
+ val original = button.paint.typeface
345
+ button.paint.typeface = resolveHeaderTypeface(context, fontFamily)
346
+ textWidth = ceil(button.paint.measureText(button.text.toString()).toDouble()).toInt()
347
+ button.paint.typeface = selectedTypeface()
348
+ textWidth = max(textWidth, ceil(button.paint.measureText(button.text.toString()).toDouble()).toInt())
349
+ button.paint.typeface = original
350
+ }
219
351
  // Reuse the rounded padding: dp(16) can be one pixel less than two dp(8) insets.
220
352
  val horizontalPadding = if (showsProgressIndicator) {
221
353
  button.compoundPaddingLeft + button.compoundPaddingRight
@@ -223,11 +355,20 @@ private class CollapsiblePagerHorizontalItemsView(
223
355
  dp(20.0)
224
356
  }
225
357
  val buttonWidth = max(dp(44.0), textWidth + horizontalPadding)
226
- val indicatorWidth = textWidth
358
+ val indicatorWidth = if (pillVariant) buttonWidth else textWidth
227
359
  val indicatorX = x + (buttonWidth - indicatorWidth) / 2
228
360
  itemFrames.add(intArrayOf(x, buttonWidth, indicatorX, indicatorWidth))
229
- val itemHeight = if (showsProgressIndicator) height else min(dp(32.0), height)
230
- val top = if (showsProgressIndicator) 0 else max(0, (height - itemHeight) / 2)
361
+ val pillInset = min(contentPaddingVerticalPx, height / 2)
362
+ val itemHeight = when {
363
+ pillVariant -> max(0, height - 2 * pillInset)
364
+ showsProgressIndicator -> height
365
+ else -> min(dp(32.0), height)
366
+ }
367
+ val top = when {
368
+ pillVariant -> pillInset
369
+ showsProgressIndicator -> 0
370
+ else -> max(0, (height - itemHeight) / 2)
371
+ }
231
372
  button.layoutParams = FrameLayout.LayoutParams(buttonWidth, itemHeight).apply {
232
373
  leftMargin = x
233
374
  topMargin = top
@@ -260,36 +401,70 @@ private class CollapsiblePagerHorizontalItemsView(
260
401
  return super.onTouchEvent(event)
261
402
  }
262
403
 
404
+ override fun onInterceptTouchEvent(event: MotionEvent): Boolean =
405
+ if (segmented) false else super.onInterceptTouchEvent(event)
406
+
263
407
  private fun updatePresentation() {
264
408
  if (buttons.isEmpty() || itemFrames.size != buttons.size) return
265
409
  val selectedIndex: Int
266
410
  val scrollTargetCenterX: Float
267
411
  if (showsProgressIndicator) {
268
- val clamped = progress.coerceIn(0f, buttons.lastIndex.toFloat())
412
+ // A pill without animation jumps (with its label colors) to the selection.
413
+ val snapToSelection = pillAnimationDisabled()
414
+ val snappedIndex = if (snapToSelection) {
415
+ (controlledSelectedKey?.let { key -> items.indexOfFirst { it.key == key }.takeIf { it >= 0 } }
416
+ ?: progress.roundToInt()).coerceIn(0, buttons.lastIndex)
417
+ } else -1
418
+ val clamped = if (snapToSelection) snappedIndex.toFloat() else progress.coerceIn(0f, buttons.lastIndex.toFloat())
269
419
  val lower = floor(clamped).toInt()
270
420
  val upper = min(lower + 1, buttons.lastIndex)
271
421
  val fraction = clamped - lower
272
422
  val from = itemFrames[lower]
273
423
  val to = itemFrames[upper]
274
- val interpolatedIndicatorX = from[2] + (to[2] - from[2]) * fraction
275
- val interpolatedIndicatorWidth = from[3] + (to[3] - from[3]) * fraction
424
+ var interpolatedIndicatorX = from[2] + (to[2] - from[2]) * fraction
425
+ var interpolatedIndicatorWidth = from[3] + (to[3] - from[3]) * fraction
426
+ if (pillVariant) {
427
+ // Leading edge leads and trailing edge lags while moving between tabs.
428
+ val leading = 1f - (1f - fraction) * (1f - fraction)
429
+ val trailing = fraction * fraction
430
+ val forward = to[2] >= from[2]
431
+ val leftEdge = from[2] + (to[2] - from[2]) * (if (forward) trailing else leading)
432
+ val rightEdge = from[2] + from[3] + (to[2] + to[3] - from[2] - from[3]) * (if (forward) leading else trailing)
433
+ interpolatedIndicatorX = leftEdge
434
+ interpolatedIndicatorWidth = max(0f, rightEdge - leftEdge)
435
+ }
276
436
  val indicatorX = interpolatedIndicatorX.roundToInt()
277
437
  val indicatorWidth = interpolatedIndicatorWidth.roundToInt()
278
- val indicatorTop = max(0, measuredHeight - indicatorBottomPx - indicatorHeightPx)
438
+ val actualPaddingVertical = min(contentPaddingVerticalPx, measuredHeight / 2)
439
+ val indicatorHeight = when {
440
+ segmented -> max(0, measuredHeight - 2 * actualPaddingVertical - dp(4.0))
441
+ pillVariant -> max(0, measuredHeight - 2 * actualPaddingVertical)
442
+ else -> indicatorHeightPx
443
+ }
444
+ val indicatorTop = when {
445
+ segmented -> actualPaddingVertical + dp(2.0)
446
+ pillVariant -> actualPaddingVertical
447
+ else -> max(0, measuredHeight - indicatorBottomPx - indicatorHeightPx)
448
+ }
449
+ if (pillVariant) indicatorBackground.cornerRadius = indicatorHeight / 2f
279
450
  indicator.layout(
280
451
  indicatorX,
281
452
  indicatorTop,
282
453
  indicatorX + indicatorWidth,
283
- indicatorTop + indicatorHeightPx,
454
+ indicatorTop + indicatorHeight,
284
455
  )
285
- indicator.visibility = if (indicatorHeightPx > 0) VISIBLE else GONE
456
+ indicator.visibility = if (!textVariant && indicatorHeight > 0) VISIBLE else GONE
286
457
  scrollTargetCenterX = interpolatedIndicatorX + interpolatedIndicatorWidth / 2f
287
- selectedIndex = clamped.roundToInt()
458
+ selectedIndex = if (controlledSelectedKey != null) items.indexOfFirst { it.key == controlledSelectedKey } else clamped.roundToInt()
459
+ val fontOwner = visualFontOwnerIndex(selectedIndex)
288
460
  buttons.forEachIndexed { index, button ->
289
- val emphasis = 1f - min(1f, kotlin.math.abs(clamped - index))
461
+ val emphasis = if (!snapToSelection && mappedSource != null && mappedDestination != null) {
462
+ (if (index == mappedSource) 1f - mappedFraction else 0f) + (if (index == mappedDestination) mappedFraction else 0f)
463
+ } else 1f - min(1f, kotlin.math.abs(clamped - index))
290
464
  button.setTextColor(ColorUtils.blendARGB(inactiveTextColor, activeTextColor, emphasis))
291
465
  button.background = null
292
466
  button.isSelected = index == selectedIndex
467
+ if (textVariant) button.typeface = if (index == fontOwner) selectedTypeface() else resolveHeaderTypeface(context, fontFamily)
293
468
  }
294
469
  } else {
295
470
  selectedIndex = items.indexOfFirst { item -> item.key == selectedKey }
@@ -304,7 +479,7 @@ private class CollapsiblePagerHorizontalItemsView(
304
479
  }
305
480
  }
306
481
 
307
- if (centerSelectionWhenIdle && !isTouchDragging && width > 0 && selectedIndex in itemFrames.indices) {
482
+ if (centerSelectionWhenIdle && !segmented && !isTouchDragging && width > 0 && selectedIndex in itemFrames.indices) {
308
483
  val desired = (scrollTargetCenterX - width / 2f).roundToInt()
309
484
  .coerceIn(0, max(0, content.measuredWidth - width))
310
485
  scrollTo(desired, 0)
@@ -316,6 +491,276 @@ private class CollapsiblePagerHorizontalItemsView(
316
491
  internal class CollapsiblePagerNativeTabBarView(context: Context) : FrameLayout(context) {
317
492
  private val row = CollapsiblePagerHorizontalItemsView(context, true)
318
493
  private var heightPx = 0
494
+ private val toolbar = ImageView(context)
495
+ private var config = JSONObject()
496
+ private var items = emptyList<CollapsiblePagerNativeHeaderItem>()
497
+ private var selectedKey = ""
498
+ private var iconOwner: Any = Any()
499
+ private var iconIdentity = ""
500
+ private var loadedIconIdentity = ""
501
+ private var iconRequestPending = false
502
+ private var readyToolbarImage: Bitmap? = null
503
+ private var readyToolbarIdentity = ""
504
+ private var failedIconIdentity = ""
505
+ private var toolbarTouchKey: String? = null
506
+ private var toolbarTouchStarted = false
507
+ private var toolbarKeyboardKey: String? = null
508
+ private var lastNativeProgress = 0f
509
+ private var hasNativeProgress = false
510
+ private var toolbarReservedWidth = 0.0
511
+ private var toolbarPagerBusy = true
512
+ private var toolbarPageIndex = -1
513
+ private var committedToolbarKey: String? = null
514
+ private var committedToolbarEntry: JSONObject? = null
515
+ private var desiredToolbarKey: String? = null
516
+ private var desiredToolbarEntry: JSONObject? = null
517
+ private var loadedToolbarImage: Bitmap? = null
518
+ private var toolbarPresenceAnimating = false
519
+ private var toolbarPresenceInterrupted = false
520
+ private var toolbarVisible = false
521
+ private var toolbarAnimationGeneration = 0
522
+ private var toolbarSize = 38.0
523
+ private var toolbarIconSize = 24.0
524
+ private var toolbarContentWidth = 24.0
525
+ private var toolbarTrailingInset = 20.0
526
+ var onToolbarPress: ((String, DoubleArray) -> Unit)? = null
527
+
528
+ private fun dp(value: Number) = (value.toDouble() * resources.displayMetrics.density).roundToInt()
529
+
530
+ fun updateConfigJSON(value: String?) {
531
+ config = runCatching { JSONObject(value ?: "{}") }.getOrDefault(JSONObject())
532
+ row.setActiveFontFamily(config.optString("activeFontFamily").takeIf(String::isNotEmpty))
533
+ row.setItemPaddingHorizontal(config.optDouble("itemPaddingHorizontal", Double.NaN).takeIf { it.isFinite() && it >= 0 })
534
+ row.setPillAnimationEnabled(config.optBoolean("indicatorAnimationEnabled", true))
535
+ requestLayout()
536
+ selectedKey = if (config.optBoolean("controlled")) config.optString("selectedKey") else items.getOrNull(lastNativeProgress.roundToInt())?.key ?: ""
537
+ row.setControlledSelectedKey(if (config.optBoolean("controlled")) selectedKey else null, controlledPageIndices() != null)
538
+ if (hasNativeProgress) setProgress(lastNativeProgress)
539
+ else {
540
+ val index = items.indexOfFirst { it.key == selectedKey }
541
+ if (index >= 0) row.setProgress(index.toFloat())
542
+ }
543
+ updateToolbar()
544
+ }
545
+
546
+ private fun ownsSettledToolbar(): Boolean = config.optBoolean("controlled") && config.optJSONObject("toolbar") != null
547
+
548
+ internal fun usesSettledToolbarOwner(): Boolean = ownsSettledToolbar()
549
+
550
+ internal fun needsToolbarPagerSettlement(pageIndex: Int): Boolean =
551
+ ownsSettledToolbar() && (toolbarPagerBusy || toolbarPageIndex != pageIndex)
552
+
553
+ private fun toolbarCanCommit(): Boolean {
554
+ if (!isAttachedToWindow) return false
555
+ if (!ownsSettledToolbar()) return true
556
+ if (toolbarPagerBusy || toolbarPageIndex < 0) return false
557
+ return controlledPageIndices() == null || config.optJSONArray("pageKeys")?.optString(toolbarPageIndex) == selectedKey
558
+ }
559
+
560
+ fun updateToolbarPagerState(pageIndex: Int, busy: Boolean) {
561
+ if (toolbarPagerBusy == busy && (busy || toolbarPageIndex == pageIndex)) return
562
+ if (!busy) toolbarPageIndex = pageIndex
563
+ toolbarPagerBusy = busy
564
+ updateToolbar()
565
+ }
566
+
567
+ private fun cancelToolbarPending() {
568
+ if (iconRequestPending || readyToolbarImage != null) {
569
+ OneKeyNamedSVG.cancel(iconOwner)
570
+ iconOwner = Any()
571
+ }
572
+ iconRequestPending = false
573
+ readyToolbarImage = null
574
+ readyToolbarIdentity = ""
575
+ }
576
+
577
+ private fun setToolbarInteractive(enabled: Boolean) {
578
+ if (!enabled) {
579
+ toolbarKeyboardKey = null
580
+ if (toolbarTouchStarted) toolbarTouchKey = null
581
+ toolbar.isPressed = false
582
+ toolbar.isHovered = false
583
+ toolbar.clearFocus()
584
+ }
585
+ toolbar.isEnabled = enabled
586
+ toolbar.isClickable = enabled
587
+ toolbar.isFocusable = enabled
588
+ toolbar.importantForAccessibility = if (enabled) View.IMPORTANT_FOR_ACCESSIBILITY_AUTO else View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
589
+ }
590
+
591
+ private fun suspendToolbar() {
592
+ setToolbarInteractive(false)
593
+ cancelToolbarPending()
594
+ desiredToolbarKey = null
595
+ desiredToolbarEntry = null
596
+ if (toolbarPresenceAnimating) {
597
+ toolbarAnimationGeneration++
598
+ toolbar.animate().cancel()
599
+ toolbarPresenceAnimating = false
600
+ toolbarPresenceInterrupted = true
601
+ }
602
+ }
603
+
604
+ private fun setToolbarVisible(visible: Boolean) {
605
+ if (toolbarVisible == visible && !toolbarPresenceInterrupted) return
606
+ toolbarVisible = visible
607
+ toolbarPresenceInterrupted = false
608
+ val generation = ++toolbarAnimationGeneration
609
+ toolbar.animate().cancel()
610
+ if (visible) toolbar.visibility = VISIBLE
611
+ if (!isAttachedToWindow) {
612
+ toolbar.alpha = if (visible) 1f else 0f
613
+ toolbar.visibility = if (visible) VISIBLE else INVISIBLE
614
+ toolbarPresenceAnimating = false
615
+ return
616
+ }
617
+ toolbarPresenceAnimating = true
618
+ toolbar.animate().alpha(if (visible) 1f else 0f).setDuration(100).withEndAction {
619
+ if (toolbarAnimationGeneration == generation) {
620
+ toolbarPresenceAnimating = false
621
+ if (!visible) toolbar.visibility = INVISIBLE
622
+ }
623
+ }.start()
624
+ }
625
+
626
+ private fun hideToolbar(failed: Boolean) {
627
+ setToolbarInteractive(false)
628
+ committedToolbarKey = null
629
+ committedToolbarEntry = null
630
+ toolbar.contentDescription = null
631
+ toolbar.setTag(com.facebook.react.R.id.react_test_id, null)
632
+ if (failed) toolbar.setImageDrawable(null)
633
+ setToolbarVisible(false)
634
+ }
635
+
636
+ private fun commitToolbar(key: String, descriptor: JSONObject, image: Bitmap, identity: String) {
637
+ if (!toolbarCanCommit() || key != selectedKey) return
638
+ if (committedToolbarKey != key && toolbarTouchStarted) toolbarTouchKey = null
639
+ toolbarSize = descriptor.optDouble("size", 38.0).coerceIn(1.0, 128.0)
640
+ toolbarIconSize = descriptor.optDouble("iconSize", min(24.0, toolbarSize)).coerceIn(1.0, toolbarSize)
641
+ toolbarContentWidth = descriptor.optDouble("contentWidth", min(24.0, toolbarSize)).coerceIn(0.0, toolbarSize)
642
+ toolbarTrailingInset = descriptor.optDouble("trailingInset", 20.0).coerceIn(0.0, 128.0)
643
+ val inset = max(0, (dp(toolbarSize) - dp(toolbarIconSize)) / 2)
644
+ toolbar.setPadding(inset, inset, inset, inset)
645
+ fun color(name: String, fallback: Int) = (descriptor.opt(name) as? Number)?.toInt() ?: fallback
646
+ val base = if (descriptor.optBoolean("selected")) color("selectedBackgroundColor", Color.TRANSPARENT) else Color.TRANSPARENT
647
+ fun fill(value: Int) = GradientDrawable().apply { shape = GradientDrawable.OVAL; setColor(value) }
648
+ toolbar.background = StateListDrawable().apply {
649
+ addState(intArrayOf(android.R.attr.state_enabled, android.R.attr.state_pressed), fill(color("pressedBackgroundColor", base)))
650
+ addState(intArrayOf(android.R.attr.state_enabled, android.R.attr.state_hovered), fill(color("hoverBackgroundColor", base)))
651
+ addState(intArrayOf(), fill(base))
652
+ }
653
+ toolbar.setImageBitmap(image)
654
+ toolbar.contentDescription = descriptor.optString("accessibilityLabel")
655
+ toolbar.setTag(com.facebook.react.R.id.react_test_id, descriptor.optString("testID"))
656
+ committedToolbarKey = key
657
+ committedToolbarEntry = descriptor
658
+ loadedToolbarImage = image
659
+ loadedIconIdentity = identity
660
+ iconIdentity = identity
661
+ iconRequestPending = false
662
+ readyToolbarImage = null
663
+ readyToolbarIdentity = ""
664
+ setToolbarVisible(true)
665
+ setToolbarInteractive(true)
666
+ requestLayout()
667
+ }
668
+
669
+ private fun applyReadyToolbarImage() {
670
+ val image = readyToolbarImage ?: return
671
+ val key = desiredToolbarKey ?: return
672
+ val entry = desiredToolbarEntry ?: return
673
+ if (readyToolbarIdentity != iconIdentity || !toolbarCanCommit() || key != selectedKey) return
674
+ commitToolbar(key, entry, image, iconIdentity)
675
+ }
676
+
677
+ private fun updateToolbar() {
678
+ val entries = config.optJSONObject("toolbar")
679
+ toolbarReservedWidth = if (entries == null) 0.0 else 44.0
680
+ if (entries != null && entries.length() > 0) {
681
+ toolbarReservedWidth = 0.0
682
+ entries.keys().forEach { key ->
683
+ val entry = entries.optJSONObject(key) ?: JSONObject()
684
+ val size = entry.optDouble("size", 38.0).coerceIn(1.0, 128.0)
685
+ toolbarReservedWidth = max(toolbarReservedWidth, entry.optDouble("contentWidth", min(24.0, size)).coerceIn(0.0, size) + entry.optDouble("trailingInset", 20.0).coerceIn(0.0, 128.0))
686
+ }
687
+ }
688
+ if (!toolbarCanCommit()) { suspendToolbar(); requestLayout(); return }
689
+ val entry = entries?.optJSONObject(selectedKey)
690
+ if (entry == null || entry.optString("iconName").isEmpty()) {
691
+ cancelToolbarPending()
692
+ desiredToolbarKey = null
693
+ desiredToolbarEntry = null
694
+ hideToolbar(false)
695
+ requestLayout()
696
+ return
697
+ }
698
+ val descriptor = JSONObject(entry.toString())
699
+ desiredToolbarKey = selectedKey
700
+ desiredToolbarEntry = descriptor
701
+ val size = descriptor.optDouble("size", 38.0).coerceIn(1.0, 128.0)
702
+ val iconSize = descriptor.optDouble("iconSize", min(24.0, size)).coerceIn(1.0, size)
703
+ val name = descriptor.optString("iconName")
704
+ val tint = descriptor.optString("iconColor", "#000000")
705
+ val identity = "$name|$tint|${resources.displayMetrics.density}|$iconSize"
706
+ val loaded = loadedToolbarImage
707
+ if (identity == loadedIconIdentity && loaded != null) {
708
+ cancelToolbarPending()
709
+ commitToolbar(selectedKey, descriptor, loaded, identity)
710
+ return
711
+ }
712
+ if (identity == iconIdentity && iconRequestPending) { applyReadyToolbarImage(); return }
713
+ cancelToolbarPending()
714
+ setToolbarInteractive(false)
715
+ iconIdentity = identity
716
+ if (identity == failedIconIdentity) { hideToolbar(true); return }
717
+ iconOwner = Any()
718
+ val owner = iconOwner
719
+ iconRequestPending = true
720
+ OneKeyNamedSVG.request(owner, context.applicationContext.assets, name, tint,
721
+ dp(iconSize), dp(iconSize), resources.displayMetrics.density) { bitmap ->
722
+ if (iconOwner === owner && iconIdentity == identity && isAttachedToWindow) {
723
+ if (bitmap == null) {
724
+ iconRequestPending = false
725
+ failedIconIdentity = identity
726
+ hideToolbar(true)
727
+ } else {
728
+ readyToolbarImage = bitmap
729
+ readyToolbarIdentity = identity
730
+ applyReadyToolbarImage()
731
+ }
732
+ }
733
+ }
734
+ requestLayout()
735
+ }
736
+
737
+ private fun performToolbarPress(fromPointer: Boolean): Boolean {
738
+ val key = if (fromPointer) toolbarTouchKey.takeIf { toolbarTouchStarted } else committedToolbarKey
739
+ if (fromPointer) { toolbarTouchStarted = false; toolbarTouchKey = null }
740
+ if (key == null || key != committedToolbarKey || key != selectedKey || committedToolbarEntry == null ||
741
+ !toolbarCanCommit() || !toolbar.isEnabled || toolbar.visibility != VISIBLE) return false
742
+ val location = IntArray(2)
743
+ toolbar.getLocationInWindow(location)
744
+ val density = resources.displayMetrics.density.toDouble()
745
+ onToolbarPress?.invoke(key, doubleArrayOf(location[0] / density, location[1] / density, toolbar.width / density, toolbar.height / density))
746
+ return true
747
+ }
748
+
749
+ override fun onAttachedToWindow() {
750
+ super.onAttachedToWindow()
751
+ toolbarPagerBusy = true
752
+ updateToolbar()
753
+ }
754
+
755
+ override fun onDetachedFromWindow() {
756
+ suspendToolbar()
757
+ toolbarPagerBusy = true
758
+ toolbarPageIndex = -1
759
+ toolbarTouchStarted = false
760
+ toolbarTouchKey = null
761
+ failedIconIdentity = ""
762
+ super.onDetachedFromWindow()
763
+ }
319
764
 
320
765
  var onItemPress: ((Int, String) -> Unit)?
321
766
  get() = row.onItemPress
@@ -325,17 +770,59 @@ internal class CollapsiblePagerNativeTabBarView(context: Context) : FrameLayout(
325
770
 
326
771
  init {
327
772
  addView(row, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
773
+ addView(toolbar)
774
+ toolbar.scaleType = ImageView.ScaleType.CENTER_INSIDE
775
+ toolbar.setPadding(dp(6), dp(6), dp(6), dp(6))
776
+ toolbar.isClickable = true
777
+ toolbar.isFocusable = true
778
+ toolbar.visibility = INVISIBLE
779
+ toolbar.alpha = 0f
780
+ toolbar.isEnabled = false
781
+ toolbar.isClickable = false
782
+ toolbar.isFocusable = false
783
+ toolbar.importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
784
+ toolbar.setOnTouchListener { _, event ->
785
+ when (event.actionMasked) {
786
+ MotionEvent.ACTION_DOWN -> { toolbarTouchStarted = true; toolbarTouchKey = committedToolbarKey.takeIf { toolbar.isEnabled && toolbarCanCommit() } }
787
+ MotionEvent.ACTION_CANCEL -> { toolbarTouchKey = null }
788
+ }
789
+ false
790
+ }
791
+ toolbar.setOnClickListener { performToolbarPress(true) }
792
+ toolbar.accessibilityDelegate = object : View.AccessibilityDelegate() {
793
+ override fun performAccessibilityAction(host: View, action: Int, args: android.os.Bundle?): Boolean {
794
+ if (action == android.view.accessibility.AccessibilityNodeInfo.ACTION_CLICK) return performToolbarPress(false)
795
+ return super.performAccessibilityAction(host, action, args)
796
+ }
797
+ }
798
+ toolbar.setOnKeyListener { _, keyCode, event ->
799
+ if (keyCode != android.view.KeyEvent.KEYCODE_ENTER && keyCode != android.view.KeyEvent.KEYCODE_DPAD_CENTER && keyCode != android.view.KeyEvent.KEYCODE_SPACE) false
800
+ else if (event.action == android.view.KeyEvent.ACTION_DOWN) {
801
+ if (event.repeatCount == 0) toolbarKeyboardKey = committedToolbarKey.takeIf { toolbar.isEnabled && toolbarCanCommit() }
802
+ toolbar.isPressed = toolbarKeyboardKey != null
803
+ toolbarKeyboardKey != null
804
+ } else if (event.action == android.view.KeyEvent.ACTION_UP) {
805
+ val valid = toolbarKeyboardKey != null && toolbarKeyboardKey == committedToolbarKey
806
+ toolbarKeyboardKey = null
807
+ toolbar.isPressed = false
808
+ valid && performToolbarPress(false)
809
+ } else false
810
+ }
328
811
  visibility = GONE
329
812
  }
330
813
 
331
814
  fun updateItemsJSON(value: String?) {
815
+ items = parseHeaderItems(value)
332
816
  row.updateItemsJSON(value)
333
817
  visibility = row.visibility
818
+ updateConfigJSON(config.toString())
334
819
  }
335
820
 
336
821
  fun updateStyle(
337
822
  height: Double,
823
+ variant: String,
338
824
  contentPadding: Double,
825
+ contentPaddingVertical: Double,
339
826
  itemSpacing: Double,
340
827
  fontSize: Double,
341
828
  fontFamily: String?,
@@ -351,6 +838,8 @@ internal class CollapsiblePagerNativeTabBarView(context: Context) : FrameLayout(
351
838
  fontFamily,
352
839
  indicatorHeight,
353
840
  indicatorBottom,
841
+ variant,
842
+ contentPaddingVertical,
354
843
  )
355
844
  requestLayout()
356
845
  }
@@ -360,15 +849,95 @@ internal class CollapsiblePagerNativeTabBarView(context: Context) : FrameLayout(
360
849
  activeTextColor: Int,
361
850
  inactiveTextColor: Int,
362
851
  indicatorColor: Int,
363
- ) = row.updateColors(
364
- backgroundColor,
365
- activeTextColor,
366
- inactiveTextColor,
367
- Color.TRANSPARENT,
368
- indicatorColor,
369
- )
852
+ ) {
853
+ val text = row.usesTextVariant()
854
+ setBackgroundColor(if (text) backgroundColor else Color.TRANSPARENT)
855
+ row.updateColors(
856
+ if (text) Color.TRANSPARENT else backgroundColor,
857
+ activeTextColor,
858
+ inactiveTextColor,
859
+ Color.TRANSPARENT,
860
+ indicatorColor,
861
+ )
862
+ }
863
+
864
+ private fun controlledPageIndices(): List<Int>? {
865
+ val pageKeys = config.optJSONArray("pageKeys") ?: return null
866
+ val names = List(pageKeys.length()) { pageKeys.optString(it) }
867
+ val indices = names.map { name -> items.indexOfFirst { it.key == name } }
868
+ if (names.isEmpty() || selectedKey !in names || names.toSet().size != names.size ||
869
+ indices.any { it < 0 } || items.map { it.key }.toSet().size != items.size) return null
870
+ return indices
871
+ }
872
+
873
+ fun usesControlledTextProgress(): Boolean {
874
+ return row.usesProgressDrivenItems() && config.optBoolean("controlled") && controlledPageIndices() != null
875
+ }
876
+
877
+ // The tab row and toolbar share a centered band no wider than contentMaxWidth;
878
+ // the bar background still covers the full width.
879
+ private fun contentBand(width: Int): IntArray {
880
+ val maxWidth = config.optDouble("contentMaxWidth", Double.NaN)
881
+ if (!maxWidth.isFinite() || maxWidth <= 0 || dp(maxWidth) >= width) return intArrayOf(0, width)
882
+ val bandWidth = dp(maxWidth)
883
+ val start = (width - bandWidth) / 2
884
+ return intArrayOf(start, start + bandWidth)
885
+ }
370
886
 
371
- fun setProgress(progress: Float) = row.setProgress(progress)
887
+ fun setProgress(progress: Float) {
888
+ lastNativeProgress = progress
889
+ hasNativeProgress = true
890
+ var mapped = progress
891
+ var source: Int? = null
892
+ var destination: Int? = null
893
+ var fraction = 0f
894
+ if (config.optBoolean("controlled")) {
895
+ val pageKeys = config.optJSONArray("pageKeys") ?: return
896
+ val indices = controlledPageIndices()
897
+ if (indices == null) {
898
+ val fallback = items.indexOfFirst { it.key == config.optString("selectedKey") }
899
+ if (fallback >= 0) { row.setProgress(fallback.toFloat()); selectedKey = items[fallback].key; updateToolbar() }
900
+ return
901
+ }
902
+ val bounded = progress.coerceIn(0f, (pageKeys.length() - 1).toFloat())
903
+ val lower = floor(bounded).toInt().coerceAtLeast(0)
904
+ val upper = min(lower + 1, pageKeys.length() - 1)
905
+ val from = indices[lower]
906
+ val to = indices[upper]
907
+ if (from < 0 || to < 0) return
908
+ fraction = bounded - lower
909
+ source = from
910
+ destination = to
911
+ mapped = from + (to - from) * fraction
912
+ }
913
+ row.setProgress(mapped, source, destination, fraction)
914
+ if (config.optBoolean("controlled")) return
915
+ val selectedIndex = mapped.roundToInt()
916
+ val nextKey = items.getOrNull(selectedIndex)?.key ?: return
917
+ if (nextKey != selectedKey) { toolbarTouchKey = null; toolbar.isPressed = false; selectedKey = nextKey; updateToolbar() }
918
+ }
919
+
920
+ override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
921
+ val width = MeasureSpec.getSize(widthMeasureSpec)
922
+ val height = MeasureSpec.getSize(heightMeasureSpec)
923
+ val reserved = dp(toolbarReservedWidth)
924
+ val band = contentBand(width)
925
+ row.measure(MeasureSpec.makeMeasureSpec(max(0, band[1] - band[0] - reserved), MeasureSpec.EXACTLY), heightMeasureSpec)
926
+ toolbar.measure(MeasureSpec.makeMeasureSpec(dp(toolbarSize), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(dp(toolbarSize), MeasureSpec.EXACTLY))
927
+ setMeasuredDimension(width, height)
928
+ }
929
+
930
+ override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
931
+ val width = right - left
932
+ val height = bottom - top
933
+ val reserved = dp(toolbarReservedWidth)
934
+ val rtl = layoutDirection == View.LAYOUT_DIRECTION_RTL
935
+ val band = contentBand(width)
936
+ row.layout(if (rtl) band[0] + reserved else band[0], 0, if (rtl) band[1] else band[1] - reserved, height)
937
+ val inset = dp(toolbarTrailingInset) - (dp(toolbarSize) - dp(toolbarContentWidth)) / 2
938
+ val x = if (rtl) band[0] + inset else band[1] - inset - dp(toolbarSize)
939
+ toolbar.layout(x, (height - dp(toolbarSize)) / 2, x + dp(toolbarSize), (height + dp(toolbarSize)) / 2)
940
+ }
372
941
 
373
942
  fun preferredHeightPx(): Int = heightPx
374
943
  }