Skip to content
TypeScript

feat(mobile): use shared custom segmented controls (#20116)

Julius Marminge802b5d7c0b86
diff --git a/apps/mobile/src/components/ui/SegmentedControl.android.tsx b/apps/mobile/src/components/ui/SegmentedControl.android.tsx
deleted file mode 100644
index 46f9d51c94d..00000000000
--- a/apps/mobile/src/components/ui/SegmentedControl.android.tsx
+++ /dev/null
@@ -1,86 +0,0 @@
-import {
- Host,
- SegmentedButton,
- SingleChoiceSegmentedButtonRow,
- Text,
-} from "@expo/ui/jetpack-compose";
-import { defaultMinSize, fillMaxWidth } from "@expo/ui/jetpack-compose/modifiers";
-import { useAppearancePreferences } from "../../features/settings/appearance/AppearancePreferencesProvider";
-import { useScaledTextRole } from "../../features/settings/appearance/useScaledTextRole";
-import { View } from "react-native";
-
-import { useControlTheme } from "./useControlTheme";
-import type { SegmentedControlProps } from "./SegmentedControl.types";
-
-function HostedSegmentedControl<Value extends number | string>(
- props: SegmentedControlProps<Value>,
-) {
- const { colorScheme } = useControlTheme();
- return (
- <View className={props.className}>
- <View importantForAccessibility="no-hide-descendants">
- <Host
- matchContents={{ vertical: true }}
- colorScheme={colorScheme}
- ignoreSafeAreaKeyboardInsets
- style={{ width: "100%" }}
- >
- <SegmentedControlContent {...props} />
- </Host>
- </View>
- <View pointerEvents="none" className="absolute inset-0 flex-row">
- {props.options.map((option) => (
- <View
- key={String(option.value)}
- accessible
- accessibilityRole={props.role ?? "button"}
- accessibilityLabel={option.accessibilityLabel ?? option.label}
- accessibilityState={{ selected: option.value === props.selected }}
- accessibilityActions={[{ name: "activate" }]}
- onAccessibilityAction={() => props.onSelect(option.value)}
- className="flex-1"
- />
- ))}
- </View>
- </View>
- );
-}
-
-export type { SegmentedControlProps } from "./SegmentedControl.types";
-
-/** Compose content shared by screen controls and native dialogs, inside their existing Host. */
-function SegmentedControlContent<Value extends number | string>(
- props: SegmentedControlProps<Value>,
-) {
- const { themeVariables: colors } = useAppearancePreferences();
- const typography = useScaledTextRole("footnote");
- return (
- <SingleChoiceSegmentedButtonRow modifiers={[fillMaxWidth()]}>
- {props.options.map((option) => (
- <SegmentedButton
- key={String(option.value)}
- selected={option.value === props.selected}
- onClick={() => props.onSelect(option.value)}
- modifiers={[defaultMinSize({ minHeight: 48 })]}
- colors={{
- activeContainerColor: colors["--color-secondary"],
- activeContentColor: colors["--color-secondary-foreground"],
- inactiveContainerColor: "transparent",
- inactiveContentColor: colors["--color-foreground"],
- activeBorderColor: colors["--color-border"],
- inactiveBorderColor: colors["--color-border"],
- }}
- >
- <SegmentedButton.Label>
- <Text style={typography}>{option.label}</Text>
- </SegmentedButton.Label>
- </SegmentedButton>
- ))}
- </SingleChoiceSegmentedButtonRow>
- );
-}
-
-/** Content is for callers already inside an Android native Host. */
-export const SegmentedControl = Object.assign(HostedSegmentedControl, {
- Content: SegmentedControlContent,
-});
diff --git a/apps/mobile/src/components/ui/SegmentedControl.tsx b/apps/mobile/src/components/ui/SegmentedControl.tsx
index bc555c63914..8ebb515884f 100644
--- a/apps/mobile/src/components/ui/SegmentedControl.tsx
+++ b/apps/mobile/src/components/ui/SegmentedControl.tsx
@@ -1,51 +1,166 @@
-import { Picker } from "@expo/ui/swift-ui";
-import { View } from "react-native";
+import { useState } from "react";
+import { I18nManager, Platform, Pressable, View } from "react-native";
+import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
+import Animated, { useAnimatedStyle, useReducedMotion, withTiming } from "react-native-reanimated";
+import { AppText } from "./AppText";
import { useControlTheme } from "./useControlTheme";
-import { NativeThemeHost } from "./NativeThemeHost";
import type { SegmentedControlProps } from "./SegmentedControl.types";
export type { SegmentedControlProps } from "./SegmentedControl.types";
-/** Let UIKit own segment sizing, selection, and accessibility through SwiftUI. */
+/** Shared capsule control with native press targets and a raised selection. */
export function SegmentedControl<Value extends string | number>(
props: SegmentedControlProps<Value>,
) {
- const { colors } = useControlTheme();
+ const { colorScheme, colors } = useControlTheme();
+ const [layout, setLayout] = useState({ width: 0, height: 0 });
+ const { width, height } = layout;
+ const reduceMotion = useReducedMotion();
+ const selectedIndex = props.options.findIndex((option) => option.value === props.selected);
+ const segmentWidth = props.options.length ? Math.max(0, width - 6) / props.options.length : 0;
+ const selectionOffset = selectedIndex * segmentWidth * (I18nManager.isRTL ? -1 : 1);
+ const selectionStyle = useAnimatedStyle(() => ({
+ width: segmentWidth,
+ transform: [{ translateX: withTiming(selectionOffset, { duration: reduceMotion ? 0 : 160 }) }],
+ }));
+ const dark = colorScheme === "dark";
+ const minHeight = props.size === "compact" ? 32 : Platform.OS === "android" ? 40 : 36;
+
return (
- <View className={props.className}>
- <View accessibilityElementsHidden>
- <NativeThemeHost matchContents={{ vertical: true }} style={{ width: "100%" }}>
- <Picker
- selection={props.selected}
- onSelectionChange={props.onSelect}
- segments={props.options.map((option) => ({
- label: option.label,
- value: option.value,
- }))}
- segmentColors={{
- background: colors["--color-card"],
- selectedBackground: colors["--color-secondary"],
- text: colors["--color-foreground-muted"],
- selectedText: colors["--color-secondary-foreground"],
- }}
- />
- </NativeThemeHost>
- </View>
- <View pointerEvents="none" className="absolute inset-0 flex-row">
- {props.options.map((option) => (
- <View
- key={String(option.value)}
- accessible
- accessibilityRole={props.role ?? "button"}
- accessibilityLabel={option.accessibilityLabel ?? option.label}
- accessibilityState={{ selected: option.value === props.selected }}
- accessibilityActions={[{ name: "activate" }]}
- onAccessibilityAction={() => props.onSelect(option.value)}
- className="flex-1"
- />
- ))}
+ <View collapsable={false} className={props.className}>
+ <View
+ onLayout={(event) => setLayout(event.nativeEvent.layout)}
+ className="flex-row rounded-full p-[3px]"
+ style={{
+ minHeight,
+ boxShadow: dark ? "0px 1px 2px #00000062" : "0px 1px 2px #00000014",
+ }}
+ >
+ <CapsuleSurface
+ width={width}
+ height={height}
+ dark={dark}
+ fillTop={colors[dark ? "--color-screen" : "--color-grouped-card"]}
+ fillBottom={colors["--color-card"]}
+ edgeColor={colors["--color-foreground"]}
+ />
+ {selectedIndex >= 0 && width > 0 ? (
+ <Animated.View
+ pointerEvents="none"
+ className="absolute bottom-[3px] start-[3px] top-[3px] rounded-full"
+ style={[
+ {
+ boxShadow: dark ? "0px 1px 2px #00000046" : "0px 2px 3px #00000026",
+ },
+ selectionStyle,
+ ]}
+ >
+ <CapsuleSurface
+ width={segmentWidth}
+ height={height - 6}
+ dark={dark}
+ fillTop={colors[dark ? "--color-secondary" : "--color-screen"]}
+ fillBottom={colors[dark ? "--color-secondary" : "--color-screen"]}
+ edgeColor={colors["--color-secondary-foreground"]}
+ selected
+ />
+ </Animated.View>
+ ) : null}
+ {props.options.map((option) => {
+ const selected = option.value === props.selected;
+ return (
+ <Pressable
+ key={`${typeof option.value}:${option.value}`}
+ accessibilityRole={props.role ?? "button"}
+ accessibilityLabel={option.accessibilityLabel ?? option.label}
+ accessibilityState={{ selected }}
+ onPress={() => props.onSelect(option.value)}
+ className="flex-1 items-center justify-center rounded-full px-2 py-1 active:opacity-70"
+ style={{ minHeight: minHeight - 6 }}
+ >
+ <AppText
+ textRole="footnote"
+ className={selected ? "font-t3-bold" : "font-t3-medium"}
+ style={{
+ color:
+ colors[selected ? "--color-secondary-foreground" : "--color-foreground-muted"],
+ }}
+ >
+ {option.label}
+ </AppText>
+ </Pressable>
+ );
+ })}
</View>
</View>
);
}
+
+/** Pen's inset well and raised selection use opposite vertical edge lighting. */
+function CapsuleSurface({
+ width,
+ height,
+ dark,
+ fillTop,
+ fillBottom,
+ edgeColor,
+ selected = false,
+}: {
+ width: number;
+ height: number;
+ dark: boolean;
+ fillTop: string;
+ fillBottom: string;
+ edgeColor: string;
+ selected?: boolean;
+}) {
+ if (width <= 0 || height <= 0) return null;
+ const edgeOpacity = selected
+ ? dark
+ ? [0.22, 0.02]
+ : [0.13, 0.01]
+ : dark
+ ? [0.02, 0.16]
+ : [0.27, 0.1];
+ return (
+ <Svg
+ pointerEvents="none"
+ width={width}
+ height={height}
+ style={{ position: "absolute", top: 0, left: 0 }}
+ >
+ <Defs>
+ <LinearGradient id="fill" x1="0" y1="0" x2="0%" y2="100%">
+ <Stop offset="0" stopColor={fillTop} />
+ <Stop offset="1" stopColor={fillBottom} />
+ </LinearGradient>
+ <LinearGradient id="edge" x1="0" y1="0" x2="0%" y2="100%">
+ <Stop offset="0" stopColor={edgeColor} stopOpacity={edgeOpacity[0]} />
+ <Stop offset="1" stopColor={edgeColor} stopOpacity={edgeOpacity[1]} />
+ </LinearGradient>
+ </Defs>
+ <Rect
+ x={0.5}
+ y={0.5}
+ width={width - 1}
+ height={height - 1}
+ rx={(height - 1) / 2}
+ fill="url(#fill)"
+ />
+ {selected && !dark ? (
+ <Rect width={width} height={height} rx={height / 2} fill="white" fillOpacity={0.85} />
+ ) : null}
+ <Rect
+ x={0.5}
+ y={0.5}
+ width={width - 1}
+ height={height - 1}
+ rx={(height - 1) / 2}
+ fill="none"
+ stroke="url(#edge)"
+ strokeWidth={1}
+ />
+ </Svg>
+ );
+}
diff --git a/apps/mobile/src/components/ui/SegmentedControl.types.ts b/apps/mobile/src/components/ui/SegmentedControl.types.ts
index a259429e374..4def9ab2ea8 100644
--- a/apps/mobile/src/components/ui/SegmentedControl.types.ts
+++ b/apps/mobile/src/components/ui/SegmentedControl.types.ts
@@ -6,7 +6,7 @@ export interface SegmentedControlProps<Value extends number | string> {
}[];
readonly selected: Value;
readonly onSelect: (value: Value) => void;
- /** Native controls determine their own sizing. Kept for existing callers. */
+ /** Compact uses a 32-point capsule; default uses 36 points on iOS and 40 on Android. */
readonly size?: "default" | "compact";
/** "tab" for the view switcher; filters stay plain buttons. */
readonly role?: "tab" | "button";
diff --git a/apps/mobile/src/features/threads/CustomSnoozeSheet.android.tsx b/apps/mobile/src/features/threads/CustomSnoozeSheet.android.tsx
index 1ff270b1626..dc65543c37b 100644
--- a/apps/mobile/src/features/threads/CustomSnoozeSheet.android.tsx
+++ b/apps/mobile/src/features/threads/CustomSnoozeSheet.android.tsx
@@ -1,4 +1,4 @@
-import { SegmentedControl } from "../../components/ui/SegmentedControl.android";
+import { SegmentedControl } from "../../components/ui/SegmentedControl";
import {
BasicAlertDialog,
Column,
@@ -6,6 +6,7 @@ import {
Host,
FilledTonalIconButton,
Row,
+ RNHostView,
Shape,
Surface,
Text,
@@ -141,33 +142,37 @@ export function CustomSnoozeSheet(props: Props) {
modifiers={[fillMaxWidth(), padding(24, 24, 24, 16)]}
>
<Text style={titleTypography}>Custom snooze</Text>
- <SegmentedControl.Content
- options={modes}
- selected={mode}
- onSelect={(value) => {
- setMode(value);
- setError(null);
- }}
- />
- {mode === "date" ? (
- <SegmentedControl.Content
- options={[
- {
- value: "date",
- label: date.toLocaleDateString([], { month: "short", day: "numeric" }),
- },
- {
- value: "time",
- label: date.toLocaleTimeString([], {
- hour: "numeric",
- minute: "2-digit",
- hourCycle: is24Hour ? "h23" : "h12",
- }),
- },
- ]}
- selected={picker}
- onSelect={setPicker}
+ <RNHostView matchContents={{ vertical: true }} modifiers={[fillMaxWidth()]}>
+ <SegmentedControl
+ options={modes}
+ selected={mode}
+ onSelect={(value) => {
+ setMode(value);
+ setError(null);
+ }}
/>
+ </RNHostView>
+ {mode === "date" ? (
+ <RNHostView matchContents={{ vertical: true }} modifiers={[fillMaxWidth()]}>
+ <SegmentedControl
+ options={[
+ {
+ value: "date",
+ label: date.toLocaleDateString([], { month: "short", day: "numeric" }),
+ },
+ {
+ value: "time",
+ label: date.toLocaleTimeString([], {
+ hour: "numeric",
+ minute: "2-digit",
+ hourCycle: is24Hour ? "h23" : "h12",
+ }),
+ },
+ ]}
+ selected={picker}
+ onSelect={setPicker}
+ />
+ </RNHostView>
) : null}
</Column>
{mode === "date" ? (
@@ -224,7 +229,9 @@ export function CustomSnoozeSheet(props: Props) {
<Text style={titleTypography}>+</Text>
</FilledTonalIconButton>
</Row>
- <SegmentedControl.Content options={units} selected={unit} onSelect={setUnit} />
+ <RNHostView matchContents={{ vertical: true }} modifiers={[fillMaxWidth()]}>
+ <SegmentedControl options={units} selected={unit} onSelect={setUnit} />
+ </RNHostView>
</Column>
)}
<Column
diff --git a/patches/@[email protected] b/patches/@[email protected]
index 2f903720a76..2546d83b804 100644
--- a/patches/@[email protected]
+++ b/patches/@[email protected]
@@ -250,152 +250,6 @@ index 2457ed1..fdc8eb1 100644
import './MaterialSymbolsAssetsTransformer.fx';
export * from './AlertDialog';
export * from './Badge';
-diff --git a/build/swift-ui/Picker/index.d.ts b/build/swift-ui/Picker/index.d.ts
-index 5a97352..01e095b 100644
---- a/build/swift-ui/Picker/index.d.ts
-+++ b/build/swift-ui/Picker/index.d.ts
-@@ -7,6 +7,15 @@ export type PickerProps<T extends SelectionValueType = any> = {
- * For example: 'photo', 'heart.fill', 'star.circle'
- */
- systemImage?: SFSymbol;
-+ /** Native options rendered by a scoped UISegmentedControl. */
-+ segments?: { label: string; value: T }[];
-+ /** Only used with segments. */
-+ segmentColors?: {
-+ background?: string;
-+ selectedBackground?: string;
-+ text?: string;
-+ selectedText?: string;
-+ };
- /**
- * A label displayed on the picker.
- */
-diff --git a/ios/Picker/PickerView.swift b/ios/Picker/PickerView.swift
-index c78f278..9b6adf8 100644
---- a/ios/Picker/PickerView.swift
-+++ b/ios/Picker/PickerView.swift
-@@ -1,12 +1,27 @@
- // Copyright 2025-present 650 Industries. All rights reserved.
-
- import SwiftUI
-+import UIKit
- import ExpoModulesCore
-
-+internal struct PickerSegment: Record {
-+ @Field var label: String = ""
-+ @Field var value: Either<String, Double>?
-+}
-+
-+internal struct PickerSegmentColors: Record {
-+ @Field var background: Color?
-+ @Field var selectedBackground: Color?
-+ @Field var text: Color?
-+ @Field var selectedText: Color?
-+}
-+
- internal final class PickerProps: UIBaseViewProps {
- @Field var label: String?
- @Field var systemImage: String?
- @Field var selection: Either<String, Double>?
-+ @Field var segments: [PickerSegment]?
-+ @Field var segmentColors: PickerSegmentColors?
- var onSelectionChange = EventDispatcher()
- }
-
-@@ -25,7 +40,18 @@ internal struct PickerView: ExpoSwiftUI.View {
-
- let labelContent = props.children?.slot("label")
-
-- if let systemImage = props.systemImage, let label = props.label {
-+ if let segments = props.segments {
-+ NativeSegmentedPicker(
-+ segments: segments,
-+ colors: props.segmentColors,
-+ selection: Self.getHashableFromEither(props.selection),
-+ onSelectionChange: { index in
-+ guard segments.indices.contains(index),
-+ let value = Self.getHashableFromEither(segments[index].value) else { return }
-+ props.onSelectionChange(["selection": value.base])
-+ }
-+ )
-+ } else if let systemImage = props.systemImage, let label = props.label {
- Picker(label, systemImage: systemImage, selection: $selection) { content }
- } else if let labelContent {
- Picker(selection: $selection) { content } label: { labelContent }
-@@ -63,7 +89,7 @@ internal struct PickerView: ExpoSwiftUI.View {
- }
- }
-
-- private static func getHashableFromEither(_ either: Either<String, Double>?) -> AnyHashable? {
-+ fileprivate static func getHashableFromEither(_ either: Either<String, Double>?) -> AnyHashable? {
- guard let either else { return nil }
- if let stringValue: String = either.get() {
- return stringValue
-@@ -74,3 +100,64 @@ internal struct PickerView: ExpoSwiftUI.View {
- return nil
- }
- }
-+
-+
-+/// Instance-scoped styling: never changes UISegmentedControl.appearance().
-+private struct NativeSegmentedPicker: UIViewRepresentable {
-+ let segments: [PickerSegment]
-+ let colors: PickerSegmentColors?
-+ let selection: AnyHashable?
-+ let onSelectionChange: (Int) -> Void
-+
-+ func makeCoordinator() -> Coordinator {
-+ Coordinator(onSelectionChange: onSelectionChange)
-+ }
-+
-+ func makeUIView(context: Context) -> UISegmentedControl {
-+ let control = UISegmentedControl()
-+ control.addTarget(context.coordinator, action: #selector(Coordinator.changed(_:)), for: .valueChanged)
-+ control.setContentHuggingPriority(.defaultLow, for: .horizontal)
-+ return control
-+ }
-+
-+ func updateUIView(_ control: UISegmentedControl, context: Context) {
-+ context.coordinator.onSelectionChange = onSelectionChange
-+ let labels = segments.map(\.label)
-+ if context.coordinator.labels != labels {
-+ control.removeAllSegments()
-+ for (index, label) in labels.enumerated() {
-+ control.insertSegment(withTitle: label, at: index, animated: false)
-+ }
-+ context.coordinator.labels = labels
-+ }
-+ control.selectedSegmentIndex = segments.firstIndex {
-+ PickerView.getHashableFromEither($0.value) == selection
-+ } ?? UISegmentedControl.noSegment
-+ control.backgroundColor = colors?.background.map { UIColor($0) }
-+ control.selectedSegmentTintColor = colors?.selectedBackground.map { UIColor($0) }
-+ control.setTitleTextAttributes(
-+ colors?.text.map { [.foregroundColor: UIColor($0)] }, for: .normal
-+ )
-+ control.setTitleTextAttributes(
-+ colors?.selectedText.map { [.foregroundColor: UIColor($0)] }, for: .selected
-+ )
-+ control.isEnabled = context.environment.isEnabled
-+ }
-+
-+ func sizeThatFits(_ proposal: ProposedViewSize, uiView: UISegmentedControl, context: Context) -> CGSize? {
-+ CGSize(width: proposal.width ?? uiView.intrinsicContentSize.width, height: uiView.intrinsicContentSize.height)
-+ }
-+
-+ final class Coordinator: NSObject {
-+ var labels: [String] = []
-+ var onSelectionChange: (Int) -> Void
-+
-+ init(onSelectionChange: @escaping (Int) -> Void) {
-+ self.onSelectionChange = onSelectionChange
-+ }
-+
-+ @objc func changed(_ control: UISegmentedControl) {
-+ onSelectionChange(control.selectedSegmentIndex)
-+ }
-+ }
-+}
diff --git a/src/jetpack-compose/Host/index.tsx b/src/jetpack-compose/Host/index.tsx
index e994f6e..d0ed70a 100644
--- a/src/jetpack-compose/Host/index.tsx
@@ -489,23 +343,3 @@ index 77fe3d7..3fa0fb9 100644
import './MaterialSymbolsAssetsTransformer.fx';
export * from './AlertDialog';
-diff --git a/src/swift-ui/Picker/index.tsx b/src/swift-ui/Picker/index.tsx
-index ab7d7ce..ceac7bf 100644
---- a/src/swift-ui/Picker/index.tsx
-+++ b/src/swift-ui/Picker/index.tsx
-@@ -13,6 +13,15 @@ export type PickerProps<T extends SelectionValueType = any> = {
- * For example: 'photo', 'heart.fill', 'star.circle'
- */
- systemImage?: SFSymbol;
-+ /** Native segmented options. Uses a scoped UISegmentedControl instead of SwiftUI Picker. */
-+ segments?: { label: string; value: T }[];
-+ /** Colors for the native segmented control. Only used with segments. */
-+ segmentColors?: {
-+ background?: string;
-+ selectedBackground?: string;
-+ text?: string;
-+ selectedText?: string;
-+ };
- /**
- * A label displayed on the picker.
- */
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 3f9e9c2f977..e1ef8366399 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -152,7 +152,7 @@ patchedDependencies:
'@clerk/[email protected]': 5f3738f8e5d50bfa467ce8afbaf7c2aa7c7c9adb95a2307424eb908f6af0d299
'@effect/[email protected]': 2731c9c3761c595f25ddc625a7d61ca376b389d5b3049ecb837c8940f21cfa02
'@expo/[email protected]': 90fa980e8b6480631fb2fbb04559834e3c612db40c550cd828f11be297d8d760
- '@expo/[email protected]': 11c3297659830464ef138e4e2b22b790350c901f57f5f01de07bcb70c43e32fc
+ '@expo/[email protected]': 5a26480373850c1a7943919aa21f904151b335a0cb01042109e0746def37923e
'@ff-labs/[email protected]': cc71fcec015f4d39bc96ae2e2bf6b0ca678124c722c66a7841efce9d34b5983c
'@legendapp/[email protected]': 680cc6a5c5b4a4032e467e7b3fde22f89a84c0ee2e6eac6fda737d6277cc0806
'@pierre/[email protected]': 298e94372dbd51846a4e26ece2ecc3e22eb1f94b0450b1f1a9c6fec127809be7
@@ -326,7 +326,7 @@ importers:
'@expo/ui':
specifier: 58.0.18
'@legendapp/list':
specifier: 'catalog:'
@@ -14898,7 +14898,7 @@ snapshots:
'@expo/[email protected]': {}
dependencies:
expo: 58.0.11(0279ba067f3e563cec3a046cc8b71592)
react: 19.3.0
@@ -19639,7 +19639,7 @@ snapshots:
dependencies:
'@expo/plist': 0.10.1
expo: 58.0.11(0279ba067f3e563cec3a046cc8b71592)
react: 19.3.0