@onekeyfe/react-native-pager-view 6.7.0-alpha.475 → 6.8.0-11

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.
package/README.md CHANGED
@@ -1,5 +1,158 @@
1
+ <div align="center">
2
+
1
3
  # @onekeyfe/react-native-pager-view
2
4
 
5
+ **OneKey's Fabric fork of `react-native-pager-view`: swipeable pages, a collapsible shared header and a native vertical scroller.**
6
+
7
+ [![npm](https://img.shields.io/npm/v/%40onekeyfe%2Freact-native-pager-view?label=npm&color=4D6BFE)](https://www.npmjs.com/package/@onekeyfe/react-native-pager-view)
8
+ [![license](https://img.shields.io/npm/l/%40onekeyfe%2Freact-native-pager-view?label=license&color=4D6BFE)](LICENSE)
9
+ ![iOS](https://img.shields.io/badge/iOS-000000?logo=apple&logoColor=white)
10
+ ![Android](https://img.shields.io/badge/Android-3DDC84?logo=android&logoColor=white)
11
+ ![Web](https://img.shields.io/badge/Web-4285F4?logo=googlechrome&logoColor=white)
12
+ ![Fabric](https://img.shields.io/badge/Fabric-4D6BFE)
13
+
14
+ </div>
15
+
16
+ PagerView flips horizontally or vertically between keyed child pages, rendered by
17
+ a Fabric native view on iOS and Android and by a DOM fallback on Web. This fork
18
+ adds `CollapsiblePagerView` — a header that collapses into a pinned sticky bar
19
+ while pages keep their own offsets and retention window — and `NativeScroller`, a
20
+ non-virtualized vertical scroller that joins that collapse. Upstream remains the
21
+ reference for the original pager behavior.
22
+
23
+ ## Features
24
+
25
+ - **Native paging** — horizontal/vertical pages with `setPage`,
26
+ `setPageWithoutAnimation`, `setScrollEnabled` and page events.
27
+ - **Collapsible shared header** — native scroll coordination on mobile and CSS
28
+ scroll timelines on Web via `WebCollapsiblePagerView`.
29
+ - **Bounded page retention** — the selected page and configured neighbours stay
30
+ mounted while distant subtrees are unmounted and restored at their offset.
31
+ - **Native tab bar** — underline, segmented, text and pill variants, toolbar
32
+ slots and controlled selection.
33
+
34
+ ## Installation
35
+
36
+ ```sh
37
+ yarn add @onekeyfe/react-native-pager-view \
38
+ @onekeyfe/react-native-image \
39
+ @onekeyfe/react-native-native-logger
40
+ ```
41
+
42
+ Peer dependencies: `react`, `react-native`, `@onekeyfe/react-native-image` (Web
43
+ icon helper) and `@onekeyfe/react-native-native-logger` (Android logging). Install
44
+ the app's iOS pods and rebuild the native binary; JavaScript-only does not
45
+ register the views:
46
+
47
+ ```sh
48
+ cd ios && pod install
49
+ ```
50
+
51
+ Android links through autolinking; deployment floors are iOS 15.1 and Android
52
+ API 24.
53
+
54
+ ## Usage
55
+
56
+ ```tsx
57
+ import PagerView, {
58
+ type PagerViewOnPageSelectedEvent,
59
+ } from '@onekeyfe/react-native-pager-view';
60
+ import { Text, View } from 'react-native';
61
+
62
+ <PagerView
63
+ style={{ flex: 1 }}
64
+ initialPage={0}
65
+ onPageSelected={(event: PagerViewOnPageSelectedEvent) => {
66
+ console.log('selected page', event.nativeEvent.position);
67
+ }}
68
+ >
69
+ <View key="welcome" style={{ flex: 1 }}>
70
+ <Text>Welcome</Text>
71
+ </View>
72
+ <View key="wallet" style={{ flex: 1 }}>
73
+ <Text>Wallet</Text>
74
+ </View>
75
+ </PagerView>
76
+ ```
77
+
78
+ The application owns page keys, content and any JS header chrome; the pager owns
79
+ page placement and gestures. Every child must be a keyed `<View>`.
80
+
81
+ ## API
82
+
83
+ ### Exports
84
+
85
+ | Export | Platforms | Description |
86
+ | --- | :-: | --- |
87
+ | `PagerView` (default) | iOS, Android, Web | Swipeable page container; native page host on mobile, DOM fallback on Web. |
88
+ | `CollapsiblePagerView` | iOS, Android, Web | Collapsible header + sticky bar wrapper. |
89
+ | `WebCollapsiblePagerView`, `useWebCollapsiblePagerPage()` | Web | Explicit Web collapse root that measures omitted heights, and the selected page's scroll owner. |
90
+ | `NativeScroller` | iOS, Android, Web | Non-virtualized vertical scroller; the Web export is a `ScrollView` implementation. |
91
+ | `usePagerView({ pagesAmount })` | iOS, Android, Web | Animated pager progress, scroll state and add/remove page helpers. |
92
+ | `ScrollEdgeEffect` | iOS | `hard` / `soft` values for iOS 26 top scroll-edge effects. |
93
+
94
+ ### `PagerView` props
95
+
96
+ | Prop | Type | Default | Platforms | Description |
97
+ | --- | --- | --- | :-: | --- |
98
+ | `initialPage`, `scrollEnabled`, `orientation` | `number`, `boolean`, `'horizontal' \| 'vertical'` | `0`, `true`, `'horizontal'` | all | First page, swipe enablement and paging axis. |
99
+ | `overdrag`, `pageMargin`, `layoutDirection` | `boolean`, `number`, `'ltr' \| 'rtl' \| 'locale'` | `false`, `0`, `'ltr'` | all | Past-edge movement, gap between pages and LTR/RTL order. |
100
+ | `nestedScrollEnabled` | `boolean` | `false` | iOS | Coordinates gestures with a parent pager at sub-tab boundaries. |
101
+ | `scrollSensitivity`, `keyboardDismissMode`, `offscreenPageLimit` | platform props | `2`, `none`, native | Android | Gesture sensitivity (`2`–`8`), keyboard dismissal and offscreen pages. |
102
+ | `onPageScroll`, `onPageSelected`, `onPageScrollStateChanged` | event callbacks | — | all | `{ position, offset }`, `{ position }` and `idle`/`dragging`/`settling`. |
103
+
104
+ The ref exposes `setPage`, `setPageWithoutAnimation` and `setScrollEnabled`.
105
+
106
+ ### `CollapsiblePagerView` props
107
+
108
+ | Prop | Type | Platforms | Description |
109
+ | --- | --- | :-: | --- |
110
+ | `header`, `stickyHeader`, `headerHeight`, `stickyHeaderHeight` | `ReactNode`, `number` | all | Collapsible content, the bar pinned after collapse and their measured heights. |
111
+ | `pageRetentionDistance` | `number` | all | Pages retained on each side of the selection. Defaults to `1`. |
112
+ | `nativeTabBar` | config object | iOS, Android, Web | Items, `controlled`/`selectedKey`, toolbar map and style variant. |
113
+ | `nativeTabPressAnimationEnabled` | `boolean` | iOS, Android | Per-press animation policy; see Caveats. |
114
+ | `onMountedPagesChanged`, `onCollapsibleStateChanged` | event callbacks | all | Mount state and settled diagnostics. |
115
+ | `topOverlay`, `topScrollEdgeEffect` | `ReactNode`, `'hard' \| 'soft'` | iOS 26+ | Fixed overlay above the header and UIKit's scroll-edge effect. |
116
+
117
+ The ref exposes `scrollHeaderBy(delta)` and `scrollHeaderToOffset(offset)` to move
118
+ the active page's collapse position.
119
+
120
+ ## Platform support
121
+
122
+ | Capability | iOS | Android | Web |
123
+ | --- | :-: | :-: | :-: |
124
+ | `PagerView` paging, events and imperative commands | ✅ | ✅ | ✅ DOM fallback |
125
+ | `CollapsiblePagerView` shared-header collapse | ✅ native | ✅ native | ✅ CSS scroll timelines |
126
+ | Page retention `pageRetentionDistance` | ✅ | ✅ | ✅ |
127
+ | Native tab bar (underline/segmented/text/pill) | ✅ | ✅ | ✅ text/pill |
128
+ | `NativeScroller` non-virtualized scroller | ✅ | ✅ | ⚠️ `ScrollView` implementation |
129
+ | iOS 26 top overlay / scroll-edge effect | ✅ | — | — |
130
+
131
+ ## Caveats
132
+
133
+ > [!IMPORTANT]
134
+ > Keep page child keys stable. Retention unmounts distant pages but keeps their
135
+ > slots and offsets; changing a key resets that page's retained state.
136
+
137
+ > [!WARNING]
138
+ > Omitting `nativeTabPressAnimationEnabled` animates adjacent tab presses and
139
+ > jumps for non-adjacent pages. Earlier versions animated every press — pass
140
+ > `true` to restore that behavior.
141
+
142
+ > [!NOTE]
143
+ > `NativeScroller` is not a virtualized list. Horizontal scrolling, sticky rows,
144
+ > snapping, zoom, automatic keyboard insets and the full ScrollView responder
145
+ > API are not provided.
146
+
147
+ ## References
148
+
149
+ - [Scroll and collapse contract](docs/SPEC.md)
150
+ - Example pages: [pager](../../example/react-native/pages/PagerViewTestPage.tsx) and [collapsible pager](../../example/react-native/pages/MarketNativePagerExamplePage.tsx)
151
+ - [npm package](https://www.npmjs.com/package/@onekeyfe/react-native-pager-view)
152
+ - [Changelog](../../CHANGELOG.md)
153
+
154
+ ## Upstream attribution
155
+
3
156
  First, a sincere thank-you to Callstack and the
4
157
  `react-native-pager-view` maintainers for their excellent work 🙏
5
158
 
@@ -16,145 +169,15 @@ unable to keep this work in patch form.
16
169
  As the gap grew, we ultimately forked `react-native-pager-view` to keep
17
170
  development and delivery stable.
18
171
 
19
- ## Upstream Project
20
-
21
- - Repository: [callstack/react-native-pager-view](https://github.com/callstack/react-native-pager-view)
172
+ - Upstream repository:
173
+ [callstack/react-native-pager-view](https://github.com/callstack/react-native-pager-view)
22
174
  - License: MIT
23
-
24
- ## Notes
25
-
26
175
  - This fork includes OneKey-specific adaptations for our product requirements.
27
- - If you are looking for original behavior and full documentation, please refer
28
- to the upstream repository.
29
-
30
- ## Collapsible pager
31
-
32
- `CollapsiblePagerView` is an opt-in container. The default `PagerView` export
33
- keeps its existing page lifetime and native implementation.
34
-
35
- ```tsx
36
- <CollapsiblePagerView
37
- header={<Header />}
38
- stickyHeader={<Tabs />}
39
- headerHeight={measuredHeaderHeight}
40
- stickyHeaderHeight={measuredTabsHeight}
41
- pageRetentionDistance={1}
42
- onMountedPagesChanged={({ mountedPages }) => {
43
- // Selected page plus one neighbour on each side by default.
44
- }}
45
- onCollapsibleStateChanged={({ nativeEvent }) => {
46
- // Settled diagnostics: headerOffset, native/attached page counts, etc.
47
- }}
48
- >
49
- {pages.map((page) => (
50
- <View key={page.key}>{page.content}</View>
51
- ))}
52
- </CollapsiblePagerView>
53
- ```
54
-
55
- Page keys must remain stable. The selected page and configured neighbours stay
56
- mounted for preheating; distant page slots remain in the pager while their
57
- React/native heavy subtrees are unmounted. iOS and Android retain a per-key
58
- scroll offset and preserve the shared header collapse when pages change. A
59
- NativeList can additionally restore its own stable item-key anchor when it is
60
- remounted; the pager does not replace that list-level anchor protocol or its
61
- cell reuse.
62
-
63
- On iOS the component observes the current `UIScrollView` content offset without
64
- replacing its delegate. Android coordinates nested scroll with the active
65
- `RecyclerView`. Web uses the active NativeList viewport automatically; another
66
- Web scroll child can opt in by exposing a DOM element with
67
- `data-collapsible-pager-scroll`. CSS scroll timelines drive header/sticky
68
- movement, so React is not updated on each vertical scroll frame.
69
- `pagerRef.current?.scrollHeaderBy(delta)` immediately moves the active page's
70
- collapsible header by a finite logical distance, clamped to its measured range.
71
- `scrollHeaderToOffset(offset)` targets an absolute collapse position, so a
72
- keyboard's own scroll adjustment cannot add a second relative movement.
73
- It is useful for revealing a focused field above a keyboard.
74
-
75
- On Web, `WebCollapsiblePagerView` is an explicit root export of the existing Web
76
- pager. It measures Header and sticky content when their heights are omitted.
77
- `isActive` describes route visibility; the pager preserves a pending scroll
78
- target across a short or temporarily hidden page and retries when real content
79
- geometry becomes ready. `useWebCollapsiblePagerPage()` exposes the selected
80
- page's scroll owner, visible metrics, content registration and pending target
81
- to descendants. These Web-only APIs require a DOM when mounted. Native callers
82
- continue to use `CollapsiblePagerView`.
83
-
84
- On iOS and Android, `nativeTabBar` renders the tab bar natively and
85
- `onNativeTabPress` reports presses. By default, adjacent tab presses animate and
86
- non-adjacent presses jump directly to the target without passing intermediate
87
- pages. Set `nativeTabPressAnimationEnabled={true}` to always animate, or `false`
88
- to always jump. Swipe gestures and imperative page commands are unchanged.
89
-
90
- The `text` variant supports `controlled`, stable `selectedKey` and one per-key
91
- `toolbar` map. Controlled presses report intent; the caller keeps page commands,
92
- menus and routing. Label colors follow actual page movement while selected font
93
- weight follows business selection. Toolbar artwork, label, action key and selected
94
- background transfer together only when the final physical page and selection
95
- agree. Motion keeps the old artwork with hit/AX disabled; two present icons replace
96
- in place, and only presence changes fade for about 100 ms. Omitting `toolbar`
97
- reserves zero width; `{}` reserves 44 logical units, and nonempty maps use their
98
- largest `contentWidth + trailingInset`. Missing/failed content keeps that slot
99
- without an active control. See [the contract](docs/SPEC.md#text-tabs-controlled-selection-and-per-tab-toolbar)
100
- for ownership, cancellation, progress, fallback and current acceptance limits.
101
-
102
- > **Behavior change:** earlier versions animated every native tab press when
103
- > `nativeTabPressAnimationEnabled` was omitted. Pass
104
- > `nativeTabPressAnimationEnabled={true}` to keep that behavior.
176
+ - For original behavior and full documentation, refer to the upstream repository.
105
177
 
106
178
  Thank you again to Callstack and everyone who contributes to
107
179
  `react-native-pager-view` 💙
108
180
 
109
- The native ancestor-scroll contribution protocol is specified in [docs/SPEC.md](docs/SPEC.md).
110
-
111
- ## NativeScroller compatibility
112
-
113
- The independent iOS/Android `NativeScroller` has passing native builds and
114
- focused simulator checks. The complete acceptance matrix remains open; see
115
- [docs/SPEC.md](docs/SPEC.md) for the verified cases and limits. It is a
116
- non-virtualized vertical scroller with one internal React content View. Fabric/Yoga lays out React children and content padding; size
117
- changes are sent to native through layout props, not a JavaScript scroll loop.
118
- Shared Fabric native state tracks local scroll displacement and ancestor header
119
- travel separately, without per-frame JavaScript coordination. Descendant hit
120
- testing and `measureInWindow` use that state; device acceptance must compare the
121
- reported coordinates with visible React content after scrolling and page return.
122
- The automatic flexGrow minimum uses a native-reported usable content height,
123
- with static pager reservations accounted for once. This internal size event is
124
- not public API and does not run on scroll frames. Before it arrives the automatic
125
- minimum is zero; a larger explicit numeric minHeight remains authoritative.
126
- Refresh insets and content-dependent bottom fill do not change this minimum.
127
- Web continues using its existing ScrollView implementation.
128
-
129
- The supported ScrollView subset is `contentContainerStyle` (including padding,
130
- height, numeric minHeight and flexGrow), `onContentSizeChange`, `scrollEnabled`,
131
- `nestedScrollEnabled`, indicators, `bounces`, `alwaysBounceVertical`,
132
- `contentInset`, keyboard dismissal/persist-tap modes, `scrollEventThrottle`, and
133
- the scroll/drag/momentum callbacks. Standard View props remain available.
134
- `decelerationRate` applies on iOS; Android uses AndroidX's native fling physics.
135
- `bounces`/`alwaysBounceVertical` and refresh tint/title are iOS controls; Android
136
- uses refresh colors/background/size and does not expose a bounce policy here.
137
- Tap-to-dismiss uses RN 0.86's JavaScript TextInput registry to preserve taps on
138
- another input and child-handled presses; keyboard behavior requires device checks.
139
- Horizontal scrolling, sticky rows, snapping, zoom, automatic keyboard insets and
140
- the full ScrollView responder API are not provided.
141
-
142
- Pass a standard `<RefreshControl refreshing={value} onRefresh={callback} />` as
143
- `refreshControl`. Its enabled, tint/colors, background, offset, title/title color
144
- and size props map to the component's native refresh controller; the RN refresh
145
- element is not mounted. Refreshing remains controlled even if the callback does
146
- not change the value. Arbitrary custom refresh components are not supported.
147
-
148
- `NativeScrollerRef` exposes `scrollTo`, `scrollToEnd`, `flashScrollIndicators`,
149
- host measurement/focus methods, `getNativeScrollRef` and `getScrollableNode`.
150
- `pagerScrollKey` remains the stable primary-scroller identity. Native command
151
- events use the ScrollView event shape; UIKit/AndroidX continue owning gestures
152
- and momentum. Animated commands whose clamped target differs from the current
153
- position emit a momentum begin/end pair; a no-op emits no new pair. A new command,
154
- new touch, content-root replacement or detach ends the previous active sequence.
155
- The focused JS tests verify wrapper routing, not native scrolling,
156
- Yoga rendering, keyboard interaction or refresh placement on a device.
157
-
158
- The codegen type boundary uses React Native's public `CodegenTypes` namespace.
159
- RN 0.86.2/0.88.0 declaration and parser checks preserve emitted JS, native schemas
160
- and the existing NativeScroller method set; no private type import patch is needed.
181
+ ## License
182
+
183
+ MIT. See [LICENSE](LICENSE).
@@ -87,6 +87,8 @@ internal class CollapsiblePagerAdapter : RecyclerView.Adapter<ViewPagerViewHolde
87
87
  */
88
88
  // OneKey patch: Match the standard pager's nested horizontal gesture host.
89
89
  // Original: class CollapsiblePagerHost(context: Context) : FrameLayout(context), NestedScrollingParent3 {
90
+ // Kept for react-native-bottom-tabs, which calls `tryScrollToTop` by name on a tab double press.
91
+ @androidx.annotation.Keep
90
92
  class CollapsiblePagerHost(context: Context) : NestedScrollableHost(context), NestedScrollingParent3 {
91
93
  private enum class HeaderGestureOwner {
92
94
  NONE,
@@ -1130,11 +1132,22 @@ class CollapsiblePagerHost(context: Context) : NestedScrollableHost(context), Ne
1130
1132
  cancelPagerTop()
1131
1133
  }
1132
1134
 
1133
- internal fun scrollToTop(target: Int, animated: Boolean) {
1134
- if (target !in 0..1) return
1135
- scrollHeaderToOffset(if (target == 1) headerHeightPx else 0, animated)
1135
+ @androidx.annotation.Keep
1136
+ fun scrollToTop(target: Int, animated: Boolean) {
1137
+ tryScrollToTop(target, animated)
1136
1138
  }
1137
1139
 
1140
+ @androidx.annotation.Keep
1141
+ fun tryScrollToTop(target: Int, animated: Boolean): Boolean {
1142
+ if (target !in 0..1) return false
1143
+ return scrollHeaderToOffset(if (target == 1) headerHeightPx else 0, animated)
1144
+ }
1145
+
1146
+ // The header offset is stored apart from the body, so a collapsed header can sit
1147
+ // above a body that is already at its top.
1148
+ @androidx.annotation.Keep
1149
+ fun isAwayFromPageTop(): Boolean = headerOffsetPx > 0
1150
+
1138
1151
  internal fun scrollHeaderBy(delta: Double) {
1139
1152
  if (!delta.isFinite()) return
1140
1153
  val density = resources.displayMetrics.density.toDouble()
@@ -1150,13 +1163,13 @@ class CollapsiblePagerHost(context: Context) : NestedScrollableHost(context), Ne
1150
1163
  scrollHeaderToOffset(targetPx, false)
1151
1164
  }
1152
1165
 
1153
- private fun scrollHeaderToOffset(logicalOffset: Int, animated: Boolean) {
1166
+ private fun scrollHeaderToOffset(logicalOffset: Int, animated: Boolean): Boolean {
1154
1167
  if (pager.scrollState != ViewPager2.SCROLL_STATE_IDLE || transitionHeaderOffsets != null ||
1155
- syntheticPageRestore || selectedPage !in 0 until adapter.itemCount || !isAttachedToWindow) return
1156
- val view = observedRecyclerView ?: observedOwnedScroller ?: observedNativeScroller ?: return
1168
+ syntheticPageRestore || selectedPage !in 0 until adapter.itemCount || !isAttachedToWindow) return false
1169
+ val view = observedRecyclerView ?: observedOwnedScroller ?: observedNativeScroller ?: return false
1157
1170
  val key = currentPageKey()
1158
1171
  val ownerKey = observedRecyclerKey ?: observedOwnedScrollerKey ?: observedNativeScrollerKey
1159
- if (ownerKey != key || !view.isAttachedToWindow || primaryScrollableForPage(selectedPage) !== view) return
1172
+ if (ownerKey != key || !view.isAttachedToWindow || primaryScrollableForPage(selectedPage) !== view) return false
1160
1173
  // Finish old child notifications before installing the new Pager-owned target.
1161
1174
  cancelPagerTop()
1162
1175
  if (view is RecyclerView) {
@@ -1203,6 +1216,7 @@ class CollapsiblePagerHost(context: Context) : NestedScrollableHost(context), Ne
1203
1216
  }
1204
1217
  } finally { dispatchingPagerTop = false }
1205
1218
  finishPagerTopIfSettled()
1219
+ return true
1206
1220
  }
1207
1221
 
1208
1222
  private fun hasExplicitTopCommand(view: View, key: String): Boolean {
@@ -86,6 +86,9 @@ private class CollapsiblePagerHorizontalItemsView(
86
86
  private var contentPaddingVerticalPx = 0
87
87
  private var segmented = false
88
88
  private var textVariant = false
89
+ private var pillVariant = false
90
+ private var itemPaddingHorizontalDp: Double? = null
91
+ private var pillAnimationEnabled = true
89
92
  private var itemSpacingPx = dp(8.0)
90
93
  private var fontSize = if (showsProgressIndicator) 16.0 else 14.0
91
94
  private var fontFamily: String? = null
@@ -177,6 +180,7 @@ private class CollapsiblePagerHorizontalItemsView(
177
180
  val wasSegmented = segmented
178
181
  segmented = showsProgressIndicator && variant == "segmented"
179
182
  textVariant = showsProgressIndicator && variant == "text"
183
+ pillVariant = showsProgressIndicator && variant == "pill"
180
184
  itemSpacingPx = max(0, dp(itemSpacing))
181
185
  this.fontSize = max(1.0, fontSize)
182
186
  this.fontFamily = fontFamily
@@ -217,6 +221,25 @@ private class CollapsiblePagerHorizontalItemsView(
217
221
 
218
222
  fun usesTextVariant(): Boolean = textVariant
219
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
+
220
243
  fun setActiveFontFamily(value: String?) { activeFontFamily = value; requestLayout() }
221
244
 
222
245
  fun setProgress(value: Float, source: Int? = null, destination: Int? = null, fraction: Float = 0f) {
@@ -253,7 +276,7 @@ private class CollapsiblePagerHorizontalItemsView(
253
276
  val fontOwner = visualFontOwnerIndex(buttons.indexOfFirst { it.isSelected })
254
277
  buttons.forEachIndexed { index, button ->
255
278
  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)
279
+ button.setPadding(itemPaddingPx(), 0, itemPaddingPx(), 0)
257
280
  button.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize.toFloat())
258
281
  }
259
282
  }
@@ -332,11 +355,20 @@ private class CollapsiblePagerHorizontalItemsView(
332
355
  dp(20.0)
333
356
  }
334
357
  val buttonWidth = max(dp(44.0), textWidth + horizontalPadding)
335
- val indicatorWidth = textWidth
358
+ val indicatorWidth = if (pillVariant) buttonWidth else textWidth
336
359
  val indicatorX = x + (buttonWidth - indicatorWidth) / 2
337
360
  itemFrames.add(intArrayOf(x, buttonWidth, indicatorX, indicatorWidth))
338
- val itemHeight = if (showsProgressIndicator) height else min(dp(32.0), height)
339
- 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
+ }
340
372
  button.layoutParams = FrameLayout.LayoutParams(buttonWidth, itemHeight).apply {
341
373
  leftMargin = x
342
374
  topMargin = top
@@ -377,19 +409,44 @@ private class CollapsiblePagerHorizontalItemsView(
377
409
  val selectedIndex: Int
378
410
  val scrollTargetCenterX: Float
379
411
  if (showsProgressIndicator) {
380
- 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())
381
419
  val lower = floor(clamped).toInt()
382
420
  val upper = min(lower + 1, buttons.lastIndex)
383
421
  val fraction = clamped - lower
384
422
  val from = itemFrames[lower]
385
423
  val to = itemFrames[upper]
386
- val interpolatedIndicatorX = from[2] + (to[2] - from[2]) * fraction
387
- 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
+ }
388
436
  val indicatorX = interpolatedIndicatorX.roundToInt()
389
437
  val indicatorWidth = interpolatedIndicatorWidth.roundToInt()
390
438
  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)
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
393
450
  indicator.layout(
394
451
  indicatorX,
395
452
  indicatorTop,
@@ -401,7 +458,7 @@ private class CollapsiblePagerHorizontalItemsView(
401
458
  selectedIndex = if (controlledSelectedKey != null) items.indexOfFirst { it.key == controlledSelectedKey } else clamped.roundToInt()
402
459
  val fontOwner = visualFontOwnerIndex(selectedIndex)
403
460
  buttons.forEachIndexed { index, button ->
404
- val emphasis = if (mappedSource != null && mappedDestination != null) {
461
+ val emphasis = if (!snapToSelection && mappedSource != null && mappedDestination != null) {
405
462
  (if (index == mappedSource) 1f - mappedFraction else 0f) + (if (index == mappedDestination) mappedFraction else 0f)
406
463
  } else 1f - min(1f, kotlin.math.abs(clamped - index))
407
464
  button.setTextColor(ColorUtils.blendARGB(inactiveTextColor, activeTextColor, emphasis))
@@ -473,6 +530,9 @@ internal class CollapsiblePagerNativeTabBarView(context: Context) : FrameLayout(
473
530
  fun updateConfigJSON(value: String?) {
474
531
  config = runCatching { JSONObject(value ?: "{}") }.getOrDefault(JSONObject())
475
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()
476
536
  selectedKey = if (config.optBoolean("controlled")) config.optString("selectedKey") else items.getOrNull(lastNativeProgress.roundToInt())?.key ?: ""
477
537
  row.setControlledSelectedKey(if (config.optBoolean("controlled")) selectedKey else null, controlledPageIndices() != null)
478
538
  if (hasNativeProgress) setProgress(lastNativeProgress)
@@ -811,7 +871,17 @@ internal class CollapsiblePagerNativeTabBarView(context: Context) : FrameLayout(
811
871
  }
812
872
 
813
873
  fun usesControlledTextProgress(): Boolean {
814
- return row.usesTextVariant() && config.optBoolean("controlled") && controlledPageIndices() != null
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)
815
885
  }
816
886
 
817
887
  fun setProgress(progress: Float) {
@@ -851,7 +921,8 @@ internal class CollapsiblePagerNativeTabBarView(context: Context) : FrameLayout(
851
921
  val width = MeasureSpec.getSize(widthMeasureSpec)
852
922
  val height = MeasureSpec.getSize(heightMeasureSpec)
853
923
  val reserved = dp(toolbarReservedWidth)
854
- row.measure(MeasureSpec.makeMeasureSpec(max(0, width - reserved), MeasureSpec.EXACTLY), heightMeasureSpec)
924
+ val band = contentBand(width)
925
+ row.measure(MeasureSpec.makeMeasureSpec(max(0, band[1] - band[0] - reserved), MeasureSpec.EXACTLY), heightMeasureSpec)
855
926
  toolbar.measure(MeasureSpec.makeMeasureSpec(dp(toolbarSize), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(dp(toolbarSize), MeasureSpec.EXACTLY))
856
927
  setMeasuredDimension(width, height)
857
928
  }
@@ -861,9 +932,10 @@ internal class CollapsiblePagerNativeTabBarView(context: Context) : FrameLayout(
861
932
  val height = bottom - top
862
933
  val reserved = dp(toolbarReservedWidth)
863
934
  val rtl = layoutDirection == View.LAYOUT_DIRECTION_RTL
864
- row.layout(if (rtl) reserved else 0, 0, if (rtl) width else width - reserved, height)
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)
865
937
  val inset = dp(toolbarTrailingInset) - (dp(toolbarSize) - dp(toolbarContentWidth)) / 2
866
- val x = if (rtl) inset else width - inset - dp(toolbarSize)
938
+ val x = if (rtl) band[0] + inset else band[1] - inset - dp(toolbarSize)
867
939
  toolbar.layout(x, (height - dp(toolbarSize)) / 2, x + dp(toolbarSize), (height + dp(toolbarSize)) / 2)
868
940
  }
869
941
 
@@ -254,7 +254,7 @@ class CollapsiblePagerViewManager : ViewGroupManager<CollapsiblePagerHost>(),
254
254
  @ReactProp(name = "nativeTabBarVariant")
255
255
  override fun setNativeTabBarVariant(view: CollapsiblePagerHost?, value: String?) {
256
256
  view ?: return
257
- view.nativeTabBarVariant = if (value == "segmented" || value == "text") value else "underline"
257
+ view.nativeTabBarVariant = if (value == "segmented" || value == "text" || value == "pill") value else "underline"
258
258
  view.applyNativeHeaderStyle()
259
259
  }
260
260