@onekeyfe/react-native-pager-view 6.7.0-3 → 6.7.0-31

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