diff --git a/example/package.json b/example/package.json index f532cb981c..d855195aa8 100644 --- a/example/package.json +++ b/example/package.json @@ -15,7 +15,6 @@ "@react-native-async-storage/async-storage": "2.2.0", "@react-native-masked-view/masked-view": "0.3.2", "@react-navigation/bottom-tabs": "^8.0.0-alpha.57", - "@react-navigation/drawer": "^8.0.0-alpha.58", "@react-navigation/elements": "3.0.0-alpha.55", "@react-navigation/native": "^8.0.0-alpha.51", "@react-navigation/native-stack": "^8.0.0-alpha.59", diff --git a/example/src/DrawerItems.tsx b/example/src/DrawerItems.tsx deleted file mode 100644 index e205164f1b..0000000000 --- a/example/src/DrawerItems.tsx +++ /dev/null @@ -1,317 +0,0 @@ -import * as React from 'react'; -import { Platform, StyleSheet, View } from 'react-native'; -import type { ColorValue } from 'react-native'; - -import { DrawerContentScrollView } from '@react-navigation/drawer'; -import Constants, { ExecutionEnvironment } from 'expo-constants'; -import { - Badge, - Button, - Dialog, - Drawer, - Palette, - Switch, - Text, - TouchableRipple, - useTheme, -} from 'react-native-paper'; - -import { dynamicThemeSupported } from '../utils'; -import { PreferencesContext } from './PreferencesContext'; - -const DrawerItemsData = [ - { - label: 'Inbox', - icon: 'inbox', - key: 0, - right: () => 44, - }, - { - label: 'Starred', - icon: 'star', - key: 1, - right: ({ color }: { color: ColorValue }) => ( - - ), - }, - { label: 'Sent mail', icon: 'send', key: 2 }, - { label: 'Colored label', icon: 'palette', key: 3 }, - { - label: 'A very long title that will be truncated', - icon: 'delete', - key: 4, - right: () => , - }, -]; - -const DrawerCollapsedItemsData = [ - { - label: 'Inbox', - focusedIcon: 'inbox', - unfocusedIcon: 'inbox-outline', - key: 0, - badge: 44, - }, - { - label: 'Starred', - focusedIcon: 'star', - unfocusedIcon: 'star-outline', - key: 1, - }, - { - label: 'Sent mail', - focusedIcon: 'send', - unfocusedIcon: 'send-outline', - key: 2, - }, - { - label: 'A very long title that will be truncated', - focusedIcon: 'delete', - unfocusedIcon: 'delete-outline', - key: 3, - }, - { - label: 'Full width', - focusedIcon: 'arrow-all', - key: 4, - }, - { - focusedIcon: 'bell', - unfocusedIcon: 'bell-outline', - key: 5, - badge: true, - }, -]; - -function DrawerItems() { - const [drawerItemIndex, setDrawerItemIndex] = React.useState(0); - const [showRTLDialog, setShowRTLDialog] = React.useState(false); - const preferences = React.useContext(PreferencesContext); - - const _setDrawerItem = (index: number) => setDrawerItemIndex(index); - - const { colors } = useTheme(); - const expoGoExecution = - Constants.executionEnvironment === ExecutionEnvironment.StoreClient; - - if (!preferences) throw new Error('PreferencesContext not provided'); - - const { - toggleShouldUseDynamicTheme, - toggleTheme, - toggleRtl: toggleRTL, - toggleCollapsed, - toggleCustomFont, - toggleRippleEffect, - customFontLoaded, - rippleEffectEnabled, - collapsed, - rtl: isRTL, - theme: { dark: isDarkTheme }, - shouldUseDynamicTheme, - } = preferences; - - const _handleToggleRTL = () => { - if (Platform.OS !== 'web' && expoGoExecution) { - setShowRTLDialog(true); - return; - } - - toggleRTL(); - }; - - const _handleDismissRTLDialog = () => { - setShowRTLDialog(false); - }; - - const coloredLabelTheme = { - colors: { - secondaryContainer: Palette.tertiary80, - onSecondaryContainer: Palette.tertiary20, - }, - }; - - return ( - - {collapsed && ( - - {DrawerCollapsedItemsData.map((props, index) => ( - { - _setDrawerItem(index); - index === 4 && toggleCollapsed(); - }} - /> - ))} - - )} - {!collapsed && ( - <> - - {DrawerItemsData.map((props, index) => ( - _setDrawerItem(index)} - /> - ))} - - - - {dynamicThemeSupported ? ( - - - Use Dynamic Theme - - - - - - ) : null} - - - Dark Theme - - - - - - - - - RTL - - - - - - - - - Collapsed drawer * - - - - - - - - - Custom font * - - - - - - - - - - {Platform.OS === 'ios' ? 'Highlight' : 'Ripple'} effect * - - - - - - - - {!collapsed && ( - - * - optional example toggles - - )} - - React Native Paper Version{' '} - {require('react-native-paper/package.json').version} - - - )} - - Due to Expo Go limitations it is impossible to change RTL - dynamically. To do so, you need to create a development build of - Example app or change it statically by setting{' '} - forcesRTL property to true in{' '} - app.json within{' '} - example directory. - - } - actions={[ - , - ]} - /> - - ); -} - -const styles = StyleSheet.create({ - drawerContent: { - flex: 1, - }, - preference: { - flexDirection: 'row', - justifyContent: 'space-between', - alignItems: 'center', - paddingVertical: 12, - paddingHorizontal: 16, - }, - v3Preference: { - height: 56, - paddingHorizontal: 28, - }, - badge: { - alignSelf: 'center', - }, - collapsedSection: { - marginTop: 16, - }, - annotation: { - marginHorizontal: 24, - marginVertical: 6, - }, -}); - -export default DrawerItems; diff --git a/example/src/ExampleList.tsx b/example/src/ExampleList.tsx index 2af1eed385..17d719b5b1 100644 --- a/example/src/ExampleList.tsx +++ b/example/src/ExampleList.tsx @@ -1,9 +1,11 @@ -import { FlatList } from 'react-native'; +import { useState } from 'react'; +import { FlatList, StyleSheet, View } from 'react-native'; import { useNavigation } from '@react-navigation/native'; -import { Divider, List, useTheme } from 'react-native-paper'; +import { Divider, List, Text, useTheme } from 'react-native-paper'; import { useSafeAreaInsets } from 'react-native-safe-area-context'; +import ExampleListHeader from './ExampleListHeader'; import ActivityIndicatorExample from './Examples/ActivityIndicatorExample'; import AppbarExample from './Examples/AppbarExample'; import AvatarExample from './Examples/AvatarExample'; @@ -46,6 +48,8 @@ import ThemeExample from './Examples/ThemeExample'; import ThemingWithReactNavigation from './Examples/ThemingWithReactNavigation'; import TooltipExample from './Examples/TooltipExample'; import TouchableRippleExample from './Examples/TouchableRippleExample'; +import { filterByQuery } from '../utils/filterByQuery'; +import { objectEntries } from '../utils/typedObject'; export const mainExamples = { ActivityIndicator: ActivityIndicatorExample, @@ -101,7 +105,7 @@ export const examples = { ...nestedExamples, }; -const data = Object.entries(mainExamples).map(([id, example]) => ({ +const data = objectEntries(mainExamples).map(([id, example]) => ({ id, data: example, })); @@ -112,32 +116,62 @@ export default function ExampleList() { const { colors } = useTheme(); const safeArea = useSafeAreaInsets(); + const [query, setQuery] = useState(''); + + const filteredData = filterByQuery(data, query, ({ id, data: example }) => [ + example.title, + id, + ]); + return ( - ( - { - // @ts-expect-error TypeScript can't call overloaded functions with union arguments. - // https://github.com/microsoft/TypeScript/issues/40803 - navigation.navigate(item.id); - }} - /> - )} - keyExtractor={({ id }) => id} - data={data} - /> + + + ( + { + // @ts-expect-error TypeScript can't call overloaded functions with union arguments. + // https://github.com/microsoft/TypeScript/issues/40803 + navigation.navigate(item.id); + }} + /> + )} + ListEmptyComponent={ + + {`No examples match "${query.trim()}"`} + + } + keyExtractor={({ id }) => id} + data={filteredData} + /> + ); } + +const styles = StyleSheet.create({ + container: { + flex: 1, + }, + empty: { + padding: 16, + textAlign: 'center', + }, +}); diff --git a/example/src/ExampleListHeader.tsx b/example/src/ExampleListHeader.tsx new file mode 100644 index 0000000000..eaf08e2ca3 --- /dev/null +++ b/example/src/ExampleListHeader.tsx @@ -0,0 +1,43 @@ +import { StyleSheet } from 'react-native'; + +import { useNavigation } from '@react-navigation/native'; +import { Appbar, Searchbar } from 'react-native-paper'; + +import PreferencesAction from './Preferences/PreferencesAction'; + +type Props = { + query: string; + onQueryChange: (query: string) => void; +}; + +export default function ExampleListHeader({ query, onQueryChange }: Props) { + const navigation = useNavigation('ExampleList'); + + const canGoBack = navigation.canGoBack(); + + return ( + + navigation.goBack() : undefined} + searchAccessibilityLabel={canGoBack ? 'go back' : 'search'} + clearAccessibilityLabel="clear search" + autoCorrect={false} + autoCapitalize="none" + style={styles.searchbar} + /> + + + ); +} + +const styles = StyleSheet.create({ + searchbar: { + flex: 1, + }, +}); diff --git a/example/src/Examples/CardExample.tsx b/example/src/Examples/CardExample.tsx index 09b732d9d0..ed8842e40c 100644 --- a/example/src/Examples/CardExample.tsx +++ b/example/src/Examples/CardExample.tsx @@ -11,7 +11,7 @@ import { useTheme, } from 'react-native-paper'; -import { PreferencesContext } from '../PreferencesContext'; +import { usePreferences } from '../Preferences/usePreferences'; import ScreenWrapper from '../ScreenWrapper'; type Mode = 'elevated' | 'outlined' | 'contained'; @@ -20,7 +20,7 @@ const CardExample = () => { const { colors } = useTheme(); const [selectedMode, setSelectedMode] = React.useState('elevated'); const [isSelected, setIsSelected] = React.useState(false); - const preferences = React.useContext(PreferencesContext); + const { toggleTheme } = usePreferences(); const modes: Mode[] = ['elevated', 'outlined', 'contained']; @@ -193,13 +193,7 @@ const CardExample = () => { - { - preferences?.toggleTheme(); - }} - mode={selectedMode} - > + } diff --git a/example/src/Examples/SearchbarExample.tsx b/example/src/Examples/SearchbarExample.tsx index 1a3e98bb8f..fbe936bbd5 100644 --- a/example/src/Examples/SearchbarExample.tsx +++ b/example/src/Examples/SearchbarExample.tsx @@ -11,10 +11,12 @@ import { useTheme, } from 'react-native-paper'; +import { usePreferences } from '../Preferences/usePreferences'; import ScreenWrapper from '../ScreenWrapper'; const SearchExample = () => { const navigation = useNavigation('Searchbar'); + const { togglePreferences } = usePreferences(); const [isVisible, setIsVisible] = React.useState(false); const [searchQueries, setSearchQuery] = React.useState({ @@ -27,7 +29,7 @@ const SearchExample = () => { searchWithoutBottomLine: '', loadingViewMode: '', clickableBack: '', - clickableDrawer: '', + clickablePreferences: '', clickableLoading: '', }); @@ -185,15 +187,15 @@ const SearchExample = () => { onChangeText={(query) => setSearchQuery({ ...searchQueries, - clickableDrawer: query, + clickablePreferences: query, }) } - value={searchQueries.clickableDrawer} + value={searchQueries.clickablePreferences} onIconPress={() => { Keyboard.dismiss(); - navigation.openDrawer(); + togglePreferences(); }} - icon="menu" + icon="cog" style={styles.searchbar} /> { - const preferences = React.useContext(PreferencesContext); + const { toggleTheme } = usePreferences(); const [options, setOptions] = React.useState({ showSnackbar: false, @@ -31,9 +31,7 @@ const SnackbarExample = () => { const action = { label: showLongerAction ? 'Toggle Theme' : 'Action', - onPress: () => { - preferences?.toggleTheme(); - }, + onPress: toggleTheme, }; return ( diff --git a/example/src/Preferences/PreferencesAction.tsx b/example/src/Preferences/PreferencesAction.tsx new file mode 100644 index 0000000000..a4e791900b --- /dev/null +++ b/example/src/Preferences/PreferencesAction.tsx @@ -0,0 +1,15 @@ +import { Appbar } from 'react-native-paper'; + +import { usePreferences } from './usePreferences'; + +export default function PreferencesAction() { + const { togglePreferences } = usePreferences(); + + return ( + + ); +} diff --git a/example/src/Preferences/PreferencesContext.tsx b/example/src/Preferences/PreferencesContext.tsx new file mode 100644 index 0000000000..c89d41e69a --- /dev/null +++ b/example/src/Preferences/PreferencesContext.tsx @@ -0,0 +1,21 @@ +import { createContext } from 'react'; + +import type { Theme } from 'react-native-paper'; + +export type Preferences = { + toggleTheme: () => void; + toggleRtl: () => void; + toggleCustomFont: () => void; + togglePreferences: () => void; + toggleRippleEffect: () => void; + toggleShouldUseDynamicTheme: () => void; + resetPreferences: () => void; + theme: Theme; + rtl: boolean; + customFontLoaded: boolean; + preferencesVisible: boolean; + rippleEffectEnabled: boolean; + shouldUseDynamicTheme: boolean; +}; + +export const PreferencesContext = createContext(null); diff --git a/example/src/Preferences/PreferencesModal.tsx b/example/src/Preferences/PreferencesModal.tsx new file mode 100644 index 0000000000..d05111ce39 --- /dev/null +++ b/example/src/Preferences/PreferencesModal.tsx @@ -0,0 +1,201 @@ +import { useState } from 'react'; +import { + Platform, + ScrollView, + StyleSheet, + useWindowDimensions, + View, +} from 'react-native'; + +import Constants, { ExecutionEnvironment } from 'expo-constants'; +import { + Button, + Dialog, + Modal, + Switch, + Text, + useTheme, +} from 'react-native-paper'; + +import { usePreferences } from './usePreferences'; +import { dynamicThemeSupported } from '../../utils'; + +export default function PreferencesModal() { + const [showRTLDialog, setShowRTLDialog] = useState(false); + const theme = useTheme(); + const { height: windowHeight } = useWindowDimensions(); + + const expoGoExecution = + Constants.executionEnvironment === ExecutionEnvironment.StoreClient; + const rtlToggleUnavailable = Platform.OS !== 'web' && expoGoExecution; + const rippleEffectLabel = `${Platform.OS === 'ios' ? 'Highlight' : 'Ripple'} effect`; + + const { + toggleShouldUseDynamicTheme, + toggleTheme, + toggleRtl, + toggleCustomFont, + toggleRippleEffect, + togglePreferences, + resetPreferences, + preferencesVisible, + customFontLoaded, + rippleEffectEnabled, + rtl, + theme: { dark: isDarkTheme }, + shouldUseDynamicTheme, + } = usePreferences(); + + const _handleToggleRTL = () => { + if (rtlToggleUnavailable) { + setShowRTLDialog(true); + return; + } + + toggleRtl(); + }; + + const _handleDismissRTLDialog = () => { + setShowRTLDialog(false); + }; + + return ( + <> + + + {dynamicThemeSupported ? ( + + Use Dynamic Theme + + + ) : null} + + Dark Theme + + + + + RTL + + + + + Custom font * + + + + + {rippleEffectLabel} * + + + + + + + * - optional example toggles + + + React Native Paper Version{' '} + {require('react-native-paper/package.json').version} + + + + + Due to Expo Go limitations it is impossible to change RTL + dynamically. To do so, you need to create a development build of + Example app or change it statically by setting{' '} + forcesRTL property to true in{' '} + app.json within{' '} + example directory. + + } + actions={[ + , + ]} + /> + + ); +} + +const styles = StyleSheet.create({ + modalContent: { + marginHorizontal: 24, + width: '100%', + maxWidth: 360, + alignSelf: 'center', + }, + scrollView: { + flexGrow: 0, + flexShrink: 1, + }, + scrollViewContent: { + paddingVertical: 12, + }, + preference: { + flexDirection: 'row', + justifyContent: 'space-between', + alignItems: 'center', + height: 56, + paddingVertical: 12, + paddingHorizontal: 28, + }, + resetButton: { + marginHorizontal: 28, + marginVertical: 12, + }, + annotation: { + marginHorizontal: 24, + marginVertical: 6, + }, +}); diff --git a/example/src/Preferences/usePreferences.ts b/example/src/Preferences/usePreferences.ts new file mode 100644 index 0000000000..85555f0223 --- /dev/null +++ b/example/src/Preferences/usePreferences.ts @@ -0,0 +1,11 @@ +import { useContext } from 'react'; + +import { PreferencesContext } from './PreferencesContext'; + +export function usePreferences() { + const preferences = useContext(PreferencesContext); + + if (!preferences) throw new Error('PreferencesContext not provided'); + + return preferences; +} diff --git a/example/src/Preferences/useSetupPreferences.ts b/example/src/Preferences/useSetupPreferences.ts new file mode 100644 index 0000000000..6319c0b25f --- /dev/null +++ b/example/src/Preferences/useSetupPreferences.ts @@ -0,0 +1,159 @@ +import * as React from 'react'; +import { I18nManager, Platform } from 'react-native'; + +import AsyncStorage from '@react-native-async-storage/async-storage'; +import * as Updates from 'expo-updates'; +import { + DarkTheme, + LightTheme, + DynamicLightTheme, + DynamicDarkTheme, +} from 'react-native-paper'; + +import type { Preferences } from './PreferencesContext'; +import { dynamicThemeSupported } from '../../utils'; +import { clearNavigationState } from '../navigationPersistence'; + +const PREFERENCES_KEY = 'APP_PREFERENCES'; + +export const getDirection = (rtl: boolean) => (rtl ? 'rtl' : 'ltr'); + +const getInitialRtl = () => { + if (Platform.OS === 'web' && typeof document !== 'undefined') { + return document.documentElement.dir === 'rtl'; + } + + return I18nManager.getConstants().isRTL; +}; + +export function useSetupPreferences() { + const [isReady, setIsReady] = React.useState(false); + + const [shouldUseDynamicTheme, setShouldUseDynamicTheme] = + React.useState(true); + const [isDarkMode, setIsDarkMode] = React.useState(false); + const [rtl, setRtl] = React.useState(getInitialRtl); + const [customFontLoaded, setCustomFont] = React.useState(false); + const [rippleEffectEnabled, setRippleEffectEnabled] = React.useState(true); + const [preferencesVisible, setPreferencesVisible] = React.useState(false); + + const [navigationKey, setNavigationKey] = React.useState(0); + + const theme = + dynamicThemeSupported && shouldUseDynamicTheme + ? isDarkMode + ? DynamicDarkTheme + : DynamicLightTheme + : isDarkMode + ? DarkTheme + : LightTheme; + + const direction = getDirection(rtl); + + React.useEffect(() => { + const restorePrefs = async () => { + try { + const prefString = await AsyncStorage.getItem(PREFERENCES_KEY); + const preferences = JSON.parse(prefString || ''); + + if (preferences) { + setIsDarkMode(preferences.theme === 'dark'); + + if (typeof preferences.rtl === 'boolean') { + setRtl(preferences.rtl); + } + } + } catch (e) { + // ignore error + } finally { + setIsReady(true); + } + }; + + void restorePrefs(); + }, []); + + React.useEffect(() => { + const savePrefs = async () => { + if (!isReady) { + return; + } + + try { + await AsyncStorage.setItem( + PREFERENCES_KEY, + JSON.stringify({ + theme: isDarkMode ? 'dark' : 'light', + rtl, + }) + ); + } catch (e) { + // ignore error + } + + if (Platform.OS === 'web' && typeof document !== 'undefined') { + document.documentElement.dir = direction; + } + + if (I18nManager.getConstants().isRTL !== rtl) { + I18nManager.forceRTL(rtl); + + if (Platform.OS !== 'web') { + await Updates.reloadAsync(); + } + } + }; + + void savePrefs(); + }, [direction, isDarkMode, isReady, rtl]); + + const resetPreferences = React.useCallback(async () => { + setShouldUseDynamicTheme(true); + setIsDarkMode(false); + setCustomFont(false); + setRippleEffectEnabled(true); + setPreferencesVisible(false); + + try { + await clearNavigationState(); + } catch (e) { + // ignore error + } + + setNavigationKey((oldValue) => oldValue + 1); + }, []); + + const preferences: Preferences = React.useMemo( + () => ({ + toggleShouldUseDynamicTheme: () => + setShouldUseDynamicTheme((oldValue) => !oldValue), + toggleTheme: () => setIsDarkMode((oldValue) => !oldValue), + toggleRtl: () => setRtl((oldValue) => !oldValue), + toggleCustomFont: () => setCustomFont((oldValue) => !oldValue), + toggleRippleEffect: () => setRippleEffectEnabled((oldValue) => !oldValue), + togglePreferences: () => setPreferencesVisible((oldValue) => !oldValue), + resetPreferences, + preferencesVisible, + customFontLoaded, + rippleEffectEnabled, + shouldUseDynamicTheme, + theme, + rtl, + }), + [ + rtl, + theme, + customFontLoaded, + preferencesVisible, + shouldUseDynamicTheme, + rippleEffectEnabled, + resetPreferences, + ] + ); + + return { + preferences, + isReady, + navigationKey, + }; +} diff --git a/example/src/PreferencesContext.tsx b/example/src/PreferencesContext.tsx deleted file mode 100644 index b5e381ae05..0000000000 --- a/example/src/PreferencesContext.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import * as React from 'react'; - -import type { Theme } from 'react-native-paper'; - -export const PreferencesContext = React.createContext<{ - toggleTheme: () => void; - toggleRtl: () => void; - toggleCollapsed: () => void; - toggleCustomFont: () => void; - toggleRippleEffect: () => void; - toggleShouldUseDynamicTheme?: () => void; - theme: Theme; - rtl: boolean; - collapsed: boolean; - customFontLoaded: boolean; - rippleEffectEnabled: boolean; - shouldUseDynamicTheme?: boolean; -} | null>(null); diff --git a/example/src/RootNavigator.tsx b/example/src/RootNavigator.tsx index 95ea077275..6bf9f5c3f8 100644 --- a/example/src/RootNavigator.tsx +++ b/example/src/RootNavigator.tsx @@ -1,6 +1,5 @@ import { Platform, StyleSheet, View } from 'react-native'; -import { useNavigation } from '@react-navigation/native'; import { createNativeStackNavigator, createNativeStackScreen, @@ -10,38 +9,35 @@ import { Appbar } from 'react-native-paper'; import ExampleList, { examples } from './ExampleList'; import { colorThemes } from '../utils'; +import PreferencesAction from './Preferences/PreferencesAction'; +import PreferencesModal from './Preferences/PreferencesModal'; +import SamplesList, { samples } from './SamplesList'; +import { objectEntries, objectFromEntries } from '../utils/typedObject'; const { TeamDetails, ...examplesWithoutParams } = examples; -type ExampleRouteName = keyof typeof examplesWithoutParams; - -const fromEntries = ( - entries: Array<[Key, Value]> -) => - // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion - Object.fromEntries(entries) as Record; - function Header({ navigation, route, options, back }: NativeStackHeaderProps) { - const drawerNavigation = useNavigation('Home'); - return ( - - {back ? ( - navigation.goBack()} /> - ) : ( + + {back && navigation.goBack()} />} + {!back && ( drawerNavigation.openDrawer()} + icon="folder-search" + aria-label="search examples" + onPress={() => + navigation.navigate('Examples', { screen: 'ExampleList' }) + } /> )} + ); } -const Root = createNativeStackNavigator({ - layout: ({ children }) => {children}, +const Examples = createNativeStackNavigator({ + initialRouteName: 'ExampleList', screenOptions: { header: (props) =>
, }, @@ -50,17 +46,12 @@ const Root = createNativeStackNavigator({ screen: ExampleList, options: { title: 'Examples', + headerShown: false, }, - linking: '', + linking: 'examples', }), - /* eslint-disable @typescript-eslint/no-unsafe-type-assertion */ - ...fromEntries( - ( - Object.entries(examplesWithoutParams) as [ - ExampleRouteName, - (typeof examplesWithoutParams)[ExampleRouteName], - ][] - ).map(([id, screen]) => [ + ...objectFromEntries( + objectEntries(examplesWithoutParams).map(([id, screen]) => [ id, createNativeStackScreen({ screen: screen, @@ -71,7 +62,6 @@ const Root = createNativeStackNavigator({ }), ]) ), - /* eslint-enable @typescript-eslint/no-unsafe-type-assertion */ TeamDetails: createNativeStackScreen({ screen: TeamDetails, options: { @@ -92,6 +82,50 @@ const Root = createNativeStackNavigator({ }, }); +const Root = createNativeStackNavigator({ + initialRouteName: 'SamplesList', + layout: ({ children }) => ( + <> + {children} + + + ), + screenOptions: { + header: (props) =>
, + }, + screens: { + SamplesList: createNativeStackScreen({ + screen: SamplesList, + options: { + title: 'Samples', + }, + linking: '', + }), + ...objectFromEntries( + objectEntries(samples).map(([id, sample]) => [ + id, + createNativeStackScreen({ + screen: sample.screen, + options: { + title: sample.title, + headerShown: sample.headerShown ?? true, + }, + }), + ]) + ), + Examples: createNativeStackScreen({ + screen: Examples, + options: { + headerShown: false, + }, + // @ts-expect-error `path` is optional at runtime; an empty path would clash with SamplesList + linking: { + initialRouteName: 'ExampleList', + }, + }), + }, +}); + export default Root; const styles = StyleSheet.create({ diff --git a/example/src/Samples/ArticleSample.tsx b/example/src/Samples/ArticleSample.tsx new file mode 100644 index 0000000000..a144e4c973 --- /dev/null +++ b/example/src/Samples/ArticleSample.tsx @@ -0,0 +1,124 @@ +import * as React from 'react'; +import { StyleSheet, View } from 'react-native'; + +import { + Button, + Card, + Chip, + FAB, + IconButton, + Text, + Tooltip, +} from 'react-native-paper'; + +import type { SampleConfig } from './types'; +import ScreenWrapper from '../ScreenWrapper'; + +export const ArticleSampleConfig: SampleConfig = { + title: 'Article', + icon: 'newspaper-variant-outline', + components: [ + 'Button', + 'Card', + 'Chip', + 'FAB', + 'IconButton', + 'Text', + 'Tooltip', + ], +}; + +const TOPICS = ['Material 3', 'Design systems', 'React Native']; + +const ArticleSample = () => { + const [liked, setLiked] = React.useState(false); + const [bookmarked, setBookmarked] = React.useState(false); + const [menuExpanded, setMenuExpanded] = React.useState(false); + + return ( + <> + + + + + + + Material Design 3 leans on tonal color, larger corner radii and + motion to express hierarchy. Paper ships those decisions as + components, so a screen built from the defaults already follows + the spec. + + + {TOPICS.map((topic) => ( + + {topic} + + ))} + + + + + + setLiked(!liked)} + /> + + + setBookmarked(!bookmarked)} + /> + + + + + + + + setMenuExpanded(false)} + trigger={{ + icon: 'share-variant', + 'aria-label': 'Share', + onPress: () => setMenuExpanded(true), + }} + items={[ + { icon: 'link', label: 'Copy link', onPress: () => {} }, + { icon: 'email', label: 'Send by email', onPress: () => {} }, + { icon: 'comment-outline', label: 'Comment', onPress: () => {} }, + ]} + /> + + ); +}; + +const styles = StyleSheet.create({ + content: { + padding: 16, + }, + cardContent: { + gap: 16, + }, + cardIcons: { + flexDirection: 'row', + alignItems: 'center', + }, + topics: { + flexDirection: 'row', + flexWrap: 'wrap', + gap: 8, + }, +}); + +export default ArticleSample; diff --git a/example/src/Samples/ContactsSample.tsx b/example/src/Samples/ContactsSample.tsx new file mode 100644 index 0000000000..aed2b5decb --- /dev/null +++ b/example/src/Samples/ContactsSample.tsx @@ -0,0 +1,112 @@ +import * as React from 'react'; +import { FlatList, StyleSheet, View } from 'react-native'; + +import { + Avatar, + Badge, + Divider, + FAB, + List, + Searchbar, +} from 'react-native-paper'; +import { useSafeAreaInsets } from 'react-native-safe-area-context'; + +import type { SampleConfig } from './types'; +import { filterByQuery } from '../../utils/filterByQuery'; +import ScreenWrapper from '../ScreenWrapper'; + +export const ContactsSampleConfig: SampleConfig = { + title: 'Contacts', + icon: 'account-group-outline', + components: ['Avatar', 'Badge', 'Divider', 'FAB', 'List', 'Searchbar'], +}; + +const CONTACTS = [ + { id: '1', name: 'Ada Lovelace', role: 'Engineering', unread: 3 }, + { id: '2', name: 'Grace Hopper', role: 'Engineering', unread: 0 }, + { id: '3', name: 'Katherine Johnson', role: 'Research', unread: 12 }, + { id: '4', name: 'Mary Jackson', role: 'Research', unread: 0 }, + { id: '5', name: 'Radia Perlman', role: 'Networking', unread: 1 }, + { id: '6', name: 'Barbara Liskov', role: 'Architecture', unread: 0 }, +]; + +const getInitials = (name: string) => + name + .split(' ') + .map((part) => part[0]) + .join(''); + +const ContactsSample = () => { + const insets = useSafeAreaInsets(); + const [query, setQuery] = React.useState(''); + + const contacts = filterByQuery(CONTACTS, query, ({ name }) => [name]); + + return ( + <> + + + contact.id} + keyboardShouldPersistTaps="handled" + ItemSeparatorComponent={Divider} + contentContainerStyle={{ paddingBottom: insets.bottom + 96 }} + renderItem={({ item }) => ( + {}} + left={({ style }) => ( + + )} + right={({ style }) => + item.unread ? ( + {item.unread} + ) : null + } + /> + )} + /> + + + + {}} + /> + + + ); +}; + +const styles = StyleSheet.create({ + searchbar: { + margin: 16, + }, + badge: { + alignSelf: 'center', + }, + fabContainer: { + position: 'absolute', + left: 16, + right: 16, + alignItems: 'flex-end', + }, +}); + +export default ContactsSample; diff --git a/example/src/Samples/HelpCenterSample.tsx b/example/src/Samples/HelpCenterSample.tsx new file mode 100644 index 0000000000..841a6454d7 --- /dev/null +++ b/example/src/Samples/HelpCenterSample.tsx @@ -0,0 +1,108 @@ +import * as React from 'react'; +import { StyleSheet, View } from 'react-native'; + +import { + Icon, + List, + Modal, + Text, + TouchableRipple, + useTheme, +} from 'react-native-paper'; + +import type { SampleConfig } from './types'; +import ScreenWrapper from '../ScreenWrapper'; + +export const HelpCenterSampleConfig: SampleConfig = { + title: 'Help center', + icon: 'help-circle-outline', + components: ['Icon', 'List', 'Modal', 'Text', 'TouchableRipple'], +}; + +const TOPICS = [ + { + id: 'getting-started', + title: 'Getting started', + icon: 'rocket-launch-outline', + answers: ['Install the app', 'Create your first workspace'], + }, + { + id: 'billing', + title: 'Billing', + icon: 'credit-card-outline', + answers: ['Update your payment method', 'Download past invoices'], + }, + { + id: 'privacy', + title: 'Privacy', + icon: 'shield-lock-outline', + answers: ['Manage data sharing', 'Delete your account'], + }, +]; + +const HelpCenterSample = () => { + const { colors } = useTheme(); + const [contactVisible, setContactVisible] = React.useState(false); + + return ( + <> + + + + {TOPICS.map((topic) => ( + } + > + {topic.answers.map((answer) => ( + {}} /> + ))} + + ))} + + + + setContactVisible(true)}> + + + Still stuck? Contact support + + + + + setContactVisible(false)} + aria-label="Contact support" + dismissAccessibilityLabel="Close contact support" + contentBorderRadius={28} + contentBackgroundColor={colors.surface} + contentContainerStyle={styles.modal} + > + Contact support + + Write to support@example.com and we will get back to you within one + business day. + + + + ); +}; + +const styles = StyleSheet.create({ + contact: { + flexDirection: 'row', + alignItems: 'center', + gap: 16, + padding: 16, + }, + modal: { + margin: 24, + padding: 24, + gap: 8, + }, +}); + +export default HelpCenterSample; diff --git a/example/src/Samples/OrdersSample.tsx b/example/src/Samples/OrdersSample.tsx new file mode 100644 index 0000000000..620be5fe2d --- /dev/null +++ b/example/src/Samples/OrdersSample.tsx @@ -0,0 +1,158 @@ +import * as React from 'react'; +import { StyleSheet, View } from 'react-native'; + +import { + Banner, + Button, + Checkbox, + DataTable, + Menu, + Text, +} from 'react-native-paper'; + +import type { SampleConfig } from './types'; +import { objectKeys } from '../../utils/typedObject'; +import ScreenWrapper from '../ScreenWrapper'; + +export const OrdersSampleConfig: SampleConfig = { + title: 'Orders', + icon: 'table-large', + components: ['Banner', 'Button', 'Checkbox', 'DataTable', 'Menu', 'Text'], +}; + +const ORDERS = [ + { id: 'A-1041', customer: 'Ada Lovelace', total: 128 }, + { id: 'A-1042', customer: 'Grace Hopper', total: 64 }, + { id: 'A-1043', customer: 'Alan Turing', total: 512 }, + { id: 'A-1044', customer: 'Barbara Liskov', total: 96 }, + { id: 'A-1045', customer: 'Radia Perlman', total: 240 }, + { id: 'A-1046', customer: 'Mary Jackson', total: 32 }, +]; + +const ITEMS_PER_PAGE = 3; + +type SortKey = 'id' | 'customer' | 'total'; + +const SORT_LABELS: Record = { + id: 'Order number', + customer: 'Customer', + total: 'Total', +}; + +const OrdersSample = () => { + const [bannerVisible, setBannerVisible] = React.useState(true); + const [menuVisible, setMenuVisible] = React.useState(false); + const [sortBy, setSortBy] = React.useState('id'); + const [selected, setSelected] = React.useState([]); + const [page, setPage] = React.useState(0); + + const sorted = ORDERS.slice().sort((a, b) => + sortBy === 'total' + ? a.total - b.total + : String(a[sortBy]).localeCompare(String(b[sortBy])) + ); + + const from = page * ITEMS_PER_PAGE; + const to = Math.min(from + ITEMS_PER_PAGE, sorted.length); + + const toggleSelected = (id: string) => + setSelected((current) => + current.includes(id) + ? current.filter((item) => item !== id) + : [...current, id] + ); + + const selectSort = (key: SortKey) => { + setSortBy(key); + setMenuVisible(false); + setPage(0); + }; + + return ( + + setBannerVisible(false) }]} + > + Two orders are waiting for a payment confirmation. + + + + {selected.length} selected + setMenuVisible(false)} + anchor={ + + } + > + {objectKeys(SORT_LABELS).map((key) => ( + selectSort(key)} + /> + ))} + + + + + + + Order + + Customer + + Total + + + {sorted.slice(from, to).map((order) => ( + + + toggleSelected(order.id)} + /> + + {order.id} + + {order.customer} + + {`$${order.total}`} + + ))} + + + + + ); +}; + +const styles = StyleSheet.create({ + toolbar: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + padding: 16, + }, + selectColumn: { + flex: 0.5, + }, + customerColumn: { + flex: 2, + }, +}); + +export default OrdersSample; diff --git a/example/src/Samples/PlayerSample.tsx b/example/src/Samples/PlayerSample.tsx new file mode 100644 index 0000000000..50f5d40116 --- /dev/null +++ b/example/src/Samples/PlayerSample.tsx @@ -0,0 +1,94 @@ +import * as React from 'react'; +import { StyleSheet, View } from 'react-native'; + +import { + Icon, + IconButton, + ProgressBar, + SegmentedButtons, + Surface, + Text, +} from 'react-native-paper'; + +import type { SampleConfig } from './types'; +import ScreenWrapper from '../ScreenWrapper'; + +export const PlayerSampleConfig: SampleConfig = { + title: 'Now playing', + icon: 'play-circle-outline', + components: [ + 'Icon', + 'IconButton', + 'ProgressBar', + 'SegmentedButtons', + 'Surface', + 'Text', + ], +}; + +const repeatModes = [ + { value: 'off', icon: 'repeat-off', label: 'Repeat off' }, + { value: 'one', icon: 'repeat-once', label: 'Repeat one' }, + { value: 'all', icon: 'repeat', label: 'Repeat all' }, +]; + +const PlayerSample = () => { + const [repeat, setRepeat] = React.useState('off'); + const [speed, setSpeed] = React.useState('1'); + + return ( + + + + + + + Nightfall + Aurora Skies · Long Way Home + + + + + + {repeatModes.map(({ value, icon, label }) => ( + setRepeat(value)} + /> + ))} + + + + + ); +}; + +const styles = StyleSheet.create({ + content: { + padding: 16, + gap: 24, + }, + row: { + flexDirection: 'row', + justifyContent: 'center', + }, + cover: { + height: 200, + alignItems: 'center', + justifyContent: 'center', + }, +}); + +export default PlayerSample; diff --git a/example/src/Samples/SettingsSample.tsx b/example/src/Samples/SettingsSample.tsx new file mode 100644 index 0000000000..c4cd28cde4 --- /dev/null +++ b/example/src/Samples/SettingsSample.tsx @@ -0,0 +1,112 @@ +import * as React from 'react'; + +import { + Button, + Dialog, + Divider, + List, + RadioButton, + Switch, + Text, +} from 'react-native-paper'; + +import type { SampleConfig } from './types'; +import ScreenWrapper from '../ScreenWrapper'; + +export const SettingsSampleConfig: SampleConfig = { + title: 'Settings', + icon: 'cog-outline', + components: [ + 'Button', + 'Dialog', + 'Divider', + 'List', + 'RadioButton', + 'Switch', + 'Text', + ], +}; + +const SettingsSample = () => { + const [notifications, setNotifications] = React.useState(true); + const [backgroundSync, setBackgroundSync] = React.useState(false); + const [density, setDensity] = React.useState('comfortable'); + const [dialogVisible, setDialogVisible] = React.useState(false); + + const hideDialog = () => setDialogVisible(false); + + return ( + + + Notifications + ( + + )} + /> + ( + + )} + /> + + + + + + List density + + + + + + + + + + Account + } + onPress={() => setDialogVisible(true)} + role="button" + accessibilityHint="Opens a confirmation dialog" + /> + + + + You will need to sign in again to access your workspace. + + } + actions={[ + , + , + ]} + /> + + ); +}; + +export default SettingsSample; diff --git a/example/src/Samples/SignUpSample.tsx b/example/src/Samples/SignUpSample.tsx new file mode 100644 index 0000000000..a1ebecf242 --- /dev/null +++ b/example/src/Samples/SignUpSample.tsx @@ -0,0 +1,111 @@ +import * as React from 'react'; +import { StyleSheet } from 'react-native'; + +import { + Button, + Checkbox, + Divider, + Snackbar, + Text, + TextInput, +} from 'react-native-paper'; +import type { TextInputAccessoryProps } from 'react-native-paper'; + +import type { SampleConfig } from './types'; +import ScreenWrapper from '../ScreenWrapper'; + +export const SignUpSampleConfig: SampleConfig = { + title: 'Sign up', + icon: 'account-plus-outline', + components: [ + 'Button', + 'Checkbox', + 'Divider', + 'Snackbar', + 'Text', + 'TextInput', + ], +}; + +const SignUpSample = () => { + const [email, setEmail] = React.useState(''); + const [password, setPassword] = React.useState(''); + const [secure, setSecure] = React.useState(true); + const [accepted, setAccepted] = React.useState(false); + const [submitted, setSubmitted] = React.useState(false); + + const emailIcon = (props: TextInputAccessoryProps) => ( + + ); + + const passwordIcon = (props: TextInputAccessoryProps) => ( + setSecure(!secure)} + /> + ); + + return ( + <> + + Create your account + + Sign up to sync your projects across every device. + + + + + + setAccepted(!accepted)} + /> + + + + + + + + setSubmitted(false)}> + Account created + + + ); +}; + +const styles = StyleSheet.create({ + content: { + padding: 16, + gap: 16, + }, +}); + +export default SignUpSample; diff --git a/example/src/Samples/WorkspaceSample.tsx b/example/src/Samples/WorkspaceSample.tsx new file mode 100644 index 0000000000..4bf50b0636 --- /dev/null +++ b/example/src/Samples/WorkspaceSample.tsx @@ -0,0 +1,604 @@ +import * as React from 'react'; +import { StyleSheet, View } from 'react-native'; +import type { NativeScrollEvent, NativeSyntheticEvent } from 'react-native'; + +import { useNavigation, usePreventRemove } from '@react-navigation/native'; +import { + ActivityIndicator, + Appbar, + Avatar, + Badge, + BottomNavigation, + FAB, + IconButton, + Text, + TouchableRipple, + useTheme, +} from 'react-native-paper'; +import type { BottomNavigationRoute, Theme } from 'react-native-paper'; + +import type { SampleConfig } from './types'; +import PreferencesAction from '../Preferences/PreferencesAction'; +import ScreenWrapper from '../ScreenWrapper'; + +export const WorkspaceSampleConfig: SampleConfig = { + title: 'Workspace', + icon: 'view-dashboard-outline', + headerShown: false, + components: [ + 'ActivityIndicator', + 'Appbar', + 'Avatar', + 'Badge', + 'BottomNavigation', + 'FAB', + 'IconButton', + 'Text', + 'TouchableRipple', + ], +}; + +type Message = { + id: string; + sender: string; + subject: string; + snippet: string; + time: string; + unread: boolean; + starred: boolean; +}; + +const INITIAL_MESSAGES: Message[] = [ + { + id: '1', + sender: 'Ken Thompson', + subject: 'Release 2.4 is out', + snippet: 'Changelog and migration notes are attached to the post.', + time: '09:41', + unread: true, + starred: false, + }, + { + id: '2', + sender: 'Calendar', + subject: 'Design review moved to 14:00', + snippet: 'The meeting room changed too. See the updated invite.', + time: '08:15', + unread: true, + starred: true, + }, + { + id: '3', + sender: 'Frances Allen', + subject: 'Compiler benchmarks', + snippet: 'The new pass is 12% faster on the large fixture set.', + time: '07:02', + unread: true, + starred: false, + }, + { + id: '4', + sender: 'Release Bot', + subject: 'Nightly build succeeded', + snippet: 'All 1,224 tests passed on iOS, Android and web.', + time: 'Yesterday', + unread: true, + starred: false, + }, + { + id: '5', + sender: 'Dennis Ritchie', + subject: 'Re: naming things', + snippet: 'Short names are fine as long as the scope is small.', + time: 'Mon', + unread: false, + starred: false, + }, + { + id: '6', + sender: 'Edsger Dijkstra', + subject: 'Re: shortest path to the office', + snippet: 'Take the second left, it saves you four minutes.', + time: 'Sun', + unread: false, + starred: true, + }, +]; + +const INCOMING_MESSAGES: Omit[] = [ + { + sender: 'Margaret Hamilton', + subject: 'Launch checklist v2', + snippet: 'Added the abort scenarios we discussed on Friday.', + time: 'Now', + }, + { + sender: 'Donald Knuth', + subject: 'Chapter 7 is ready for review', + snippet: 'Please send corrections before the end of the month.', + time: 'Now', + }, +]; + +const SYNC_DURATION = 1500; + +const TEAM = ['Ken Thompson', 'Frances Allen', 'Dennis Ritchie']; + +const getAvatarColors = (sender: string, colors: Theme['colors']) => { + const palette = [ + [colors.primary, colors.onPrimary], + [colors.primaryContainer, colors.onPrimaryContainer], + [colors.secondary, colors.onSecondary], + [colors.secondaryContainer, colors.onSecondaryContainer], + [colors.tertiary, colors.onTertiary], + [colors.tertiaryContainer, colors.onTertiaryContainer], + ]; + const hash = [...sender].reduce( + (sum, char) => (sum * 31 + char.charCodeAt(0)) % 997, + 7 + ); + + return palette[hash % palette.length]; +}; + +type MessageRowProps = { + message: Message; + selected: boolean; + onPress: () => void; + onToggleSelection: () => void; + onToggleStar: () => void; +}; + +const MessageRow = ({ + message, + selected, + onPress, + onToggleSelection, + onToggleStar, +}: MessageRowProps) => { + const { colors } = useTheme(); + const [avatarBackground, avatarColor] = getAvatarColors( + message.sender, + colors + ); + const emphasis = message.unread + ? [styles.unread, { color: colors.onSurface }] + : { color: colors.onSurfaceVariant }; + + const accessibilityLabel = [ + message.unread ? 'Unread' : null, + message.sender, + message.subject, + message.time, + ] + .filter(Boolean) + .join(', '); + + return ( + + { + if (nativeEvent.actionName === 'toggleSelection') { + onToggleSelection(); + } + }} + onPress={onPress} + onLongPress={onToggleSelection} + style={styles.row} + > + + {selected ? ( + + ) : ( + + )} + + + + {message.sender} + + + {message.time} + + {message.unread ? ( + + ) : null} + + + + + {message.subject} + + + {message.snippet} + + + + + + + + + + + + ); +}; + +type InboxProps = { + messages: Message[]; + selectedIds: string[]; + onOpen: (id: string) => void; + onToggleSelection: (id: string) => void; + onToggleStar: (id: string) => void; +}; + +const Inbox = ({ + messages, + selectedIds, + onOpen, + onToggleSelection, + onToggleStar, +}: InboxProps) => { + const { colors } = useTheme(); + const [composeExpanded, setComposeExpanded] = React.useState(true); + const lastOffset = React.useRef(0); + const selectionMode = selectedIds.length > 0; + + const handleScroll = ({ + nativeEvent, + }: NativeSyntheticEvent) => { + const offset = nativeEvent.contentOffset.y; + setComposeExpanded(offset <= 0 || offset < lastOffset.current); + lastOffset.current = offset; + }; + + return ( + + + {messages.length === 0 ? ( + + All caught up + + ) : ( + messages.map((message) => ( + + selectionMode + ? onToggleSelection(message.id) + : onOpen(message.id) + } + onToggleSelection={() => onToggleSelection(message.id)} + onToggleStar={() => onToggleStar(message.id)} + /> + )) + )} + + + {}} + /> + + + ); +}; + +const TasksRoute = () => ( + + Today + Review the release checklist + Prepare the design handoff + +); + +const TeamRoute = () => ( + + {TEAM.map((member) => ( + + + {member} + + ))} + +); + +const WorkspaceSample = () => { + const navigation = useNavigation('WorkspaceSample'); + const [index, setIndex] = React.useState(0); + const [messages, setMessages] = React.useState(INITIAL_MESSAGES); + const [selectedIds, setSelectedIds] = React.useState([]); + const [syncing, setSyncing] = React.useState(false); + const syncCount = React.useRef(0); + const syncTimeout = React.useRef>(undefined); + + const selectionMode = selectedIds.length > 0; + const unreadCount = messages.filter((message) => message.unread).length; + + const clearSelection = () => setSelectedIds([]); + + usePreventRemove(selectionMode, clearSelection); + + React.useEffect(() => () => clearTimeout(syncTimeout.current), []); + + const toggleSelection = (id: string) => + setSelectedIds((ids) => + ids.includes(id) ? ids.filter((item) => item !== id) : [...ids, id] + ); + + const updateMessages = (ids: string[], changes: Partial) => + setMessages((items) => + items.map((message) => + ids.includes(message.id) ? { ...message, ...changes } : message + ) + ); + + const toggleStar = (id: string) => + setMessages((items) => + items.map((message) => + message.id === id ? { ...message, starred: !message.starred } : message + ) + ); + + const archiveSelected = () => { + setMessages((items) => + items.filter((message) => !selectedIds.includes(message.id)) + ); + clearSelection(); + }; + + const markSelectedAsRead = () => { + updateMessages(selectedIds, { unread: false }); + clearSelection(); + }; + + const sync = () => { + setSyncing(true); + syncTimeout.current = setTimeout(() => { + const incoming = + INCOMING_MESSAGES[syncCount.current % INCOMING_MESSAGES.length]; + syncCount.current += 1; + setMessages((items) => [ + { + ...incoming, + id: `incoming-${syncCount.current}`, + unread: true, + starred: false, + }, + ...items, + ]); + setSyncing(false); + }, SYNC_DURATION); + }; + + const handleIndexChange = (newIndex: number) => { + clearSelection(); + setIndex(newIndex); + }; + + const routes: BottomNavigationRoute[] = [ + { + key: 'inbox', + title: 'Inbox', + focusedIcon: 'inbox', + unfocusedIcon: 'inbox-outline', + badge: unreadCount > 0 ? unreadCount : false, + }, + { + key: 'tasks', + title: 'Tasks', + focusedIcon: 'check-circle', + unfocusedIcon: 'check-circle-outline', + }, + { + key: 'team', + title: 'Team', + focusedIcon: 'account-group', + unfocusedIcon: 'account-group-outline', + }, + ]; + + const renderScene = ({ route }: { route: BottomNavigationRoute }) => { + switch (route.key) { + case 'inbox': + return ( + updateMessages([id], { unread: false })} + onToggleSelection={toggleSelection} + onToggleStar={toggleStar} + /> + ); + case 'tasks': + return ; + case 'team': + return ; + default: + return null; + } + }; + + return ( + + {selectionMode ? ( + + + + + + + ) : ( + + navigation.goBack()} /> + + {syncing ? ( + + ) : ( + + )} + {}} + /> + + + )} + + + ); +}; + +const styles = StyleSheet.create({ + screen: { + flex: 1, + }, + content: { + padding: 16, + gap: 16, + }, + inbox: { + paddingTop: 8, + paddingBottom: 96, + }, + empty: { + padding: 16, + }, + row: { + paddingHorizontal: 16, + paddingVertical: 8, + }, + rowContent: { + flexDirection: 'row', + gap: 16, + }, + message: { + flex: 1, + }, + line: { + flexDirection: 'row', + alignItems: 'center', + gap: 8, + }, + grow: { + flex: 1, + }, + unread: { + fontWeight: '700', + }, + unreadDot: { + alignSelf: 'center', + }, + starSpace: { + width: 20, + }, + starContainer: { + position: 'absolute', + left: 8, + right: 8, + bottom: 10, + alignItems: 'flex-end', + }, + star: { + margin: 0, + }, + fabContainer: { + position: 'absolute', + left: 16, + right: 16, + bottom: 16, + alignItems: 'flex-end', + }, + member: { + flexDirection: 'row', + alignItems: 'center', + gap: 16, + }, + syncIndicator: { + marginHorizontal: 12, + }, +}); + +export default WorkspaceSample; diff --git a/example/src/Samples/types.ts b/example/src/Samples/types.ts new file mode 100644 index 0000000000..1ea5e6a460 --- /dev/null +++ b/example/src/Samples/types.ts @@ -0,0 +1,8 @@ +import type { AvatarIconProps } from 'react-native-paper'; + +export type SampleConfig = { + title: string; + icon: AvatarIconProps['icon']; + components: string[]; + headerShown?: boolean; +}; diff --git a/example/src/SamplesList.tsx b/example/src/SamplesList.tsx new file mode 100644 index 0000000000..774e55a112 --- /dev/null +++ b/example/src/SamplesList.tsx @@ -0,0 +1,96 @@ +import { FlatList, StyleSheet, View } from 'react-native'; + +import { useNavigation } from '@react-navigation/native'; +import { Avatar, Card, Text, useTheme } from 'react-native-paper'; +import { useSafeAreaInsets } from 'react-native-safe-area-context'; + +import ArticleSample, { ArticleSampleConfig } from './Samples/ArticleSample'; +import ContactsSample, { ContactsSampleConfig } from './Samples/ContactsSample'; +import HelpCenterSample, { + HelpCenterSampleConfig, +} from './Samples/HelpCenterSample'; +import OrdersSample, { OrdersSampleConfig } from './Samples/OrdersSample'; +import PlayerSample, { PlayerSampleConfig } from './Samples/PlayerSample'; +import SettingsSample, { SettingsSampleConfig } from './Samples/SettingsSample'; +import SignUpSample, { SignUpSampleConfig } from './Samples/SignUpSample'; +import WorkspaceSample, { + WorkspaceSampleConfig, +} from './Samples/WorkspaceSample'; +import { objectKeys } from '../utils/typedObject'; + +export const samples = { + SignUpSample: { ...SignUpSampleConfig, screen: SignUpSample }, + ContactsSample: { ...ContactsSampleConfig, screen: ContactsSample }, + ArticleSample: { ...ArticleSampleConfig, screen: ArticleSample }, + SettingsSample: { ...SettingsSampleConfig, screen: SettingsSample }, + PlayerSample: { ...PlayerSampleConfig, screen: PlayerSample }, + OrdersSample: { ...OrdersSampleConfig, screen: OrdersSample }, + HelpCenterSample: { ...HelpCenterSampleConfig, screen: HelpCenterSample }, + WorkspaceSample: { ...WorkspaceSampleConfig, screen: WorkspaceSample }, +}; + +const data = objectKeys(samples).map((id) => ({ + id, + ...samples[id], +})); + +export default function SamplesList() { + const navigation = useNavigation('SamplesList'); + const safeArea = useSafeAreaInsets(); + const { colors } = useTheme(); + + return ( + id} + contentContainerStyle={[ + styles.content, + { + paddingBottom: safeArea.bottom + 16, + paddingLeft: safeArea.left + 16, + paddingRight: safeArea.right + 16, + }, + ]} + showsVerticalScrollIndicator={false} + renderItem={({ item }) => ( + navigation.navigate(item.id)}> + } + /> + + + {item.components.map((component) => ( + + {component} + + ))} + + + + )} + /> + ); +} + +const styles = StyleSheet.create({ + content: { + padding: 16, + gap: 16, + }, + tags: { + flexDirection: 'row', + flexWrap: 'wrap', + gap: 8, + }, + tag: { + borderWidth: 1, + borderRadius: 8, + paddingHorizontal: 8, + paddingVertical: 4, + }, +}); diff --git a/example/src/index.tsx b/example/src/index.tsx index afa3941044..f6d5464a85 100644 --- a/example/src/index.tsx +++ b/example/src/index.tsx @@ -1,30 +1,19 @@ -import * as React from 'react'; -import { I18nManager, Platform } from 'react-native'; +import { Platform } from 'react-native'; -import AsyncStorage from '@react-native-async-storage/async-storage'; -import { - createDrawerNavigator, - createDrawerScreen, -} from '@react-navigation/drawer'; import { createStaticNavigation } from '@react-navigation/native'; import { useFonts } from 'expo-font'; import { useKeepAwake } from 'expo-keep-awake'; import * as SplashScreen from 'expo-splash-screen'; import { StatusBar } from 'expo-status-bar'; -import * as Updates from 'expo-updates'; -import { - PaperProvider, - DarkTheme, - LightTheme, - DynamicLightTheme, - DynamicDarkTheme, -} from 'react-native-paper'; -import { useSafeAreaInsets } from 'react-native-safe-area-context'; +import { PaperProvider } from 'react-native-paper'; -import DrawerItems from './DrawerItems'; -import { PreferencesContext } from './PreferencesContext'; +import { navigationPersistor } from './navigationPersistence'; +import { PreferencesContext } from './Preferences/PreferencesContext'; +import { + getDirection, + useSetupPreferences, +} from './Preferences/useSetupPreferences'; import App from './RootNavigator'; -import { dynamicThemeSupported } from '../utils'; import { CombinedDarkTheme, CombinedDefaultTheme, @@ -32,54 +21,12 @@ import { createConfiguredFontTheme, } from '../utils/themes'; -const PERSISTENCE_KEY = 'NAVIGATION_STATE'; -const PREFERENCES_KEY = 'APP_PREFERENCES'; - -const getInitialRtl = () => { - if (Platform.OS === 'web' && typeof document !== 'undefined') { - return document.documentElement.dir === 'rtl'; - } - - return I18nManager.getConstants().isRTL; -}; - -const Drawer = createDrawerNavigator({ - screens: { - Home: createDrawerScreen({ - screen: App, - options: { - headerShown: false, - }, - linking: { - path: '', - initialRouteName: 'ExampleList', - }, - }), - }, -}).with(({ Navigator }) => { - const preferences = React.useContext(PreferencesContext); - const insets = useSafeAreaInsets(); - const { left, right } = insets || { left: 0, right: 0 }; - const collapsedDrawerWidth = 100 + Math.max(left, right); +const Navigation = createStaticNavigation(App); - return ( - } - /> - ); -}); - -const Navigation = createStaticNavigation(Drawer); - -type RootDrawerType = typeof Drawer; +type RootNavigationType = typeof App; declare module '@react-navigation/core' { - interface RootNavigator extends RootDrawerType {} + interface RootNavigator extends RootNavigationType {} } export default function PaperExample() { @@ -89,115 +36,16 @@ export default function PaperExample() { Abel: require('../assets/fonts/Abel-Regular.ttf'), }); - const [isReady, setIsReady] = React.useState(false); - - const [shouldUseDynamicTheme, setShouldUseDynamicTheme] = - React.useState(true); - const [isDarkMode, setIsDarkMode] = React.useState(false); - const [rtl, setRtl] = React.useState(getInitialRtl); - const [collapsed, setCollapsed] = React.useState(false); - const [customFontLoaded, setCustomFont] = React.useState(false); - const [rippleEffectEnabled, setRippleEffectEnabled] = React.useState(true); - - const theme = - dynamicThemeSupported && shouldUseDynamicTheme - ? isDarkMode - ? DynamicDarkTheme - : DynamicLightTheme - : isDarkMode - ? DarkTheme - : LightTheme; - - const direction = rtl ? 'rtl' : 'ltr'; - - React.useEffect(() => { - const restorePrefs = async () => { - try { - const prefString = await AsyncStorage.getItem(PREFERENCES_KEY); - const preferences = JSON.parse(prefString || ''); - - if (preferences) { - setIsDarkMode(preferences.theme === 'dark'); - - if (typeof preferences.rtl === 'boolean') { - setRtl(preferences.rtl); - } - } - } catch (e) { - // ignore error - } finally { - setIsReady(true); - } - }; - - void restorePrefs(); - }, []); - - React.useEffect(() => { - const savePrefs = async () => { - if (!isReady) { - return; - } - - try { - await AsyncStorage.setItem( - PREFERENCES_KEY, - JSON.stringify({ - theme: isDarkMode ? 'dark' : 'light', - rtl, - }) - ); - } catch (e) { - // ignore error - } - - if (Platform.OS === 'web' && typeof document !== 'undefined') { - document.documentElement.dir = direction; - } - - if (I18nManager.getConstants().isRTL !== rtl) { - I18nManager.forceRTL(rtl); - - if (Platform.OS !== 'web') { - await Updates.reloadAsync(); - } - } - }; - - void savePrefs(); - }, [direction, isDarkMode, isReady, rtl]); - - const preferences = React.useMemo( - () => ({ - toggleShouldUseDynamicTheme: () => - setShouldUseDynamicTheme((oldValue) => !oldValue), - toggleTheme: () => setIsDarkMode((oldValue) => !oldValue), - toggleRtl: () => setRtl((oldValue) => !oldValue), - toggleCollapsed: () => setCollapsed((oldValue) => !oldValue), - toggleCustomFont: () => setCustomFont((oldValue) => !oldValue), - toggleRippleEffect: () => setRippleEffectEnabled((oldValue) => !oldValue), - customFontLoaded, - rippleEffectEnabled, - shouldUseDynamicTheme, - theme, - collapsed, - rtl, - }), - [ - rtl, - theme, - collapsed, - customFontLoaded, - shouldUseDynamicTheme, - rippleEffectEnabled, - ] - ); + const { preferences, isReady, navigationKey } = useSetupPreferences(); if (!isReady || !fontsLoaded) { return null; } - const combinedTheme = isDarkMode ? CombinedDarkTheme : CombinedDefaultTheme; + const { theme, customFontLoaded, rippleEffectEnabled, rtl } = preferences; + const direction = getDirection(rtl); + + const combinedTheme = theme.dark ? CombinedDarkTheme : CombinedDefaultTheme; const configuredFontTheme = createConfiguredFontTheme(combinedTheme); const configuredFontNavigationTheme = createConfiguredFontNavigationTheme(combinedTheme); @@ -209,25 +57,17 @@ export default function PaperExample() { return ( { void SplashScreen.hideAsync(); diff --git a/example/src/navigationPersistence.ts b/example/src/navigationPersistence.ts new file mode 100644 index 0000000000..ee252eca9d --- /dev/null +++ b/example/src/navigationPersistence.ts @@ -0,0 +1,17 @@ +import AsyncStorage from '@react-native-async-storage/async-storage'; + +const PERSISTENCE_KEY = 'NAVIGATION_STATE_V2'; + +export const navigationPersistor = { + async persist(state: unknown) { + await AsyncStorage.setItem(PERSISTENCE_KEY, JSON.stringify(state)); + }, + async restore() { + const state = await AsyncStorage.getItem(PERSISTENCE_KEY); + + return state ? JSON.parse(state) : undefined; + }, +}; + +export const clearNavigationState = () => + AsyncStorage.removeItem(PERSISTENCE_KEY); diff --git a/example/utils/filterByQuery.ts b/example/utils/filterByQuery.ts new file mode 100644 index 0000000000..5ac1a4e1ae --- /dev/null +++ b/example/utils/filterByQuery.ts @@ -0,0 +1,15 @@ +export const filterByQuery = ( + items: T[], + query: string, + getSearchableText: (item: T) => string[] +) => { + const search = query.trim().toLowerCase(); + + if (!search) { + return items; + } + + return items.filter((item) => + getSearchableText(item).some((text) => text.toLowerCase().includes(search)) + ); +}; diff --git a/example/utils/typedObject.ts b/example/utils/typedObject.ts new file mode 100644 index 0000000000..ef4b87a928 --- /dev/null +++ b/example/utils/typedObject.ts @@ -0,0 +1,20 @@ +/** + * `Object.keys`, `Object.entries` and `Object.fromEntries` all widen keys to + * `string`, which forces an assertion every time an example builds or iterates + * over a known object literal. These wrappers keep the literal key types, so + * call sites stay assertion-free. + */ + +export const objectKeys = (object: T) => + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion + Object.keys(object) as Array; + +export const objectEntries = (object: T) => + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion + Object.entries(object) as Array<[keyof T, T[keyof T]]>; + +export const objectFromEntries = ( + entries: Array<[Key, Value]> +) => + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion + Object.fromEntries(entries) as Record; diff --git a/yarn.lock b/yarn.lock index 5a3598f86a..7682302cad 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4551,26 +4551,6 @@ __metadata: languageName: node linkType: hard -"@react-navigation/drawer@npm:^8.0.0-alpha.58": - version: 8.0.0-alpha.58 - resolution: "@react-navigation/drawer@npm:8.0.0-alpha.58" - dependencies: - "@react-navigation/elements": "npm:^3.0.0-alpha.55" - react-native-drawer-layout: "npm:^5.0.0-alpha.20" - use-latest-callback: "npm:^0.3.5" - peerDependencies: - "@react-navigation/native": ^8.0.0-alpha.51 - react: ">= 19.2.0" - react-native: "*" - react-native-gesture-handler: ">= 3.0.0" - react-native-reanimated: ">= 4.0.0" - react-native-safe-area-context: ">= 5.5.0" - react-native-screens: ">= 4.30.0" - react-native-worklets: ">= 0.4.0" - checksum: 10c0/9e7967a382f8f976efa7db2f98be67dbff414d30101565e68f7ea944a01babaf4d5c185327b51150c3dad95f66452821044d070b408040555f59281431625661 - languageName: node - linkType: hard - "@react-navigation/elements@npm:3.0.0-alpha.55, @react-navigation/elements@npm:^3.0.0-alpha.55": version: 3.0.0-alpha.55 resolution: "@react-navigation/elements@npm:3.0.0-alpha.55" @@ -18043,21 +18023,6 @@ __metadata: languageName: node linkType: hard -"react-native-drawer-layout@npm:^5.0.0-alpha.20": - version: 5.0.0-alpha.20 - resolution: "react-native-drawer-layout@npm:5.0.0-alpha.20" - dependencies: - use-latest-callback: "npm:^0.3.5" - peerDependencies: - react: ">= 19.2.0" - react-native: "*" - react-native-gesture-handler: ">= 3.0.0" - react-native-reanimated: ">= 4.0.0" - react-native-worklets: ">= 0.4.0" - checksum: 10c0/59ba0aad7c6faadcbda2d97ef676e9b0009f50f402fe9f62eef9251f9371d477b3bc28bfaf8174c3af16087d9235f7da812d819cbcc32b619f79f9f533257ebc - languageName: node - linkType: hard - "react-native-gesture-handler@npm:~3.3.0": version: 3.3.0 resolution: "react-native-gesture-handler@npm:3.3.0" @@ -18110,7 +18075,6 @@ __metadata: "@react-native-async-storage/async-storage": "npm:2.2.0" "@react-native-masked-view/masked-view": "npm:0.3.2" "@react-navigation/bottom-tabs": "npm:^8.0.0-alpha.57" - "@react-navigation/drawer": "npm:^8.0.0-alpha.58" "@react-navigation/elements": "npm:3.0.0-alpha.55" "@react-navigation/native": "npm:^8.0.0-alpha.51" "@react-navigation/native-stack": "npm:^8.0.0-alpha.59"