diff --git a/src/App.tsx b/src/App.tsx index 4c95b36da..9ebbfd903 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -95,14 +95,10 @@ if (IS_IOS) { void SystemUI.setBackgroundColorAsync('black') } if (IS_ANDROID) { - // iOS is handled by the config plugin -sfn - ScreenOrientation.lockAsync( - ScreenOrientation.OrientationLock.PORTRAIT_UP, - ).catch(error => - logger.debug('Could not lock orientation', {safeMessage: error}), + void ScreenOrientation.unlockAsync().catch(error => + logger.debug('Could not unlock orientation', {safeMessage: error}), ) } - /** * Begin geolocation ASAP */ diff --git a/src/Navigation.tsx b/src/Navigation.tsx index 0023f722b..bbb0b1c25 100644 --- a/src/Navigation.tsx +++ b/src/Navigation.tsx @@ -1,4 +1,4 @@ -import {type JSX, useCallback, useRef} from 'react' +import {type JSX, useCallback, useEffect, useRef} from 'react' import * as Linking from 'expo-linking' import * as Notifications from 'expo-notifications' import {Referrer} from '@bsky.app/expo-bluesky-swiss-army' @@ -32,10 +32,17 @@ import { } from '#/lib/hooks/useNotificationHandler' import {useWebScrollRestoration} from '#/lib/hooks/useWebScrollRestoration' import {useCallOnce} from '#/lib/once' -import {buildStateObject, getCurrentRoute} from '#/lib/routes/helpers' +import { + buildStateObject, + getCurrentRoute, + getTabState, + TabState, +} from '#/lib/routes/helpers' +import {type SidebarTab} from '#/lib/routes/tab-to-nav-item' import { type AllNavigatorParams, type BottomTabNavigatorParams, + type CommonNavigatorParams, type FlatNavigatorParams, type HomeTabNavigatorParams, type MessagesTabNavigatorParams, @@ -47,13 +54,19 @@ import { } from '#/lib/routes/types' import {bskyTitle} from '#/lib/strings/headings' import {CHAT_INVITE_CODE_REGEX} from '#/lib/strings/url-helpers' +import {emitSoftReset} from '#/state/events' import {useUnreadNotifications} from '#/state/queries/notifications/unread' import {useSession} from '#/state/session' -import {useLoggedOutViewControls} from '#/state/shell/logged-out' +import {useOnboardingState} from '#/state/shell' +import { + useLoggedOutView, + useLoggedOutViewControls, +} from '#/state/shell/logged-out' import { shouldRequestEmailConfirmation, snoozeEmailConfirmationPrompt, } from '#/state/shell/reminders' +import {useShellLayout} from '#/state/shell/shell-layout' import {useCloseAllActiveElements} from '#/state/util' import {CommunityGuidelinesScreen} from '#/view/screens/CommunityGuidelines' import {CopyrightPolicyScreen} from '#/view/screens/CopyrightPolicy' @@ -72,6 +85,8 @@ import {SupportScreen} from '#/view/screens/Support' import {TermsOfServiceScreen} from '#/view/screens/TermsOfService' import {BottomBar} from '#/view/shell/bottom-bar/BottomBar' import {createNativeStackNavigatorWithAuth} from '#/view/shell/createNativeStackNavigatorWithAuth' +import {DesktopLeftNav} from '#/view/shell/desktop/LeftNav' +import {getNativeTabBarVisibility} from '#/view/shell/nativeTabBarVisibility' import {AtmosphereScreen} from '#/screens/Atmosphere' import {BookmarksScreen} from '#/screens/Bookmarks' import {CustomFeedScreen} from '#/screens/CustomFeed' @@ -135,7 +150,7 @@ import { import {Wizard} from '#/screens/StarterPack/Wizard' import TopicScreen from '#/screens/Topic' import {VideoFeed} from '#/screens/VideoFeed' -import {type Theme, useTheme} from '#/alf' +import {type Theme, useBreakpoints, useTheme} from '#/alf' import { EmailDialogScreenID, useEmailDialogControl, @@ -157,6 +172,7 @@ const MyProfileTab = createNativeStackNavigatorWithAuth() const MessagesTab = createNativeStackNavigatorWithAuth() +const SecondaryTab = createNativeStackNavigatorWithAuth() const Flat = createNativeStackNavigatorWithAuth() const Tab = createBottomTabNavigator() @@ -635,7 +651,7 @@ function TabsNavigator({ }) { const tabBar = useCallback( (props: JSX.IntrinsicAttributes & BottomTabBarProps) => ( - + ), [], ) @@ -661,10 +677,114 @@ function TabsNavigator({ name="MyProfileTab" getComponent={() => MyProfileTabNavigator} /> + FeedsTabNavigator} /> + ListsTabNavigator} /> + BookmarksTabNavigator} + /> + SettingsTabNavigator} + /> ) } +function SecondaryTabNavigator({ + initialRouteName, +}: { + initialRouteName: keyof CommonNavigatorParams +}) { + const t = useTheme() + return ( + + {commonScreens(SecondaryTab as typeof Flat)} + + ) +} + +function FeedsTabNavigator() { + return +} + +function ListsTabNavigator() { + return +} + +function BookmarksTabNavigator() { + return +} + +function SettingsTabNavigator() { + return +} + +function NativeTabBar(props: BottomTabBarProps) { + const {gtMobile} = useBreakpoints() + const {hasSession, currentAccount} = useSession() + const onboardingState = useOnboardingState() + const {showLoggedOut} = useLoggedOutView() + const {footerHeight} = useShellLayout() + const currentRouteName = getCurrentRoute(props.state).name + const {showTabletSidebar, hideTabBar} = getNativeTabBarVisibility({ + gtMobile, + hasSession, + signupQueued: !!currentAccount?.signupQueued, + showLoggedOut, + onboardingActive: onboardingState.isActive, + isVideoFeed: currentRouteName === 'VideoFeed', + }) + + useEffect(() => { + if (showTabletSidebar || hideTabBar) { + footerHeight.set(0) + } + }, [showTabletSidebar, hideTabBar, footerHeight]) + + const onNavigateTab = (tab: SidebarTab) => { + const state = props.navigation.getState() + const tabState = getTabState(state, tab) + if (tabState === TabState.InsideAtRoot) { + emitSoftReset() + } else if (tabState === TabState.Inside) { + const target = state.routes.find(route => route.name === `${tab}Tab`) + ?.state?.key + if (target) { + props.navigation.dispatch({ + ...StackActions.popToTop(), + target, + }) + } else { + props.navigation.reset({ + index: 0, + routes: [{name: `${tab}Tab`}], + }) + } + } else { + // The tab navigator route names mirror the shared navigation tab names. + props.navigation.navigate(`${tab}Tab`) + } + } + + if (hideTabBar) { + return null + } + + if (showTabletSidebar) { + return ( + + ) + } + + return +} + function screenOptions(t: Theme) { return { fullScreenGestureEnabled: true, @@ -675,18 +795,20 @@ function screenOptions(t: Theme) { function HomeTabNavigator() { const t = useTheme() + const {gtMobile} = useBreakpoints() - const BLURRED_SCROLL_EDGE_EFFECT = IS_LIQUID_GLASS - ? ({ - headerShown: true, - headerTransparent: true, - headerTitle: '', - headerBackVisible: false, - scrollEdgeEffects: { - top: 'soft', - }, - } as const) - : {} + const BLURRED_SCROLL_EDGE_EFFECT = + IS_LIQUID_GLASS && !gtMobile + ? ({ + headerShown: true, + headerTransparent: true, + headerTitle: '', + headerBackVisible: false, + scrollEdgeEffects: { + top: 'soft', + }, + } as const) + : {} return ( @@ -895,6 +1017,14 @@ const LINKING = { if (name === 'Messages') { return buildStateObject('MessagesTab', 'Messages', params) } + if ( + name === 'Feeds' || + name === 'Lists' || + name === 'Bookmarks' || + name === 'Settings' + ) { + return buildStateObject(`${name}Tab`, name, params) + } // if the path is something else, like a post, profile, or even settings, we need to initialize the home tab as pre-existing state otherwise the back button will not work return buildStateObject('HomeTab', name, params, [ { diff --git a/src/alf/README.md b/src/alf/README.md index aa31bcf98..668537cd4 100644 --- a/src/alf/README.md +++ b/src/alf/README.md @@ -47,6 +47,19 @@ const t = useTheme() ### Breakpoints +Web and native use the same width thresholds: `gtPhone` at 500, `gtMobile` at +800, and `gtTablet` at 1300. On native, these follow the current app window, +not the device's screen or model. A compact tablet window stays below +`gtMobile`; the same device in a wider window can show the sidebar. Rotation, +Split View, and window resizing can cross these thresholds. + +Width does not imply mouse or hover support: keep touch actions available on +native tablets even when `gtMobile` is true. + +`useLayoutBreakpoints().rightNavVisible` stays false on native because the +native shell has no right rail. Feed modules that move into that rail on web +must remain in the native feed. + ```tsx const b = useBreakpoints() diff --git a/src/alf/breakpoints.native.ts b/src/alf/breakpoints.native.ts new file mode 100644 index 000000000..7323a0acc --- /dev/null +++ b/src/alf/breakpoints.native.ts @@ -0,0 +1,46 @@ +import {useContext, useSyncExternalStore} from 'react' +import {Dimensions} from 'react-native' + +import { + BreakpointWidthContext, + getBreakpoints, + getLayoutBreakpoints, +} from '#/alf/breakpoints.shared' + +export {type Breakpoint, BreakpointWidthContext} from '#/alf/breakpoints.shared' + +function subscribeToWindowWidth(onChange: () => void) { + const subscription = Dimensions.addEventListener('change', onChange) + return () => subscription.remove() +} + +function getWindowWidth() { + return Dimensions.get('window').width +} + +function useResponsiveWidth() { + // A height-only change (for example the keyboard) is not a breakpoint change. + const width = useSyncExternalStore( + subscribeToWindowWidth, + getWindowWidth, + getWindowWidth, + ) + const containerWidth = useContext(BreakpointWidthContext) + + return containerWidth ?? width +} + +export function useBreakpoints() { + return getBreakpoints(useResponsiveWidth()) +} + +export function useLayoutBreakpoints() { + const breakpoints = getLayoutBreakpoints(useResponsiveWidth()) + return { + ...breakpoints, + // Native has no right rail, so its feed modules must stay in the feed. + rightNavVisible: false, + // Unlike web, there is no right rail to offset the centered column for. + centerColumnOffset: false, + } +} diff --git a/src/alf/breakpoints.shared.ts b/src/alf/breakpoints.shared.ts new file mode 100644 index 000000000..699d25b64 --- /dev/null +++ b/src/alf/breakpoints.shared.ts @@ -0,0 +1,67 @@ +import {createContext} from 'react' + +export type Breakpoint = 'gtPhone' | 'gtMobile' | 'gtTablet' + +export const BREAKPOINTS = { + phone: 500, + mobile: 800, + tablet: 1300, + rightNav: 1100, +} as const + +/** The available width inside a native sheet or other contained surface. */ +export const BreakpointWidthContext = createContext( + undefined, +) + +export function getBreakpoints(width: number): Record & { + activeBreakpoint: Breakpoint | undefined +} { + const gtPhone = width >= BREAKPOINTS.phone + const gtMobile = width >= BREAKPOINTS.mobile + const gtTablet = width >= BREAKPOINTS.tablet + + return { + gtPhone, + gtMobile, + gtTablet, + activeBreakpoint: gtTablet + ? 'gtTablet' + : gtMobile + ? 'gtMobile' + : gtPhone + ? 'gtPhone' + : undefined, + } +} + +export function getLayoutBreakpoints(width: number) { + return { + rightNavVisible: width >= BREAKPOINTS.rightNav, + centerColumnOffset: + width >= BREAKPOINTS.rightNav && width <= BREAKPOINTS.tablet, + leftNavMinimal: width <= BREAKPOINTS.tablet, + } +} + +export function shouldCenterNativeTabletContent({ + gtMobile, + isWithinDialog, + isWithinSplitView, + isWithinOffsetView, + disabled = false, +}: { + gtMobile: boolean + isWithinDialog: boolean + isWithinSplitView: boolean + isWithinOffsetView: boolean + disabled?: boolean +}) { + return ( + gtMobile && + !isWithinDialog && + !isWithinSplitView && + !isWithinOffsetView && + !disabled + ) +} diff --git a/src/alf/breakpoints.test.tsx b/src/alf/breakpoints.test.tsx new file mode 100644 index 000000000..ec18ac3af --- /dev/null +++ b/src/alf/breakpoints.test.tsx @@ -0,0 +1,171 @@ +import {Dimensions} from 'react-native' +import {act, renderHook} from '@testing-library/react-native' + +import { + BreakpointWidthContext, + useBreakpoints, + useLayoutBreakpoints, +} from '#/alf/breakpoints.native' +import { + getLayoutBreakpoints, + shouldCenterNativeTabletContent, +} from '#/alf/breakpoints.shared' +import * as env from '#/env' + +jest.mock('#/env', () => ({__esModule: true, IS_IPAD: true})) + +const initialWindow = Dimensions.get('window') + +function setWindowWidth(width: number) { + act(() => { + Dimensions.set({ + window: {width, height: 1133, scale: 2, fontScale: 1}, + }) + }) +} + +afterEach(() => { + act(() => Dimensions.set({window: initialWindow})) + jest.restoreAllMocks() +}) + +describe('native responsive layout', () => { + it('keeps mini portrait compact and updates when its window rotates', () => { + setWindowWidth(744) + const {result, rerender} = renderHook(useBreakpoints) + + expect(result.current.gtMobile).toBe(false) + expect(result.current.activeBreakpoint).toBe('gtPhone') + + setWindowWidth(1133) + rerender({}) + expect(result.current.gtMobile).toBe(true) + expect(result.current.gtTablet).toBe(false) + + setWindowWidth(375) + rerender({}) + expect(result.current.activeBreakpoint).toBeUndefined() + }) + + it.each([ + [499, undefined], + [500, 'gtPhone'], + [799, 'gtPhone'], + [800, 'gtMobile'], + [1299, 'gtMobile'], + [1300, 'gtTablet'], + ] as const)('uses the web breakpoint at width %s', (width, expected) => { + setWindowWidth(width) + const {result} = renderHook(useBreakpoints) + expect(result.current.activeBreakpoint).toBe(expected) + }) + + it('uses the presented sheet width for its descendants', () => { + setWindowWidth(1366) + const {result} = renderHook(useBreakpoints, { + wrapper: ({children}) => ( + {children} + ), + }) + expect(result.current.gtPhone).toBe(false) + expect(result.current.gtMobile).toBe(false) + }) + + it('adapts wide non-iPad windows with the window width', () => { + jest.replaceProperty(env, 'IS_IPAD', false) + const subscribe = jest.spyOn(Dimensions, 'addEventListener') + setWindowWidth(744) + const {result} = renderHook(useBreakpoints) + expect(result.current.gtMobile).toBe(false) + expect(subscribe).toHaveBeenCalled() + + setWindowWidth(1366) + expect(result.current.gtMobile).toBe(true) + expect(result.current.gtTablet).toBe(true) + }) + + it('does not change breakpoints for a height-only resize', () => { + setWindowWidth(1024) + const {result} = renderHook(useBreakpoints) + const before = result.current + + act(() => { + Dimensions.set({ + window: {width: 1024, height: 600, scale: 2, fontScale: 1}, + }) + }) + expect(result.current).toBe(before) + }) + + it('keeps native centered columns centered without a right rail', () => { + setWindowWidth(1099) + const {result, rerender} = renderHook(useLayoutBreakpoints) + expect(result.current.rightNavVisible).toBe(false) + expect(result.current.centerColumnOffset).toBe(false) + + setWindowWidth(1100) + rerender({}) + expect(result.current).toEqual({ + rightNavVisible: false, + centerColumnOffset: false, + leftNavMinimal: true, + }) + + setWindowWidth(1366) + rerender({}) + expect(result.current).toEqual({ + rightNavVisible: false, + centerColumnOffset: false, + leftNavMinimal: false, + }) + }) + + it('preserves web right rail thresholds and its tablet column offset', () => { + expect(getLayoutBreakpoints(1099)).toMatchObject({ + rightNavVisible: false, + centerColumnOffset: false, + }) + expect(getLayoutBreakpoints(1100)).toMatchObject({ + rightNavVisible: true, + centerColumnOffset: true, + }) + expect(getLayoutBreakpoints(1366)).toMatchObject({ + rightNavVisible: true, + centerColumnOffset: false, + }) + }) + + it('does not apply a second native tablet offset to nested centered content', () => { + expect( + shouldCenterNativeTabletContent({ + gtMobile: true, + isWithinDialog: false, + isWithinSplitView: false, + isWithinOffsetView: true, + }), + ).toBe(false) + }) + + it('keeps full-bleed tablet content out of the centered column', () => { + expect( + shouldCenterNativeTabletContent({ + gtMobile: true, + isWithinDialog: false, + isWithinSplitView: false, + isWithinOffsetView: false, + disabled: true, + }), + ).toBe(false) + }) + + it('centers any wide native window outside contained surfaces', () => { + expect( + shouldCenterNativeTabletContent({ + gtMobile: true, + isWithinDialog: false, + isWithinSplitView: false, + isWithinOffsetView: false, + }), + ).toBe(true) + }) +}) diff --git a/src/alf/breakpoints.ts b/src/alf/breakpoints.ts index c9f66a77f..23dd3ebe4 100644 --- a/src/alf/breakpoints.ts +++ b/src/alf/breakpoints.ts @@ -1,14 +1,16 @@ import {useMemo} from 'react' import {useMediaQuery} from 'react-responsive' -export type Breakpoint = 'gtPhone' | 'gtMobile' | 'gtTablet' +import {type Breakpoint, BREAKPOINTS} from '#/alf/breakpoints.shared' + +export {type Breakpoint, BreakpointWidthContext} from '#/alf/breakpoints.shared' export function useBreakpoints(): Record & { activeBreakpoint: Breakpoint | undefined } { - const gtPhone = useMediaQuery({minWidth: 500}) - const gtMobile = useMediaQuery({minWidth: 800}) - const gtTablet = useMediaQuery({minWidth: 1300}) + const gtPhone = useMediaQuery({minWidth: BREAKPOINTS.phone}) + const gtMobile = useMediaQuery({minWidth: BREAKPOINTS.mobile}) + const gtTablet = useMediaQuery({minWidth: BREAKPOINTS.tablet}) return useMemo(() => { let active: Breakpoint | undefined if (gtTablet) { @@ -31,9 +33,12 @@ export function useBreakpoints(): Record & { * Fine-tuned breakpoints for the shell layout */ export function useLayoutBreakpoints() { - const rightNavVisible = useMediaQuery({minWidth: 1100}) - const centerColumnOffset = useMediaQuery({minWidth: 1100, maxWidth: 1300}) - const leftNavMinimal = useMediaQuery({maxWidth: 1300}) + const rightNavVisible = useMediaQuery({minWidth: BREAKPOINTS.rightNav}) + const centerColumnOffset = useMediaQuery({ + minWidth: BREAKPOINTS.rightNav, + maxWidth: BREAKPOINTS.tablet, + }) + const leftNavMinimal = useMediaQuery({maxWidth: BREAKPOINTS.tablet}) return { rightNavVisible, diff --git a/src/components/Layout/README.md b/src/components/Layout/README.md index 1bcc3489e..d691b58b4 100644 --- a/src/components/Layout/README.md +++ b/src/components/Layout/README.md @@ -98,8 +98,10 @@ looks roughly like this: This provides the "Content" functionality for a screen. This component is actually an `Animated.ScrollView`, and accepts props for that component. It -provides a little default styling as well. On web, it also _centers the content -inside our center content column of 600px_. +provides a little default styling as well. On web and wide native windows, +it _centers the content inside our center content column of 600px_. The scroll +view itself stays full width so gestures in the surrounding whitespace scroll +the content too. > [!NOTE] > What about flatlists or pagers? Those components are not colocated here (yet). @@ -142,6 +144,9 @@ screen for an example. This component behaves like our old `CenteredView` component. +Use it for non-scrolling content. `Layout.Content` and `List` center their own +contents; wrapping either in `Layout.Center` also constrains its scrollable area. + ### `Layout.SCROLLBAR_OFFSET` and `Layout.SCROLLBAR_OFFSET_POSITIVE` Provide a pre-configured CSS vars for use when aligning fixed position elements. diff --git a/src/components/Layout/index.tsx b/src/components/Layout/index.tsx index 256432593..06e13eec4 100644 --- a/src/components/Layout/index.tsx +++ b/src/components/Layout/index.tsx @@ -22,6 +22,7 @@ import { useTheme, web, } from '#/alf' +import {shouldCenterNativeTabletContent} from '#/alf/breakpoints.shared' import {useDialogContext} from '#/components/Dialog' import { CENTER_COLUMN_OFFSET, @@ -29,7 +30,7 @@ import { SCROLLBAR_OFFSET, } from '#/components/Layout/const' import {ScrollbarOffsetContext} from '#/components/Layout/context' -import {IS_WEB} from '#/env' +import {IS_IPAD, IS_WEB} from '#/env' export * from '#/components/Layout/const' export * as Header from '#/components/Layout/Header' @@ -38,6 +39,8 @@ export type ScreenProps = React.ComponentProps & { style?: StyleProp noInsetTop?: boolean minimalShell?: boolean + /** Skip the centered desktop-width borders for immersive content. */ + fullBleed?: boolean } /** @@ -47,16 +50,22 @@ export const Screen = memo(function Screen({ style, noInsetTop, minimalShell = false, + fullBleed = false, ...props }: ScreenProps) { const {top} = useSafeAreaInsets() const {isWithinSplitView} = useIsWithinSplitView() + const {gtMobile} = useBreakpoints() useEnableMinimalShellModeForScreen({enabled: minimalShell}) return ( <> - {IS_WEB && !isWithinSplitView && } + {IS_WEB && !fullBleed && !isWithinSplitView ? ( + + ) : !fullBleed && gtMobile && !isWithinSplitView ? ( + + ) : null} ({isWithinOffsetView: true}), []) // note - if we ever make the footer transparent in any way, // we'll need to change this to use contentInsets/scrollIndicatorInsets @@ -101,12 +127,20 @@ export const Content = memo(function Content({ } }) - return ( + const scrollView = ( {IS_WEB ? (
@@ -131,6 +182,14 @@ export const Content = memo(function Content({ )} ) + + return IS_WEB ? ( + scrollView + ) : ( + + {scrollView} + + ) }) /** @@ -208,3 +267,29 @@ const WebCenterBorders = memo(function LayoutWebCenterBorders() { /> ) : null }) + +const NativeCenterBorders = memo(function LayoutNativeCenterBorders() { + const t = useTheme() + const {centerColumnOffset} = useLayoutBreakpoints() + return ( + + ) +}) diff --git a/src/components/feeds/PostFeedVideoGridRow.tsx b/src/components/feeds/PostFeedVideoGridRow.tsx index 54c79c0af..5e9d9d8e0 100644 --- a/src/components/feeds/PostFeedVideoGridRow.tsx +++ b/src/components/feeds/PostFeedVideoGridRow.tsx @@ -2,7 +2,7 @@ import {View} from 'react-native' import {type FeedPostSliceItem} from '#/state/queries/post-feed' import {type VideoFeedSourceContext} from '#/screens/VideoFeed/types' -import {atoms as a, useGutters} from '#/alf' +import {atoms as a, useBreakpoints, useGutters} from '#/alf' import * as Grid from '#/components/Grid' import { VideoPostCard, @@ -12,6 +12,12 @@ import {useAnalytics} from '#/analytics' import {app} from '#/lexicons' import * as bsky from '#/types/bsky' +/** Keep feed batching, card widths, and placeholders on the same breakpoint. */ +export function useVideoGridColumns() { + const {gtMobile} = useBreakpoints() + return gtMobile ? 3 : 2 +} + export function PostFeedVideoGridRow({ items: slices, sourceContext, @@ -20,6 +26,7 @@ export function PostFeedVideoGridRow({ sourceContext: VideoFeedSourceContext }) { const ax = useAnalytics() + const columns = useVideoGridColumns() const gutters = useGutters(['base', 'base', 0, 'base']) const posts = slices .filter(slice => bsky.isType(app.bsky.embed.video.view, slice.post.embed)) @@ -39,7 +46,7 @@ export function PostFeedVideoGridRow({ {posts.map(post => ( - + - - + {Array.from({length: columns}, (_, index) => ( + + ))} ) diff --git a/src/components/hooks/useHeaderOffset.ts b/src/components/hooks/useHeaderOffset.ts index c965f522f..9c8c2a0f7 100644 --- a/src/components/hooks/useHeaderOffset.ts +++ b/src/components/hooks/useHeaderOffset.ts @@ -2,13 +2,13 @@ import {useWindowDimensions} from 'react-native' import {useSafeAreaInsets} from 'react-native-safe-area-context' import {useBreakpoints} from '#/alf' -import {IS_LIQUID_GLASS} from '#/env' +import {IS_LIQUID_GLASS, IS_WEB} from '#/env' export function useHeaderOffset() { const {gtMobile} = useBreakpoints() const {fontScale} = useWindowDimensions() const insets = useSafeAreaInsets() - if (gtMobile) { + if (gtMobile && IS_WEB) { return 0 } const navBarHeight = 52 + (IS_LIQUID_GLASS ? insets.top : 0) diff --git a/src/components/icons/nano.tsx b/src/components/icons/nano.tsx index 905984cfd..c2e59debd 100644 --- a/src/components/icons/nano.tsx +++ b/src/components/icons/nano.tsx @@ -98,7 +98,21 @@ export function withNanoGlyph( const Icon = forwardRef(function NanoIcon(props, ref) { const t = useTheme() - const {fill, size, style, width, height, testID, gradient, ...rest} = props + const { + fill, + size, + style, + width, + height, + testID, + gradient, + /* + * Only the SVG needs this, on web. The glyph is always hidden from + * screen readers, see its accessibilityLabel below. + */ + 'aria-hidden': _ariaHidden, + ...rest + } = props /* * Mirrors useCommonSVGProps: an explicit `size` token wins, then a raw diff --git a/src/env/index.ts b/src/env/index.ts index 994f3002a..cd54f5b09 100644 --- a/src/env/index.ts +++ b/src/env/index.ts @@ -44,6 +44,7 @@ export const APP_METADATA = `${BUNDLE_IDENTIFIER.slice(0, 7)} (${ * Platform detection */ export const IS_IOS: boolean = Platform.OS === 'ios' +export const IS_IPAD: boolean = Platform.OS === 'ios' && Platform.isPad export const IS_ANDROID: boolean = Platform.OS === 'android' export const IS_NATIVE: boolean = true export const IS_WEB: boolean = false diff --git a/src/env/index.web.ts b/src/env/index.web.ts index c130ab814..def4072aa 100644 --- a/src/env/index.web.ts +++ b/src/env/index.web.ts @@ -29,6 +29,7 @@ export const ANDROID_API_LEVEL: number = 0 * Platform detection */ export const IS_IOS: boolean = false +export const IS_IPAD: boolean = false export const IS_ANDROID: boolean = false export const IS_NATIVE: boolean = false export const IS_WEB: boolean = true diff --git a/src/lib/hooks/useBottomBarOffset.ts b/src/lib/hooks/useBottomBarOffset.ts index 6bb737760..10ac30db9 100644 --- a/src/lib/hooks/useBottomBarOffset.ts +++ b/src/lib/hooks/useBottomBarOffset.ts @@ -2,13 +2,13 @@ import {useSafeAreaInsets} from 'react-native-safe-area-context' import {useWebMediaQueries} from '#/lib/hooks/useWebMediaQueries' import {clamp} from '#/lib/numbers' +import {useSession} from '#/state/session' import {IS_WEB} from '#/env' export function useBottomBarOffset(modifier: number = 0) { const {isTabletOrDesktop} = useWebMediaQueries() const {bottom: bottomInset} = useSafeAreaInsets() - return ( - (IS_WEB && isTabletOrDesktop ? 0 : clamp(60 + bottomInset, 60, 75)) + - modifier - ) + const {hasSession} = useSession() + const hasNoBottomBar = isTabletOrDesktop && (IS_WEB || hasSession) + return (hasNoBottomBar ? 0 : clamp(60 + bottomInset, 60, 75)) + modifier } diff --git a/src/lib/hooks/useNavigationTabState.ts b/src/lib/hooks/useNavigationTabState.ts index 2abfc1316..b2c2caea8 100644 --- a/src/lib/hooks/useNavigationTabState.ts +++ b/src/lib/hooks/useNavigationTabState.ts @@ -9,9 +9,10 @@ export function useNavigationTabState() { isAtHome: getTabState(state, 'Home') !== TabState.Outside, isAtSearch: getTabState(state, 'Search') !== TabState.Outside, isAtAtmosphere, - // FeedsTab no longer exists, but this check works for `Feeds` screen as well isAtFeeds: getTabState(state, 'Feeds') !== TabState.Outside, + isAtLists: getTabState(state, 'Lists') !== TabState.Outside, isAtBookmarks: getTabState(state, 'Bookmarks') !== TabState.Outside, + isAtSettings: getTabState(state, 'Settings') !== TabState.Outside, isAtNotifications: getTabState(state, 'Notifications') !== TabState.Outside, isAtMyProfile: getTabState(state, 'MyProfile') !== TabState.Outside, @@ -23,7 +24,10 @@ export function useNavigationTabState() { !res.isAtSearch && !res.isAtAtmosphere && !res.isAtFeeds && + !res.isAtLists && !res.isAtNotifications && + !res.isAtBookmarks && + !res.isAtSettings && !res.isAtMyProfile && !res.isAtMessages ) { diff --git a/src/lib/hooks/useNavigationTabState.web.ts b/src/lib/hooks/useNavigationTabState.web.ts index fc8cf3351..b7c010a55 100644 --- a/src/lib/hooks/useNavigationTabState.web.ts +++ b/src/lib/hooks/useNavigationTabState.web.ts @@ -10,7 +10,9 @@ export function useNavigationTabState() { isAtSearch: currentRoute === 'Search', isAtAtmosphere: currentRoute === 'Atmosphere', isAtFeeds: currentRoute === 'Feeds', + isAtLists: currentRoute === 'Lists', isAtBookmarks: currentRoute === 'Bookmarks', + isAtSettings: currentRoute === 'Settings', isAtNotifications: currentRoute === 'Notifications', isAtMyProfile: currentRoute === 'MyProfile', isAtMessages: currentRoute === 'Messages', diff --git a/src/lib/hooks/useWebMediaQueries.tsx b/src/lib/hooks/useWebMediaQueries.tsx index f4a1a16ec..8f855e0c5 100644 --- a/src/lib/hooks/useWebMediaQueries.tsx +++ b/src/lib/hooks/useWebMediaQueries.tsx @@ -1,24 +1,14 @@ -import {useMediaQuery} from 'react-responsive' - -import {IS_NATIVE} from '#/env' +import {useBreakpoints} from '#/alf/breakpoints' /** * @deprecated use `useBreakpoints` from `#/alf` instead */ export function useWebMediaQueries() { - const isDesktop = useMediaQuery({minWidth: 1300}) - const isTablet = useMediaQuery({minWidth: 800, maxWidth: 1300 - 1}) - const isMobile = useMediaQuery({maxWidth: 800 - 1}) + const {gtMobile, gtTablet} = useBreakpoints() + const isDesktop = gtTablet + const isTablet = gtMobile && !gtTablet + const isMobile = !gtMobile const isTabletOrMobile = isMobile || isTablet const isTabletOrDesktop = isDesktop || isTablet - if (IS_NATIVE) { - return { - isMobile: true, - isTablet: false, - isTabletOrMobile: true, - isTabletOrDesktop: false, - isDesktop: false, - } - } return {isMobile, isTablet, isTabletOrMobile, isTabletOrDesktop, isDesktop} } diff --git a/src/lib/routes/helpers.test.ts b/src/lib/routes/helpers.test.ts new file mode 100644 index 000000000..fa785d237 --- /dev/null +++ b/src/lib/routes/helpers.test.ts @@ -0,0 +1,106 @@ +import { + buildStateObject, + getTabState, + isCurrentProfileRoute, + isStateAtTabRoot, + TabState, +} from '#/lib/routes/helpers' +import {type State} from '#/lib/routes/types' + +function asState(value: unknown) { + return value as State +} + +describe('native tab navigation state', () => { + it.each([ + ['HomeTab', 'Home'], + ['SearchTab', 'Search'], + ['MessagesTab', 'Messages'], + ['NotificationsTab', 'Notifications'], + ['MyProfileTab', 'MyProfile'], + ['FeedsTab', 'Feeds'], + ['ListsTab', 'Lists'], + ['BookmarksTab', 'Bookmarks'], + ['SettingsTab', 'Settings'], + ])('recognizes %s as the %s root', (tabRoute, screen) => { + const state = asState(buildStateObject(tabRoute, screen, {})) + + expect(getTabState(state, screen)).toBe(TabState.InsideAtRoot) + expect(isStateAtTabRoot(state)).toBe(true) + }) + + it('recognizes the own-profile route alias for sidebar selection', () => { + expect( + isCurrentProfileRoute({ + routeName: 'MyProfile', + currentHandle: 'alice.test', + }), + ).toBe(true) + }) + + it('only selects a Profile route for the current account', () => { + expect( + isCurrentProfileRoute({ + routeName: 'Profile', + profileName: 'alice.test', + currentHandle: 'alice.test', + }), + ).toBe(true) + expect( + isCurrentProfileRoute({ + routeName: 'Profile', + profileName: 'bob.test', + currentHandle: 'alice.test', + }), + ).toBe(false) + }) + + it.each([ + ['HomeTab', 'Home'], + ['SearchTab', 'Search'], + ['MessagesTab', 'Messages'], + ['NotificationsTab', 'Notifications'], + ['MyProfileTab', 'MyProfile'], + ['FeedsTab', 'Feeds'], + ['ListsTab', 'Lists'], + ['BookmarksTab', 'Bookmarks'], + ['SettingsTab', 'Settings'], + ])( + 'retains %s when a sidebar tab pushes another screen', + (tabRoute, screen) => { + const state = asState( + buildStateObject(tabRoute, 'Profile', {name: 'alice.test'}), + ) + + expect(getTabState(state, screen)).toBe(TabState.Inside) + expect(isStateAtTabRoot(state)).toBe(false) + }, + ) + + it('builds deep links directly into the matching sidebar tab', () => { + for (const screen of ['Feeds', 'Lists', 'Bookmarks', 'Settings']) { + const state = asState(buildStateObject(`${screen}Tab`, screen, {})) + expect(getTabState(state, screen)).toBe(TabState.InsideAtRoot) + } + }) + + it('does not confuse a detail screen in one tab with another tab', () => { + const state = asState( + buildStateObject('ListsTab', 'Profile', {name: 'alice.test'}), + ) + + expect(getTabState(state, 'Lists')).toBe(TabState.Inside) + expect(getTabState(state, 'Settings')).toBe(TabState.Outside) + expect(getTabState(state, 'MyProfile')).toBe(TabState.Outside) + }) + + it.each(['Feeds', 'Lists', 'Bookmarks', 'Settings'])( + 'does not treat the legacy %s common screen inside HomeTab as a tab root', + screen => { + const state = asState(buildStateObject('HomeTab', screen, {})) + + expect(isStateAtTabRoot(state)).toBe(false) + expect(getTabState(state, screen)).toBe(TabState.Outside) + }, + ) +}) diff --git a/src/lib/routes/helpers.ts b/src/lib/routes/helpers.ts index 08263cdde..ca8fff414 100644 --- a/src/lib/routes/helpers.ts +++ b/src/lib/routes/helpers.ts @@ -40,9 +40,17 @@ export function isStateAtTabRoot(state: State | undefined) { return true } const currentRoute = getCurrentRoute(state) + const activeTab = state.routes[state.index || 0].name + const isSecondaryTabRoot = + (activeTab === 'FeedsTab' && currentRoute.name === 'Feeds') || + (activeTab === 'ListsTab' && currentRoute.name === 'Lists') || + (activeTab === 'BookmarksTab' && currentRoute.name === 'Bookmarks') || + (activeTab === 'SettingsTab' && currentRoute.name === 'Settings') + return ( isTab(currentRoute.name, 'Home') || isTab(currentRoute.name, 'Search') || + isSecondaryTabRoot || isTab(currentRoute.name, 'Messages') || isTab(currentRoute.name, 'Notifications') || isTab(currentRoute.name, 'MyProfile') @@ -61,19 +69,55 @@ export function isTab(current: string, route: string) { ) } +/** The native profile tab root is named `MyProfile` instead of `Profile`. */ +export function isCurrentProfileRoute({ + routeName, + profileName, + currentHandle, +}: { + routeName: string + profileName?: string + currentHandle?: string +}) { + return ( + routeName === 'MyProfile' || + (routeName === 'Profile' && + !!currentHandle && + profileName === currentHandle) + ) +} + export enum TabState { InsideAtRoot, Inside, Outside, } + +const SECONDARY_TAB_ROUTES: Record = { + Feeds: 'FeedsTab', + Lists: 'ListsTab', + Bookmarks: 'BookmarksTab', + Settings: 'SettingsTab', +} + export function getTabState(state: State | undefined, tab: string): TabState { if (!state) { return TabState.Outside } + const currentRoute = getCurrentRoute(state) + const activeTabRoute = state.routes[state.index || 0].name + const secondaryTabRoute = SECONDARY_TAB_ROUTES[tab] + if (secondaryTabRoute) { + if (activeTabRoute !== secondaryTabRoute) { + return TabState.Outside + } + return currentRoute.name === tab ? TabState.InsideAtRoot : TabState.Inside + } + if (isTab(currentRoute.name, tab)) { return TabState.InsideAtRoot - } else if (isTab(state.routes[state.index || 0].name, tab)) { + } else if (isTab(activeTabRoute, tab)) { return TabState.Inside } return TabState.Outside diff --git a/src/lib/routes/tab-to-nav-item.ts b/src/lib/routes/tab-to-nav-item.ts index 49471a1e8..877766f46 100644 --- a/src/lib/routes/tab-to-nav-item.ts +++ b/src/lib/routes/tab-to-nav-item.ts @@ -3,6 +3,9 @@ import {type Events} from '#/analytics/metrics/types' export type SharedNavTab = 'Home' | 'Search' | 'Messages' | 'Notifications' | 'MyProfile' +export type SidebarTab = + SharedNavTab | 'Feeds' | 'Lists' | 'Bookmarks' | 'Settings' + export const TAB_TO_NAV_ITEM: Record< SharedNavTab, Events['nav:click']['item'] diff --git a/src/lib/routes/types.ts b/src/lib/routes/types.ts index e1769b96e..88d6fbe21 100644 --- a/src/lib/routes/types.ts +++ b/src/lib/routes/types.ts @@ -113,6 +113,10 @@ export type BottomTabNavigatorParams = CommonNavigatorParams & { NotificationsTab: undefined MyProfileTab: undefined MessagesTab: undefined + FeedsTab: undefined + ListsTab: undefined + BookmarksTab: undefined + SettingsTab: undefined } export type HomeTabNavigatorParams = CommonNavigatorParams & { @@ -163,6 +167,10 @@ export type AllNavigatorParams = CommonNavigatorParams & { Notifications: undefined MyProfileTab: undefined MessagesTab: undefined + FeedsTab: undefined + ListsTab: undefined + BookmarksTab: undefined + SettingsTab: undefined Messages: { pushToConversation?: string pushToNewGroupChat?: boolean diff --git a/src/screens/Notifications/__tests__/PageList.test.ts b/src/screens/Notifications/__tests__/PageList.test.ts index 0e8ad2242..c26a1d373 100644 --- a/src/screens/Notifications/__tests__/PageList.test.ts +++ b/src/screens/Notifications/__tests__/PageList.test.ts @@ -10,6 +10,7 @@ import { import {type Theme} from '#/alf' // The placeholder helper doesn't need the native runtime or analytics setup. +jest.mock('#/lib/hooks/useBottomBarOffset', () => ({})) jest.mock('#/state/queries/notifications/grouped', () => ({})) jest.mock('#/state/queries/notifications/unread', () => ({})) jest.mock('#/view/com/util/List', () => ({})) diff --git a/src/screens/VideoFeed/index.tsx b/src/screens/VideoFeed/index.tsx index 40df0d71c..6123c85a9 100644 --- a/src/screens/VideoFeed/index.tsx +++ b/src/screens/VideoFeed/index.tsx @@ -149,7 +149,11 @@ export function VideoFeed({}: NativeStackScreenProps< return ( - + void onCurrentPageSelected?: (index: number) => void allowHeaderOverScroll?: boolean + /** Extra vertical clipping bounds for a header that must clip horizontally. */ + headerOverflowInset?: number } export function PagerWithHeader({ ref, @@ -65,6 +68,7 @@ export function PagerWithHeader({ onPageSelected, onCurrentPageSelected, allowHeaderOverScroll, + headerOverflowInset, }: PagerWithHeaderProps) { const [currentPage, setCurrentPage] = useState(0) const [tabBarHeight, setTabBarHeight] = useState(0) @@ -97,6 +101,7 @@ export function PagerWithHeader({ isHeaderReady={isHeaderReady} renderHeader={renderHeader} currentPage={currentPage} + headerOverflowInset={headerOverflowInset} onCurrentPageSelected={onCurrentPageSelected} onTabBarLayout={onTabBarLayout} onHeaderOnlyLayout={onHeaderOnlyLayout} @@ -122,6 +127,7 @@ export function PagerWithHeader({ scrollY, testID, allowHeaderOverScroll, + headerOverflowInset, ], ) @@ -231,6 +237,7 @@ let PagerTabBar = ({ onCurrentPageSelected, onSelect, allowHeaderOverScroll, + headerOverflowInset, dragProgress, dragState, }: { @@ -250,6 +257,8 @@ let PagerTabBar = ({ onCurrentPageSelected?: (index: number) => void onSelect?: (index: number) => void allowHeaderOverScroll?: boolean + /** Extra vertical clipping bounds for a header that must clip horizontally. */ + headerOverflowInset?: number dragProgress: SharedValue dragState: SharedValue<'idle' | 'dragging' | 'settling'> }): React.ReactNode => { @@ -293,7 +302,18 @@ let PagerTabBar = ({ fallbackHeaderOnlyHeight.current = e.nativeEvent.layout.height } }}> - {renderHeader?.({setMinimumHeight: setMinimumHeaderHeight})} + {/* The extended clipping bounds must not intercept touches over the feed. */} +
+ {renderHeader?.({setMinimumHeight: setMinimumHeaderHeight})} +
{ // It wouldn't be enough to place `onLayout` on the parent node because // this would risk measuring before `isHeaderReady` has turned `true`. diff --git a/src/view/com/pager/PagerWithHeader.web.tsx b/src/view/com/pager/PagerWithHeader.web.tsx index 757453f6d..39eeded04 100644 --- a/src/view/com/pager/PagerWithHeader.web.tsx +++ b/src/view/com/pager/PagerWithHeader.web.tsx @@ -37,6 +37,8 @@ export interface PagerWithHeaderProps { onPageSelected?: (index: number) => void onCurrentPageSelected?: (index: number) => void allowHeaderOverScroll?: boolean // Ignored on web. + /** Native-only vertical room for horizontally clipped headers. */ + headerOverflowInset?: number } export const PagerWithHeader = forwardRef( function PageWithHeaderImpl( diff --git a/src/view/com/pager/TabBar.tsx b/src/view/com/pager/TabBar.tsx index 4407de691..8cbe1d356 100644 --- a/src/view/com/pager/TabBar.tsx +++ b/src/view/com/pager/TabBar.tsx @@ -19,6 +19,7 @@ import {scheduleOnRN, scheduleOnUI} from 'react-native-worklets' import {PressableWithHover} from '#/view/com/util/PressableWithHover' import {BlockDrawerGesture} from '#/view/shell/BlockDrawerGesture' import {atoms as a, useTheme} from '#/alf' +import {Center} from '#/components/Layout' import {Text} from '#/components/Typography' export interface TabBarProps { @@ -317,7 +318,7 @@ export function TabBar({ ) return ( - @@ -376,7 +377,7 @@ export function TabBar({ - +
) } diff --git a/src/view/com/posts/PostFeed.tsx b/src/view/com/posts/PostFeed.tsx index 580654834..19c417860 100644 --- a/src/view/com/posts/PostFeed.tsx +++ b/src/view/com/posts/PostFeed.tsx @@ -51,7 +51,7 @@ import {List, type ListRef} from '#/view/com/util/List' import {PostFeedLoadingPlaceholder} from '#/view/com/util/LoadingPlaceholder' import {LoadMoreRetryBtn} from '#/view/com/util/LoadMoreRetryBtn' import {type VideoFeedSourceContext} from '#/screens/VideoFeed/types' -import {atoms as a, useBreakpoints, useLayoutBreakpoints, useTheme} from '#/alf' +import {atoms as a, useLayoutBreakpoints, useTheme} from '#/alf' import { AgeAssuranceDismissibleFeedBanner, useInternalState as useAgeAssuranceBannerState, @@ -60,6 +60,7 @@ import {ProgressGuide, SuggestedFollows} from '#/components/FeedInterstitials' import { PostFeedVideoGridRow, PostFeedVideoGridRowPlaceholder, + useVideoGridColumns, } from '#/components/feeds/PostFeedVideoGridRow' import {FeedTrendingTopicsInterstitial} from '#/components/interstitials/FeedTrendingTopics' import {TrendingVideos as TrendingVideosInterstitial} from '#/components/interstitials/TrendingVideos' @@ -262,7 +263,7 @@ let PostFeed = ({ // eslint-disable-next-line react-hooks/purity const lastFetchRef = useRef(Date.now()) const [feedType, feedUriOrActorDid, feedTab] = feed.split('|') - const {gtMobile} = useBreakpoints() + const videoGridColumns = useVideoGridColumns() const {rightNavVisible} = useLayoutBreakpoints() const areVideoFeedsEnabled = IS_NATIVE @@ -501,13 +502,12 @@ let PostFeed = ({ for (let i = 0; i < videos.length; i++) { const video = videos[i] const item = video.item - const cols = gtMobile ? 3 : 2 const rowItem = { item, feedContext: video.feedContext, reqId: video.reqId, } - if (i % cols === 0) { + if (i % videoGridColumns === 0) { rows.push([rowItem]) } else { rows[rows.length - 1].push(rowItem) @@ -728,7 +728,7 @@ let PostFeed = ({ hasSession, showProgressInterstitial, trendingVideoDisabled, - gtMobile, + videoGridColumns, isVideoFeed, areVideoFeedsEnabled, hasPressedShowLessUris, diff --git a/src/view/com/util/List.tsx b/src/view/com/util/List.tsx index a524d3ecf..25d069f69 100644 --- a/src/view/com/util/List.tsx +++ b/src/view/com/util/List.tsx @@ -1,5 +1,9 @@ -import {forwardRef, memo, useDeferredValue, useMemo} from 'react' -import {type ListViewToken as ViewToken, RefreshControl} from 'react-native' +import {forwardRef, memo, useContext, useDeferredValue, useMemo} from 'react' +import { + type ListViewToken as ViewToken, + RefreshControl, + StyleSheet, +} from 'react-native' import { type FlatListPropsWithLayout, useAnimatedScrollHandler, @@ -12,9 +16,17 @@ import {useDedupe} from '#/lib/hooks/useDedupe' import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback' import {useScrollHandlers} from '#/lib/ScrollContext' import {addStyle} from '#/lib/styles' -import {useTheme} from '#/alf' +import {useIsWithinSplitView} from '#/screens/Messages/components/splitView/context' +import {useBreakpoints, useLayoutBreakpoints, useTheme} from '#/alf' +import {shouldCenterNativeTabletContent} from '#/alf/breakpoints.shared' +import {useDialogContext} from '#/components/Dialog/context' +import { + CENTER_COLUMN_OFFSET, + CENTER_COLUMN_WIDTH, +} from '#/components/Layout/const' +import {ScrollbarOffsetContext} from '#/components/Layout/context' import {useLightbox} from '#/components/Lightbox/state' -import {IS_IOS} from '#/env' +import {IS_IOS, IS_IPAD} from '#/env' import {FlatList_INTERNAL} from './Views' export type ListMethods = FlatList_INTERNAL @@ -39,6 +51,8 @@ export type ListProps = Omit< desktopFixedHeight?: number | boolean // Web only prop to contain the scroll to the container rather than the window disableFullWindowScroll?: boolean + /** Disable the centered native tablet column for full-bleed content. */ + disableTabletLayout?: boolean sideBorders?: boolean progressViewOffset?: number } @@ -54,15 +68,35 @@ let List = forwardRef( onRefresh, onItemSeen, headerOffset, + sideBorders, + disableTabletLayout = false, style, + contentContainerStyle, progressViewOffset, - automaticallyAdjustsScrollIndicatorInsets = false, + automaticallyAdjustsScrollIndicatorInsets, ...props }, ref, ): React.ReactElement => { const isScrolledDown = useSharedValue(false) const t = useTheme() + const {gtMobile} = useBreakpoints() + const {centerColumnOffset} = useLayoutBreakpoints() + const {isWithinDialog} = useDialogContext() + const {isWithinSplitView} = useIsWithinSplitView() + const {isWithinOffsetView} = useContext(ScrollbarOffsetContext) + const centerOnTablet = shouldCenterNativeTabletContent({ + gtMobile, + isWithinDialog, + isWithinSplitView, + isWithinOffsetView, + disabled: disableTabletLayout, + }) + const isWithinContainedTabletSurface = + isWithinDialog || isWithinSplitView || isWithinOffsetView + const usesSystemScrollIndicatorInsets = + gtMobile && !isWithinContainedTabletSurface + const offsetContext = useMemo(() => ({isWithinOffsetView: true}), []) const dedupe = useDedupe(400) const scrollsToTop = useAllowScrollToTop() @@ -154,27 +188,60 @@ let List = forwardRef( } return ( - + + + ) }, ) @@ -183,9 +250,20 @@ List.displayName = 'List' List = memo(List) export {List} -// We only want to use this context value on iOS because the `scrollsToTop` prop is iOS-only -// removing it saves us a re-render on Android -const useAllowScrollToTop = IS_IOS ? useAllowScrollToTopIOS : () => undefined +/* + * We only want to use this context value on iOS because the `scrollsToTop` + * prop is iOS-only, so removing it saves us a re-render on Android. + * + * iPadOS 26 also scrolls to the top when a header button is tapped, and only + * after the button's onPress has run, so it lands on the screen underneath a + * closed lightbox or after a back navigation. Turn it off there entirely. See + * https://github.com/facebook/react-native/issues/56061 + */ +const useAllowScrollToTop = IS_IPAD + ? () => false + : IS_IOS + ? useAllowScrollToTopIOS + : () => undefined function useAllowScrollToTopIOS() { const {activeLightbox} = useLightbox() return useDeferredValue(!activeLightbox) diff --git a/src/view/com/util/Views.tsx b/src/view/com/util/Views.tsx index d59b62af7..75dab4e35 100644 --- a/src/view/com/util/Views.tsx +++ b/src/view/com/util/Views.tsx @@ -1,7 +1,19 @@ -import {forwardRef, memo} from 'react' -import {View, type ViewProps} from 'react-native' +import {forwardRef, memo, useContext} from 'react' +import {StyleSheet, View, type ViewProps} from 'react-native' import Animated from 'react-native-reanimated' +import {useIsWithinSplitView} from '#/screens/Messages/components/splitView/context' +import {useBreakpoints, useLayoutBreakpoints, useTheme} from '#/alf' +import {shouldCenterNativeTabletContent} from '#/alf/breakpoints.shared' +import {useDialogContext} from '#/components/Dialog/context' +import { + CENTER_COLUMN_OFFSET, + CENTER_COLUMN_WIDTH, +} from '#/components/Layout/const' +import {ScrollbarOffsetContext} from '#/components/Layout/context' + +const CENTERED_VIEW_OFFSET_CONTEXT = {isWithinOffsetView: true} + // If you explode these into functions, don't forget to forwardRef! /** @@ -26,5 +38,49 @@ export const CenteredView = forwardRef< ViewProps & {sideBorders?: boolean; topBorder?: boolean} > >(function CenteredView(props, ref) { - return + const {style, sideBorders, topBorder, ...rest} = props + const t = useTheme() + const {gtMobile} = useBreakpoints() + const {centerColumnOffset} = useLayoutBreakpoints() + const {isWithinDialog} = useDialogContext() + const {isWithinSplitView} = useIsWithinSplitView() + const {isWithinOffsetView} = useContext(ScrollbarOffsetContext) + const centerOnTablet = shouldCenterNativeTabletContent({ + gtMobile, + isWithinDialog, + isWithinSplitView, + isWithinOffsetView, + }) + return ( + + + + ) }) diff --git a/src/view/com/util/fab/FAB.tsx b/src/view/com/util/fab/FAB.tsx index b222fe45c..8fec81dc2 100644 --- a/src/view/com/util/fab/FAB.tsx +++ b/src/view/com/util/fab/FAB.tsx @@ -1 +1,9 @@ -export {FABInner as FAB} from './FABInner' +import {useBreakpoints} from '#/alf' +import {IS_NATIVE} from '#/env' +import {FABInner, type FABProps} from './FABInner' + +export function FAB(props: FABProps) { + const {gtMobile} = useBreakpoints() + if (IS_NATIVE && gtMobile) return null + return +} diff --git a/src/view/com/util/load-latest/LoadLatestBtn.tsx b/src/view/com/util/load-latest/LoadLatestBtn.tsx index d99d342d3..358299b2e 100644 --- a/src/view/com/util/load-latest/LoadLatestBtn.tsx +++ b/src/view/com/util/load-latest/LoadLatestBtn.tsx @@ -1,4 +1,4 @@ -import {StyleSheet} from 'react-native' +import {StyleSheet, useWindowDimensions} from 'react-native' import Animated from 'react-native-reanimated' import {useSafeAreaInsets} from 'react-native-safe-area-context' import {useMediaQuery} from 'react-responsive' @@ -14,6 +14,7 @@ import {useInteractionState} from '#/components/hooks/useInteractionState' import {ArrowTop_Stroke2_Corner0_Rounded as ArrowIcon} from '#/components/icons/Arrow' import {CENTER_COLUMN_OFFSET} from '#/components/Layout' import {SubtleHover} from '#/components/SubtleHover' +import {IS_NATIVE} from '#/env' export function LoadLatestBtn({ onPress, @@ -27,6 +28,8 @@ export function LoadLatestBtn({ const {hasSession} = useSession() const {isDesktop, isTablet, isMobile, isTabletOrMobile} = useWebMediaQueries() const {centerColumnOffset} = useLayoutBreakpoints() + const {height: windowHeight, width: windowWidth} = useWindowDimensions() + const centerColumnLeftOffset = centerColumnOffset ? CENTER_COLUMN_OFFSET : 0 const fabMinimalShellTransform = useMinimalShellFabTransform() const insets = useSafeAreaInsets() const t = useTheme() @@ -37,7 +40,8 @@ export function LoadLatestBtn({ } = useInteractionState() // move button inline if it starts overlapping the left nav - const isTallViewport = useMediaQuery({minHeight: 700}) + const isTallViewportMedia = useMediaQuery({minHeight: 700}) + const isTallViewport = IS_NATIVE ? windowHeight >= 700 : isTallViewportMedia // Adjust height of the fab if we have a session only on mobile web. If we don't have a session, we want to adjust // it on both tablet and mobile since we are showing the bottom bar (see createNativeStackNavigatorWithAuth) @@ -62,6 +66,13 @@ export function LoadLatestBtn({ (centerColumnOffset ? styles.loadLatestInlineOffset : styles.loadLatestInline), + IS_NATIVE && + (isTablet || isDesktop) && { + left: + isDesktop && isTallViewport + ? windowWidth / 2 - 382 + : windowWidth / 2 - 282 + centerColumnLeftOffset, + }, bottomPosition, showBottomBar && fabMinimalShellTransform, ]}> diff --git a/src/view/screens/Feeds.tsx b/src/view/screens/Feeds.tsx index 616a005dc..f0b2dd5a4 100644 --- a/src/view/screens/Feeds.tsx +++ b/src/view/screens/Feeds.tsx @@ -519,24 +519,24 @@ export function FeedsScreen(_props: Props) { - - item.key} - contentContainerStyle={styles.contentContainer} - renderItem={renderItem} - refreshing={isPTR} - onRefresh={isUserSearching ? undefined : onPullToRefresh} - initialNumToRender={10} - onEndReached={onEndReached} - desktopFixedHeight - keyboardShouldPersistTaps="handled" - keyboardDismissMode="on-drag" - sideBorders={false} - /> + item.key} + contentContainerStyle={styles.contentContainer} + renderItem={renderItem} + refreshing={isPTR} + onRefresh={isUserSearching ? undefined : onPullToRefresh} + initialNumToRender={10} + onEndReached={onEndReached} + desktopFixedHeight + keyboardShouldPersistTaps="handled" + keyboardDismissMode="on-drag" + sideBorders={false} + /> + {hasSession && ( - - - - - - Blocked Accounts - - - - - {isEmpty ? ( - - - {isError ? ( - - ) : ( - - )} - - ) : ( - item.did} - refreshing={isPTRing} - onRefresh={onRefresh} - onEndReached={onEndReached} - renderItem={renderItem} - initialNumToRender={15} - // FIXME(dan) + + + + + Blocked Accounts + + + + + {isEmpty ? ( + + + {isError ? ( + + ) : ( + + )} + + ) : ( + item.did} + refreshing={isPTRing} + onRefresh={onRefresh} + onEndReached={onEndReached} + renderItem={renderItem} + initialNumToRender={15} + // FIXME(dan) - ListHeaderComponent={Info} - ListFooterComponent={ - - } - /> - )} - + ListHeaderComponent={Info} + ListFooterComponent={ + + } + /> + )} ) } diff --git a/src/view/screens/ModerationMutedAccounts.tsx b/src/view/screens/ModerationMutedAccounts.tsx index 7184d31b8..8184abc7b 100644 --- a/src/view/screens/ModerationMutedAccounts.tsx +++ b/src/view/screens/ModerationMutedAccounts.tsx @@ -109,43 +109,41 @@ export function ModerationMutedAccounts({}: Props) { - - {isEmpty ? ( - - - {isError ? ( - - ) : ( - - )} - - ) : ( - item.did} - refreshing={isPTRing} - onRefresh={onRefresh} - onEndReached={onEndReached} - renderItem={renderItem} - initialNumToRender={15} - // FIXME(dan) + {isEmpty ? ( + + + {isError ? ( + + ) : ( + + )} + + ) : ( + item.did} + refreshing={isPTRing} + onRefresh={onRefresh} + onEndReached={onEndReached} + renderItem={renderItem} + initialNumToRender={15} + // FIXME(dan) - ListHeaderComponent={Info} - ListFooterComponent={ - - } - /> - )} - + ListHeaderComponent={Info} + ListFooterComponent={ + + } + /> + )} ) } diff --git a/src/view/shell/Drawer.tsx b/src/view/shell/Drawer.tsx index 5c18ef673..66f8a21ce 100644 --- a/src/view/shell/Drawer.tsx +++ b/src/view/shell/Drawer.tsx @@ -74,6 +74,16 @@ import {InviteFriendsDialog} from '#/features/inviteFriends' import {useActorStatus} from '#/features/liveNow' const iconWidth = 26 +type SecondarySidebarTab = 'Feeds' | 'Lists' | 'Bookmarks' | 'Settings' +const SECONDARY_TAB_ROUTES: Record< + SecondarySidebarTab, + 'FeedsTab' | 'ListsTab' | 'BookmarksTab' | 'SettingsTab' +> = { + Feeds: 'FeedsTab', + Lists: 'ListsTab', + Bookmarks: 'BookmarksTab', + Settings: 'SettingsTab', +} let DrawerProfileCard = ({ account, @@ -274,11 +284,38 @@ let DrawerContent = ({}: React.PropsWithoutRef<{}>): React.ReactNode => { onPressTab('MyProfile', 'drawerHeader') }, [onPressTab]) + const navigateToSecondaryTab = useCallback( + (tab: SecondarySidebarTab) => { + const state = navigation.getState() + const tabState = getTabState(state, tab) + const routeName = SECONDARY_TAB_ROUTES[tab] + if (tabState === TabState.InsideAtRoot) { + emitSoftReset() + } else if (tabState === TabState.Inside) { + const target = state.routes.find(route => route.name === routeName) + ?.state?.key + if (target) { + navigation.dispatch({ + ...StackActions.popToTop(), + target, + }) + } else { + navigation.reset({index: 0, routes: [{name: routeName}]}) + } + } else { + navigation.navigate(routeName) + } + setDrawerOpen(false) + }, + [navigation, setDrawerOpen], + ) + const onPressMyFeeds = useCallback(() => { ax.metric('nav:click', {item: 'feeds', surface: 'drawer'}) - navigation.navigate('Feeds') - setDrawerOpen(false) - }, [navigation, setDrawerOpen, ax]) + if (IS_WEB) navigation.navigate('Feeds') + else navigateToSecondaryTab('Feeds') + if (IS_WEB) setDrawerOpen(false) + }, [navigation, navigateToSecondaryTab, setDrawerOpen, ax]) const onPressAtmosphere = useCallback(() => { ax.metric('nav:click', {item: 'atmosphere', surface: 'drawer'}) @@ -288,21 +325,24 @@ let DrawerContent = ({}: React.PropsWithoutRef<{}>): React.ReactNode => { const onPressLists = useCallback(() => { ax.metric('nav:click', {item: 'lists', surface: 'drawer'}) - navigation.navigate('Lists') - setDrawerOpen(false) - }, [navigation, setDrawerOpen, ax]) + if (IS_WEB) navigation.navigate('Lists') + else navigateToSecondaryTab('Lists') + if (IS_WEB) setDrawerOpen(false) + }, [navigation, navigateToSecondaryTab, setDrawerOpen, ax]) const onPressBookmarks = useCallback(() => { ax.metric('nav:click', {item: 'saved', surface: 'drawer'}) - navigation.navigate('Bookmarks') - setDrawerOpen(false) - }, [navigation, setDrawerOpen, ax]) + if (IS_WEB) navigation.navigate('Bookmarks') + else navigateToSecondaryTab('Bookmarks') + if (IS_WEB) setDrawerOpen(false) + }, [navigation, navigateToSecondaryTab, setDrawerOpen, ax]) const onPressSettings = useCallback(() => { ax.metric('nav:click', {item: 'settings', surface: 'drawer'}) - navigation.navigate('Settings') - setDrawerOpen(false) - }, [navigation, setDrawerOpen, ax]) + if (IS_WEB) navigation.navigate('Settings') + else navigateToSecondaryTab('Settings') + if (IS_WEB) setDrawerOpen(false) + }, [navigation, navigateToSecondaryTab, setDrawerOpen, ax]) const onPressFeedback = useCallback(() => { void Linking.openURL( diff --git a/src/view/shell/desktop/LeftNav.tsx b/src/view/shell/desktop/LeftNav.tsx index fa20fa931..82718f439 100644 --- a/src/view/shell/desktop/LeftNav.tsx +++ b/src/view/shell/desktop/LeftNav.tsx @@ -1,5 +1,11 @@ import {useCallback, useMemo, useState} from 'react' -import {StyleSheet, View} from 'react-native' +import { + type GestureResponderEvent, + ScrollView, + StyleSheet, + View, +} from 'react-native' +import {useSafeAreaInsets} from 'react-native-safe-area-context' import {PlatformInfo} from '@bsky.app/expo-bluesky-swiss-army' import {plural} from '@lingui/core/macro' import {Trans, useLingui} from '@lingui/react/macro' @@ -7,8 +13,15 @@ import {useNavigation, useNavigationState} from '@react-navigation/native' import {useAccountSwitcher} from '#/lib/hooks/useAccountSwitcher' import {useOpenComposer} from '#/lib/hooks/useOpenComposer' -import {getCurrentRoute, isTab} from '#/lib/routes/helpers' +import { + getCurrentRoute, + getTabState, + isCurrentProfileRoute, + isTab, + TabState, +} from '#/lib/routes/helpers' import {makeProfileLink} from '#/lib/routes/links' +import {type SidebarTab} from '#/lib/routes/tab-to-nav-item' import { type CommonNavigatorParams, type NavigationProp, @@ -81,20 +94,38 @@ import { UserCircle_Filled_Corner0_Rounded as UserCircleFilledIcon, UserCircle_Stroke2_Corner0_Rounded as UserCircleIcon, } from '#/components/icons/UserCircle' -import {CENTER_COLUMN_OFFSET, CENTER_COLUMN_WIDTH} from '#/components/Layout' +import { + CENTER_COLUMN_OFFSET, + CENTER_COLUMN_WIDTH, +} from '#/components/Layout/const' import * as Menu from '#/components/Menu' import * as Prompt from '#/components/Prompt' import {Text} from '#/components/Typography' import {useAgeAssurance} from '#/ageAssurance' import {useAnalytics} from '#/analytics' import {type Events} from '#/analytics/metrics/types' +import {IS_IOS, IS_NATIVE, IS_WEB} from '#/env' import {isFollowingV2HomeDotEnabled} from '#/features/followingV2/eligibility' import {useActorStatus} from '#/features/liveNow' import {type app} from '#/lexicons' import {router} from '#/routes' +import {getComposeButtonLayout} from './composeButtonLayout' const LARGE_ELEMENT_SIZE = 48 const NAV_ICON_WIDTH = 28 +const NAV_ITEM_TO_TAB: Partial< + Record +> = { + home: 'Home', + search: 'Search', + chat: 'Messages', + notifications: 'Notifications', + profile: 'MyProfile', + feeds: 'Feeds', + lists: 'Lists', + saved: 'Bookmarks', + settings: 'Settings', +} export const LEFT_NAV_STANDARD_WIDTH = 240 export const LEFT_NAV_MINIMAL_WIDTH = 80 @@ -249,6 +280,25 @@ function SwitchMenuItems({ signOutPromptControl: DialogControlProps }) { const {t: l} = useLingui() + const {currentAccount} = useSession() + const {onPressSwitchAccount, pendingDid} = useAccountSwitcher() + const navigation = useNavigation() + const {control} = Menu.useMenuContext() + const currentRouteInfo = useNavigationState(state => { + if (!state) { + return {name: 'Home'} + } + return getCurrentRoute(state) + }) + const profileLink = currentAccount ? makeProfileLink(currentAccount) : '/' + const isCurrent = isCurrentProfileRoute({ + routeName: currentRouteInfo.name, + profileName: + currentRouteInfo.name === 'Profile' + ? (currentRouteInfo.params as CommonNavigatorParams['Profile']).name + : undefined, + currentHandle: currentAccount?.handle, + }) const {setShowLoggedOut} = useLoggedOutViewControls() const closeEverything = useCloseAllActiveElements() @@ -257,26 +307,79 @@ function SwitchMenuItems({ closeEverything() } + const onProfilePress = (e: GestureResponderEvent) => { + if (IS_WEB) { + const mouseEvent = e as unknown as React.MouseEvent< + HTMLAnchorElement, + MouseEvent + > + if (mouseEvent.ctrlKey || mouseEvent.metaKey || mouseEvent.altKey) { + return + } + mouseEvent.preventDefault() + } + + const onNavigate = () => { + if (isCurrent) { + emitSoftReset() + } else { + const [screen, params] = router.matchPath(profileLink) + // @ts-expect-error TODO: type matchPath well enough that it can be plugged into navigation.navigate directly + navigation.navigate(screen, params, {pop: true}) + } + } + + if (IS_IOS) { + onNavigate() + } else if (IS_NATIVE) { + control.close() + onNavigate() + } else { + control.close(onNavigate) + } + } + return ( {accounts && accounts.length > 0 && ( <> + + Switch account + - - Switch account - - {accounts.map(other => ( - + {/* Native groups require Menu.Item as a direct child. */} + {accounts.map(({account, profile}) => ( + + void onPressSwitchAccount(account, 'SwitchAccount') + }> + + + {sanitizeHandle(profile?.handle ?? account.handle, '@')} + + ))} )} - + + + + Go to profile + + @@ -293,96 +396,23 @@ function SwitchMenuItems({ ) } -function SwitcherMenuProfileLink() { - const {t: l} = useLingui() - const {currentAccount} = useSession() - const navigation = useNavigation() - const context = Menu.useMenuContext() - const profileLink = currentAccount ? makeProfileLink(currentAccount) : '/' - const [pathName] = useMemo(() => router.matchPath(profileLink), [profileLink]) - const currentRouteInfo = useNavigationState(state => { - if (!state) { - return {name: 'Home'} - } - return getCurrentRoute(state) - }) - const isCurrent = useMemo(() => { - if (currentRouteInfo.name === 'Profile') { - return ( - isTab(currentRouteInfo.name, pathName) && - (currentRouteInfo.params as CommonNavigatorParams['Profile']).name === - currentAccount?.handle - ) - } else { - return isTab(currentRouteInfo.name, pathName) - } - }, [currentAccount?.handle, currentRouteInfo, pathName]) - - const onProfilePress = useCallback( - (e: React.MouseEvent) => { - if (e.ctrlKey || e.metaKey || e.altKey) { - return - } - e.preventDefault() - context.control.close() - if (isCurrent) { - emitSoftReset() - } else { - const [screen, params] = router.matchPath(profileLink) - // @ts-expect-error TODO: type matchPath well enough that it can be plugged into navigation.navigate directly - navigation.navigate(screen, params, {pop: true}) - } - }, - [navigation, profileLink, isCurrent, context], - ) - return ( - - - - Go to profile - - - ) -} - -function SwitchMenuItem({ - account, +function SwitchMenuItemAvatar({ profile, }: { - account: SessionAccount profile: app.bsky.actor.defs.ProfileViewDetailed | undefined }) { - const {t: l} = useLingui() - const {onPressSwitchAccount, pendingDid} = useAccountSwitcher() const {isActive: live} = useActorStatus(profile) return ( - void onPressSwitchAccount(account, 'SwitchAccount')}> - - - - - {sanitizeHandle(profile?.handle ?? account.handle, '@')} - - + + + ) } @@ -398,6 +428,7 @@ interface NavItemProps { label: string minimal: boolean navItem: Events['nav:click']['item'] + onNavigateTab?: (tab: SidebarTab) => void } function NavItem({ beta, @@ -408,6 +439,7 @@ function NavItem({ label, minimal, navItem, + onNavigateTab, }: NavItemProps) { const t = useTheme() const {t: l} = useLingui() @@ -416,18 +448,25 @@ function NavItem({ const {currentAccount} = useSession() const [pathName] = useMemo(() => router.matchPath(href), [href]) - const currentRouteInfo = useNavigationState(state => { - if (!state) { - return {name: 'Home'} - } - return getCurrentRoute(state) - }) - let isCurrent = - currentRouteInfo.name === 'Profile' - ? isTab(currentRouteInfo.name, pathName) && - (currentRouteInfo.params as CommonNavigatorParams['Profile']).name === - currentAccount?.handle + const navigationState = useNavigationState(state => state) + const currentRouteInfo = getCurrentRoute(navigationState) + const tab = NAV_ITEM_TO_TAB[navItem] + const isCurrent = + navItem === 'profile' + ? isCurrentProfileRoute({ + routeName: currentRouteInfo.name, + profileName: + currentRouteInfo.name === 'Profile' + ? (currentRouteInfo.params as CommonNavigatorParams['Profile']) + .name + : undefined, + currentHandle: currentAccount?.handle, + }) : isTab(currentRouteInfo.name, pathName) + const isSelected = + IS_NATIVE && tab + ? getTabState(navigationState, tab) !== TabState.Outside + : isCurrent const isRelated = currentRouteInfo.name.startsWith(pathName) const navigation = useNavigation() const onPressWrapped = useCallback( @@ -436,7 +475,11 @@ function NavItem({ if (e.ctrlKey || e.metaKey || e.altKey) { return } - e.preventDefault() + e.preventDefault?.() + if (tab && onNavigateTab) { + onNavigateTab(tab) + return + } if (isCurrent) { emitSoftReset() } else { @@ -445,10 +488,11 @@ function NavItem({ navigation.navigate(screen, params, {pop: true}) } }, - [navigation, href, isCurrent, ax, navItem], + [navigation, href, isCurrent, ax, navItem, onNavigateTab, tab], ) - const Icon = isCurrent || isRelated ? icons.active : icons.inactive + const Icon = + isSelected || (!IS_NATIVE && isRelated) ? icons.active : icons.inactive return ( {!minimal && ( - + {label} {beta && } @@ -589,18 +634,17 @@ function ComposeBtn({minimal}: {minimal: boolean}) { const onPressCompose = async () => openComposer({mention: await getProfileHandle(), logContext: 'Fab'}) + const layout = getComposeButtonLayout({minimal, isNative: IS_NATIVE}) + return ( - +