Files
orca/mobile/src/components/MobileSegmentedControl.tsx
T
NeilandKelvin Amoaba 5d61e00c6d build(mobile): upgrade to Expo SDK 58 and React Native 0.88 (#37935)
* build(mobile): upgrade to Expo SDK 58 and React Native 0.88

Expo 58 drops Zod from @expo/cli, which clears the last Zod 3 advisory
(GHSA-mrhx-c7xc-m3w5) in mobile along with its local patch and override.

- Expo 55 -> 58, React Native 0.83 -> 0.88, React 19.3, gesture-handler 3,
  webview 14, reanimated 4.7, worklets 0.13 (SDK 58 bundled versions,
  pinned below today's batch to respect minimumReleaseAge).
- Port the react-native and react-native-webview patches unchanged; drop
  expo-constants, expo-notifications, @expo/cli, expo-router, zod and
  query-string patches plus the zod/query-string/xcode>uuid overrides,
  which upstream fixed or no longer need.
- iOS minimum rises to 16.4 (Expo 58 / RN 0.88 requirement).
- Migrate to RN 0.88 strict types: instance ref types, NamedStyles,
  AppState.currentState, list header/footer nulls.
- Replace removed runtime APIs: InteractionManager -> idle callback with a
  macrotask fallback; StyleSheet.absoluteFillObject -> absoluteFill;
  FileHandle.readBytes -> readBytesSync (it became async).
- Resolve react-native/asset-registry for shared assets in Metro and alias
  the old registry path for react-native-svg in the desktop mobile-web bundle.
- Reduce the iOS scene plugin to the reconnect override; Expo 58's template
  now ships the scene delegate itself.

* fix(mobile): bridge react-native-svg web imports and libsodium runtime for RN 0.88

- Share react-native-svg web shims between the mobile-web build and its render
  checks: map the old asset-registry path to react-native-web's registry and stub
  the Android-only touch-sound TurboModule.
- Patch react-native-libsodium 1.7.0 to read the JSI runtime from the bridge proxy;
  RN 0.88 removed RCTCxxBridge.runtime.

* fix(mobile): use Expo 58's legacy promise resolver for audio permissions

* fix(mobile): skip null handles in the RPC recording timer shims for RN 0.88 types

* style(mobile): format MobilePRSidebar after rebase

* fix(mobile): name RN 0.88 text input refs for declarations; allow queued back in stack render check

- Type text input refs with an exported interface so declaration emit can name hook results
  (RN 0.88 aliases TextInputInstance to an unexported class).
- Expo Router 58 drains back() after a commit; check the interrupted push's exit from the
  frame it starts, bounded to three frames of lag.

* chore(mobile): justify the text input handle interface for React Doctor

* chore(mobile): use a nameable intersection alias for text input refs

* fix(mobile): use sync expo-file-system writes, copies and moves on Expo 58

Expo 58 made File.write/copy/move and FileHandle.writeBytes return promises.
Our callers never awaited them, so failures escaped their try/catch and the
store's tmp-then-move and PDF writes could race their close or rename.

* build(mobile): raise the page bundle budget to 10 MiB for Expo 58

Expo 58 adds about 310 KB to the page: expo-router (+258 KB, now carrying
React Navigation, net about +110 KB) and Reanimated 4.7 (+152 KB). Main had
85 KB of headroom left. 10 MiB still stays within the 10 MiB per-asset contract.

* fix(mobile): drop the window-metrics seed RN 0.88 removed from Android

RN 0.88 no longer holds window metrics: DeviceInfoModule reads the activity's
WindowMetrics on demand and setWindowDisplayMetrics is gone, so MainActivity
no longer compiled. Layout scale still comes from the screen metrics we reseed.

---------

Co-authored-by: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com>
2026-11-11 23:30:02 +00:00

207 lines
7.6 KiB
TypeScript

import { useEffect, useRef, useState } from 'react'
import {
Pressable,
ScrollView,
Text,
View,
type ScrollViewInstance,
type StyleProp,
type ViewStyle
} from 'react-native'
import { triggerSelection } from '../platform/haptics'
import { resolveTabStripScrollOffset } from '../session/tabs/tab-strip-scroll'
import { colors, concentricRadius, feedback, radii, spacing } from '../theme/mobile-theme'
import { themedStyleSheet } from '../theme/themed-styles'
import { useMobileColorScheme } from '../theme/use-mobile-color-scheme'
export type MobileSegment<Value extends string> = {
value: Value
label: string
/** A longer spoken name where the short label leans on its surroundings. */
accessibilityLabel?: string
}
type Props<Value extends string> = {
segments: readonly MobileSegment<Value>[]
/** A value outside the segments selects none, e.g. one a newer host sent. */
selected: string | undefined
onSelect: (value: Value) => void
/** Prefixes each segment's testID with this, then the segment's value. */
testIDPrefix?: string
/** Segments share the full width instead of sizing to their labels. */
fill?: boolean
/** Like `fill`, but labels too long for an equal share widen their segment and the track scrolls. */
scrollWhenCrowded?: boolean
/** Paints the track like a sheet's grouped rows, so it stands out from the sheet. */
onSheet?: boolean
/** The track; its default color suits a panel-colored row. */
style?: StyleProp<ViewStyle>
/** Shown but not pickable, e.g. while the value it sets is locked. */
disabled?: boolean
/** The segments switch the content below, so screen readers hear tabs instead of radio buttons. */
tabs?: boolean
}
/** A pick-one pill control; each segment reads as a radio button, or as a tab with `tabs`. */
export function MobileSegmentedControl<Value extends string>(props: Props<Value>) {
useMobileColorScheme()
const [trackWidth, setTrackWidth] = useState(0)
const scrollRef = useRef<ScrollViewInstance>(null)
const scrollX = useRef(0)
const [widths] = useState(() => new Map<string, number>())
const revealSelected = (): void => {
if (!scrollRef.current || trackWidth === 0) {
return
}
const span = segmentSpan(props.segments, widths, props.selected)
if (span) {
const x = resolveTabStripScrollOffset({
...span,
viewportWidth: trackWidth,
currentOffset: scrollX.current,
margin: TRACK_INSET
})
scrollRef.current.scrollTo({ x, animated: false })
}
}
const segmentValues = props.segments.map((segment) => segment.value).join('\n')
// Not on every render: a re-render must not undo the user's own scroll.
useEffect(revealSelected, [props.selected, trackWidth, segmentValues])
// Equal shares that exactly fill the track while every label fits.
const equalShare = props.scrollWhenCrowded &&
trackWidth > 0 && {
minWidth: Math.floor((trackWidth - 2 * TRACK_INSET) / props.segments.length)
}
const accessibilityRole = props.tabs ? 'tablist' : 'radiogroup'
const segments = props.segments.map((segment) => {
const active = segment.value === props.selected
return (
<Pressable
key={segment.value}
onLayout={
props.scrollWhenCrowded
? (event) => {
// Widths, not x: web reports only size changes, so a shifted segment's x goes stale.
widths.set(segment.value, event.nativeEvent.layout.width)
revealSelected()
}
: undefined
}
accessibilityRole={props.tabs ? 'tab' : 'radio'}
aria-checked={props.tabs ? undefined : active}
accessibilityState={{
disabled: props.disabled === true,
...(props.tabs ? { selected: active } : {})
}}
disabled={props.disabled}
accessibilityLabel={segment.accessibilityLabel ?? segment.label}
testID={props.testIDPrefix ? `${props.testIDPrefix}${segment.value}` : undefined}
onPress={() => {
if (!active) {
triggerSelection()
}
props.onSelect(segment.value)
}}
// Stretches the 34 pt segment to a 44 pt touch box.
hitSlop={{ top: 5, bottom: 5 }}
style={({ pressed }) => [
styles.segment,
props.fill && !props.scrollWhenCrowded && styles.segmentFill,
props.scrollWhenCrowded && styles.segmentCrowdable,
equalShare,
active && (props.onSheet ? styles.segmentActiveOnSheet : styles.segmentActive),
pressed && !active && styles.segmentPressed
]}
>
<Text style={[styles.segmentText, active && styles.segmentTextActive]} numberOfLines={1}>
{segment.label}
</Text>
</Pressable>
)
})
const sheetStyle = props.onSheet && styles.segmentedOnSheet
if (!props.scrollWhenCrowded) {
return (
<View
style={[styles.segmented, sheetStyle, props.style]}
accessibilityRole={accessibilityRole}
>
{segments}
</View>
)
}
return (
<ScrollView
ref={scrollRef}
horizontal
// Fitting segments shouldn't rubber-band sideways on iOS.
alwaysBounceHorizontal={false}
showsHorizontalScrollIndicator={false}
style={[styles.scrollTrack, sheetStyle, props.style]}
contentContainerStyle={styles.scrollContent}
accessibilityRole={accessibilityRole}
onLayout={(event) => setTrackWidth(event.nativeEvent.layout.width)}
onScroll={(event) => {
scrollX.current = event.nativeEvent.contentOffset.x
}}
scrollEventThrottle={16}
>
{segments}
</ScrollView>
)
}
const TRACK_INSET = 3
/** Where the selected segment sits in the scrolled content, once every segment has a width. */
function segmentSpan(
segments: readonly MobileSegment<string>[],
widths: ReadonlyMap<string, number>,
selected: string | undefined
): { tabX: number; tabWidth: number; contentWidth: number } | undefined {
let left = TRACK_INSET
let span: { tabX: number; tabWidth: number } | undefined
for (const segment of segments) {
const width = widths.get(segment.value)
if (width === undefined) {
return undefined
}
if (segment.value === selected) {
span = { tabX: left, tabWidth: width }
}
left += width
}
return span && { ...span, contentWidth: left + TRACK_INSET }
}
const styles = themedStyleSheet(() => ({
segmented: {
flexDirection: 'row',
alignItems: 'center',
backgroundColor: colors.bgBase,
borderRadius: radii.control,
padding: TRACK_INSET
},
// Room above and below the label, so it doesn't sit against the track's edges.
segment: {
minHeight: 34,
justifyContent: 'center',
paddingHorizontal: spacing.md,
borderRadius: concentricRadius(radii.control, TRACK_INSET)
},
segmentFill: { flex: 1, alignItems: 'center', paddingHorizontal: spacing.xs },
segmentCrowdable: { flexGrow: 1, alignItems: 'center', paddingHorizontal: spacing.xs },
// The inset sits on the content, so segments scroll out under the track's rounded edge.
scrollTrack: { flexGrow: 0, backgroundColor: colors.bgBase, borderRadius: radii.control },
scrollContent: { flexGrow: 1, alignItems: 'center', padding: TRACK_INSET },
segmentedOnSheet: { backgroundColor: colors.sheetGroup },
segmentActive: { backgroundColor: colors.bgRaised },
// bgRaised is the sheet group's own color in dark; the switch's grey fill lifts off it in both themes.
segmentActiveOnSheet: { backgroundColor: colors.translucentFill },
segmentText: { fontSize: 13, color: colors.textSecondary, fontWeight: '600' },
segmentTextActive: { color: colors.textPrimary },
segmentPressed: { opacity: feedback.pressedOpacity }
}))