├── android ├── app │ ├── src │ │ ├── main │ │ │ ├── res │ │ │ │ ├── values-night │ │ │ │ │ └── colors.xml │ │ │ │ ├── mipmap-hdpi │ │ │ │ │ ├── ic_launcher.webp │ │ │ │ │ ├── ic_launcher_round.webp │ │ │ │ │ └── ic_launcher_foreground.webp │ │ │ │ ├── mipmap-mdpi │ │ │ │ │ ├── ic_launcher.webp │ │ │ │ │ ├── ic_launcher_round.webp │ │ │ │ │ └── ic_launcher_foreground.webp │ │ │ │ ├── mipmap-xhdpi │ │ │ │ │ ├── ic_launcher.webp │ │ │ │ │ ├── ic_launcher_round.webp │ │ │ │ │ └── ic_launcher_foreground.webp │ │ │ │ ├── mipmap-xxhdpi │ │ │ │ │ ├── ic_launcher.webp │ │ │ │ │ ├── ic_launcher_round.webp │ │ │ │ │ └── ic_launcher_foreground.webp │ │ │ │ ├── mipmap-xxxhdpi │ │ │ │ │ ├── ic_launcher.webp │ │ │ │ │ ├── ic_launcher_round.webp │ │ │ │ │ └── ic_launcher_foreground.webp │ │ │ │ ├── drawable-hdpi │ │ │ │ │ └── splashscreen_logo.png │ │ │ │ ├── drawable-mdpi │ │ │ │ │ └── splashscreen_logo.png │ │ │ │ ├── drawable-xhdpi │ │ │ │ │ └── splashscreen_logo.png │ │ │ │ ├── drawable-xxhdpi │ │ │ │ │ └── splashscreen_logo.png │ │ │ │ ├── drawable-xxxhdpi │ │ │ │ │ └── splashscreen_logo.png │ │ │ │ ├── values │ │ │ │ │ ├── colors.xml │ │ │ │ │ ├── strings.xml │ │ │ │ │ └── styles.xml │ │ │ │ ├── drawable │ │ │ │ │ ├── ic_launcher_background.xml │ │ │ │ │ └── rn_edit_text_material.xml │ │ │ │ └── mipmap-anydpi-v26 │ │ │ │ │ ├── ic_launcher.xml │ │ │ │ │ └── ic_launcher_round.xml │ │ │ ├── AndroidManifest.xml │ │ │ └── java │ │ │ │ └── com │ │ │ │ └── your │ │ │ │ └── app │ │ │ │ ├── MainApplication.kt │ │ │ │ └── MainActivity.kt │ │ └── debug │ │ │ └── AndroidManifest.xml │ ├── debug.keystore │ ├── proguard-rules.pro │ └── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── .gitignore ├── settings.gradle ├── build.gradle ├── gradle.properties ├── gradlew.bat └── gradlew ├── hooks ├── useColorScheme.ts ├── useColorScheme.web.ts └── useThemeColor.ts ├── .vscode └── settings.json ├── artificial ├── dark.png ├── agents.png ├── image.png ├── discover.png ├── settings.png └── wechat-qr.jpg ├── assets ├── images │ ├── icon.png │ ├── favicon.png │ ├── react-logo.png │ ├── splash-icon.png │ ├── adaptive-icon.png │ ├── react-logo@2x.png │ ├── react-logo@3x.png │ └── partial-react-logo.png └── fonts │ └── SpaceMono-Regular.ttf ├── components ├── ui │ ├── TabBarBackground.tsx │ ├── IconSymbol.ios.tsx │ ├── TabBarBackground.ios.tsx │ └── IconSymbol.tsx ├── __tests__ │ ├── ThemedText-test.tsx │ └── __snapshots__ │ │ └── ThemedText-test.tsx.snap ├── ThemedView.tsx ├── HapticTab.tsx ├── ExternalLink.tsx ├── HelloWave.tsx ├── Collapsible.tsx ├── ThemedText.tsx ├── CodeBlock.tsx ├── ParallaxScrollView.tsx └── Message.tsx ├── tsconfig.json ├── .gitignore ├── types └── react-native-syntax-highlighter.d.ts ├── eas.json ├── constants ├── Colors.ts └── Config.ts ├── app ├── +not-found.tsx ├── _layout.tsx ├── (tabs) │ ├── _layout.tsx │ ├── agent.tsx │ ├── settings.tsx │ ├── discover.tsx │ └── index.tsx ├── chats.tsx └── agent │ └── [id].tsx ├── app.json ├── contexts └── ThemeContext.tsx ├── package.json ├── requirement.md ├── scripts └── reset-project.js ├── README.md └── utils ├── storage.ts └── gemini.ts /android/app/src/main/res/values-night/colors.xml: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /hooks/useColorScheme.ts: -------------------------------------------------------------------------------- 1 | export { useColorScheme } from 'react-native'; 2 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "cSpell.words": [ 3 | "Pressable" 4 | ] 5 | } -------------------------------------------------------------------------------- /artificial/dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/artificial/dark.png -------------------------------------------------------------------------------- /artificial/agents.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/artificial/agents.png -------------------------------------------------------------------------------- /artificial/image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/artificial/image.png -------------------------------------------------------------------------------- /assets/images/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/assets/images/icon.png -------------------------------------------------------------------------------- /artificial/discover.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/artificial/discover.png -------------------------------------------------------------------------------- /artificial/settings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/artificial/settings.png -------------------------------------------------------------------------------- /artificial/wechat-qr.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/artificial/wechat-qr.jpg -------------------------------------------------------------------------------- /android/app/debug.keystore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/android/app/debug.keystore -------------------------------------------------------------------------------- /assets/images/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/assets/images/favicon.png -------------------------------------------------------------------------------- /assets/images/react-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/assets/images/react-logo.png -------------------------------------------------------------------------------- /assets/images/splash-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/assets/images/splash-icon.png -------------------------------------------------------------------------------- /assets/images/adaptive-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/assets/images/adaptive-icon.png -------------------------------------------------------------------------------- /assets/images/react-logo@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/assets/images/react-logo@2x.png -------------------------------------------------------------------------------- /assets/images/react-logo@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/assets/images/react-logo@3x.png -------------------------------------------------------------------------------- /assets/fonts/SpaceMono-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/assets/fonts/SpaceMono-Regular.ttf -------------------------------------------------------------------------------- /assets/images/partial-react-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/assets/images/partial-react-logo.png -------------------------------------------------------------------------------- /android/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/android/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-hdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/android/app/src/main/res/mipmap-hdpi/ic_launcher.webp -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-mdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/android/app/src/main/res/mipmap-mdpi/ic_launcher.webp -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /android/app/src/main/res/drawable-hdpi/splashscreen_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/android/app/src/main/res/drawable-hdpi/splashscreen_logo.png -------------------------------------------------------------------------------- /android/app/src/main/res/drawable-mdpi/splashscreen_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/android/app/src/main/res/drawable-mdpi/splashscreen_logo.png -------------------------------------------------------------------------------- /android/app/src/main/res/drawable-xhdpi/splashscreen_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/android/app/src/main/res/drawable-xhdpi/splashscreen_logo.png -------------------------------------------------------------------------------- /android/app/src/main/res/drawable-xxhdpi/splashscreen_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/android/app/src/main/res/drawable-xxhdpi/splashscreen_logo.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /android/app/src/main/res/drawable-xxxhdpi/splashscreen_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/android/app/src/main/res/drawable-xxxhdpi/splashscreen_logo.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bravekingzhang/gemini-pro-chatbot/HEAD/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp -------------------------------------------------------------------------------- /components/ui/TabBarBackground.tsx: -------------------------------------------------------------------------------- 1 | // This is a shim for web and Android where the tab bar is generally opaque. 2 | export default undefined; 3 | 4 | export function useBottomTabOverflow() { 5 | return 0; 6 | } 7 | -------------------------------------------------------------------------------- /android/.gitignore: -------------------------------------------------------------------------------- 1 | # OSX 2 | # 3 | .DS_Store 4 | 5 | # Android/IntelliJ 6 | # 7 | build/ 8 | .idea 9 | .gradle 10 | local.properties 11 | *.iml 12 | *.hprof 13 | .cxx/ 14 | 15 | # Bundle artifacts 16 | *.jsbundle 17 | -------------------------------------------------------------------------------- /android/app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | #ffffff 3 | #ffffff 4 | #023c69 5 | #ffffff 6 | -------------------------------------------------------------------------------- /android/app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-all.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /components/__tests__/ThemedText-test.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import renderer from 'react-test-renderer'; 3 | 4 | import { ThemedText } from '../ThemedText'; 5 | 6 | it(`renders correctly`, () => { 7 | const tree = renderer.create(Snapshot test!).toJSON(); 8 | 9 | expect(tree).toMatchSnapshot(); 10 | }); 11 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "expo/tsconfig.base", 3 | "compilerOptions": { 4 | "strict": true, 5 | "baseUrl": ".", 6 | "paths": { 7 | "@/*": [ 8 | "./*" 9 | ] 10 | } 11 | }, 12 | "include": [ 13 | "**/*.ts", 14 | "**/*.tsx", 15 | ".expo/types/**/*.ts", 16 | "expo-env.d.ts" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /android/app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | gemini-pro-chatbot 3 | automatic 4 | contain 5 | false 6 | -------------------------------------------------------------------------------- /android/app/src/debug/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /components/__tests__/__snapshots__/ThemedText-test.tsx.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`renders correctly 1`] = ` 4 | 22 | Snapshot test! 23 | 24 | `; 25 | -------------------------------------------------------------------------------- /components/ThemedView.tsx: -------------------------------------------------------------------------------- 1 | import { View, type ViewProps } from 'react-native'; 2 | 3 | import { useThemeColor } from '@/hooks/useThemeColor'; 4 | 5 | export type ThemedViewProps = ViewProps & { 6 | lightColor?: string; 7 | darkColor?: string; 8 | }; 9 | 10 | export function ThemedView({ style, lightColor, darkColor, ...otherProps }: ThemedViewProps) { 11 | const backgroundColor = useThemeColor({ light: lightColor, dark: darkColor }, 'background'); 12 | 13 | return ; 14 | } 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Learn more https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files 2 | 3 | # dependencies 4 | node_modules/ 5 | 6 | # Expo 7 | .expo/ 8 | dist/ 9 | web-build/ 10 | expo-env.d.ts 11 | 12 | # Native 13 | *.orig.* 14 | *.jks 15 | *.p8 16 | *.p12 17 | *.key 18 | *.mobileprovision 19 | 20 | # Metro 21 | .metro-health-check* 22 | 23 | # debug 24 | npm-debug.* 25 | yarn-debug.* 26 | yarn-error.* 27 | 28 | # macOS 29 | .DS_Store 30 | *.pem 31 | 32 | # local env files 33 | .env*.local 34 | 35 | # typescript 36 | *.tsbuildinfo 37 | 38 | app-example 39 | -------------------------------------------------------------------------------- /types/react-native-syntax-highlighter.d.ts: -------------------------------------------------------------------------------- 1 | declare module 'react-native-syntax-highlighter' { 2 | import { StyleProp, ViewStyle } from 'react-native'; 3 | 4 | interface SyntaxHighlighterProps { 5 | language?: string; 6 | style?: any; 7 | customStyle?: StyleProp; 8 | highlighter?: string; 9 | children: string; 10 | } 11 | 12 | export default function SyntaxHighlighter(props: SyntaxHighlighterProps): JSX.Element; 13 | } 14 | 15 | declare module 'react-syntax-highlighter/dist/cjs/styles/hljs' { 16 | const vs2015: any; 17 | export { vs2015 }; 18 | } -------------------------------------------------------------------------------- /hooks/useColorScheme.web.ts: -------------------------------------------------------------------------------- 1 | import { useEffect, useState } from 'react'; 2 | import { useColorScheme as useRNColorScheme } from 'react-native'; 3 | 4 | /** 5 | * To support static rendering, this value needs to be re-calculated on the client side for web 6 | */ 7 | export function useColorScheme() { 8 | const [hasHydrated, setHasHydrated] = useState(false); 9 | 10 | useEffect(() => { 11 | setHasHydrated(true); 12 | }, []); 13 | 14 | const colorScheme = useRNColorScheme(); 15 | 16 | if (hasHydrated) { 17 | return colorScheme; 18 | } 19 | 20 | return 'light'; 21 | } 22 | -------------------------------------------------------------------------------- /android/app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # react-native-reanimated 11 | -keep class com.swmansion.reanimated.** { *; } 12 | -keep class com.facebook.react.turbomodule.** { *; } 13 | 14 | # Add any project specific keep options here: 15 | -------------------------------------------------------------------------------- /hooks/useThemeColor.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Learn more about light and dark modes: 3 | * https://docs.expo.dev/guides/color-schemes/ 4 | */ 5 | 6 | import { Colors } from '@/constants/Colors'; 7 | import { useColorScheme } from '@/hooks/useColorScheme'; 8 | 9 | export function useThemeColor( 10 | props: { light?: string; dark?: string }, 11 | colorName: keyof typeof Colors.light & keyof typeof Colors.dark 12 | ) { 13 | const theme = useColorScheme() ?? 'light'; 14 | const colorFromProps = props[theme]; 15 | 16 | if (colorFromProps) { 17 | return colorFromProps; 18 | } else { 19 | return Colors[theme][colorName]; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /components/HapticTab.tsx: -------------------------------------------------------------------------------- 1 | import { BottomTabBarButtonProps } from '@react-navigation/bottom-tabs'; 2 | import { PlatformPressable } from '@react-navigation/elements'; 3 | import * as Haptics from 'expo-haptics'; 4 | 5 | export function HapticTab(props: BottomTabBarButtonProps) { 6 | return ( 7 | { 10 | if (process.env.EXPO_OS === 'ios') { 11 | // Add a soft haptic feedback when pressing down on the tabs. 12 | Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light); 13 | } 14 | props.onPressIn?.(ev); 15 | }} 16 | /> 17 | ); 18 | } 19 | -------------------------------------------------------------------------------- /eas.json: -------------------------------------------------------------------------------- 1 | { 2 | "cli": { 3 | "version": ">= 13.4.2", 4 | "appVersionSource": "remote" 5 | }, 6 | "build": { 7 | "preview": { 8 | "android": { 9 | "buildType": "apk" 10 | } 11 | }, 12 | "preview2": { 13 | "android": { 14 | "gradleCommand": ":app:assembleRelease" 15 | } 16 | }, 17 | "preview3": { 18 | "developmentClient": true 19 | }, 20 | "preview4": { 21 | "distribution": "internal" 22 | }, 23 | "production": { 24 | "android": { 25 | "buildType": "apk" 26 | }, 27 | "env": { 28 | "ANDROID_SDK_ROOT": "/Users/brzhang/Library/Android/sdk" 29 | } 30 | } 31 | }, 32 | "submit": { 33 | "production": {} 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /components/ui/IconSymbol.ios.tsx: -------------------------------------------------------------------------------- 1 | import { SymbolView, SymbolViewProps, SymbolWeight } from 'expo-symbols'; 2 | import { StyleProp, ViewStyle } from 'react-native'; 3 | 4 | export function IconSymbol({ 5 | name, 6 | size = 24, 7 | color, 8 | style, 9 | weight = 'regular', 10 | }: { 11 | name: SymbolViewProps['name']; 12 | size?: number; 13 | color: string; 14 | style?: StyleProp; 15 | weight?: SymbolWeight; 16 | }) { 17 | return ( 18 | 31 | ); 32 | } 33 | -------------------------------------------------------------------------------- /components/ExternalLink.tsx: -------------------------------------------------------------------------------- 1 | import { Link } from 'expo-router'; 2 | import { openBrowserAsync } from 'expo-web-browser'; 3 | import { type ComponentProps } from 'react'; 4 | import { Platform } from 'react-native'; 5 | 6 | type Props = Omit, 'href'> & { href: string }; 7 | 8 | export function ExternalLink({ href, ...rest }: Props) { 9 | return ( 10 | { 15 | if (Platform.OS !== 'web') { 16 | // Prevent the default behavior of linking to the default browser on native. 17 | event.preventDefault(); 18 | // Open the link in an in-app browser. 19 | await openBrowserAsync(href); 20 | } 21 | }} 22 | /> 23 | ); 24 | } 25 | -------------------------------------------------------------------------------- /components/ui/TabBarBackground.ios.tsx: -------------------------------------------------------------------------------- 1 | import { useBottomTabBarHeight } from '@react-navigation/bottom-tabs'; 2 | import { BlurView } from 'expo-blur'; 3 | import { StyleSheet } from 'react-native'; 4 | import { useSafeAreaInsets } from 'react-native-safe-area-context'; 5 | 6 | export default function BlurTabBarBackground() { 7 | return ( 8 | 15 | ); 16 | } 17 | 18 | export function useBottomTabOverflow() { 19 | const tabHeight = useBottomTabBarHeight(); 20 | const { bottom } = useSafeAreaInsets(); 21 | return tabHeight - bottom; 22 | } 23 | -------------------------------------------------------------------------------- /constants/Colors.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Below are the colors that are used in the app. The colors are defined in the light and dark mode. 3 | * There are many other ways to style your app. For example, [Nativewind](https://www.nativewind.dev/), [Tamagui](https://tamagui.dev/), [unistyles](https://reactnativeunistyles.vercel.app), etc. 4 | */ 5 | 6 | const tintColorLight = '#0a7ea4'; 7 | const tintColorDark = '#fff'; 8 | 9 | export const Colors = { 10 | light: { 11 | text: '#11181C', 12 | background: '#fff', 13 | tint: tintColorLight, 14 | icon: '#687076', 15 | tabIconDefault: '#687076', 16 | tabIconSelected: tintColorLight, 17 | }, 18 | dark: { 19 | text: '#ECEDEE', 20 | background: '#151718', 21 | tint: tintColorDark, 22 | icon: '#9BA1A6', 23 | tabIconDefault: '#9BA1A6', 24 | tabIconSelected: tintColorDark, 25 | }, 26 | }; 27 | -------------------------------------------------------------------------------- /app/+not-found.tsx: -------------------------------------------------------------------------------- 1 | import { Link, Stack } from 'expo-router'; 2 | import { StyleSheet } from 'react-native'; 3 | 4 | import { ThemedText } from '@/components/ThemedText'; 5 | import { ThemedView } from '@/components/ThemedView'; 6 | 7 | export default function NotFoundScreen() { 8 | return ( 9 | <> 10 | 11 | 12 | This screen doesn't exist. 13 | 14 | Go to home screen! 15 | 16 | 17 | 18 | ); 19 | } 20 | 21 | const styles = StyleSheet.create({ 22 | container: { 23 | flex: 1, 24 | alignItems: 'center', 25 | justifyContent: 'center', 26 | padding: 20, 27 | }, 28 | link: { 29 | marginTop: 15, 30 | paddingVertical: 15, 31 | }, 32 | }); 33 | -------------------------------------------------------------------------------- /components/HelloWave.tsx: -------------------------------------------------------------------------------- 1 | import { useEffect } from 'react'; 2 | import { StyleSheet } from 'react-native'; 3 | import Animated, { 4 | useSharedValue, 5 | useAnimatedStyle, 6 | withTiming, 7 | withRepeat, 8 | withSequence, 9 | } from 'react-native-reanimated'; 10 | 11 | import { ThemedText } from '@/components/ThemedText'; 12 | 13 | export function HelloWave() { 14 | const rotationAnimation = useSharedValue(0); 15 | 16 | useEffect(() => { 17 | rotationAnimation.value = withRepeat( 18 | withSequence(withTiming(25, { duration: 150 }), withTiming(0, { duration: 150 })), 19 | 4 // Run the animation 4 times 20 | ); 21 | }, []); 22 | 23 | const animatedStyle = useAnimatedStyle(() => ({ 24 | transform: [{ rotate: `${rotationAnimation.value}deg` }], 25 | })); 26 | 27 | return ( 28 | 29 | 👋 30 | 31 | ); 32 | } 33 | 34 | const styles = StyleSheet.create({ 35 | text: { 36 | fontSize: 28, 37 | lineHeight: 32, 38 | marginTop: -6, 39 | }, 40 | }); 41 | -------------------------------------------------------------------------------- /android/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 14 | 19 | -------------------------------------------------------------------------------- /app.json: -------------------------------------------------------------------------------- 1 | { 2 | "expo": { 3 | "name": "gemini-pro-chatbot", 4 | "slug": "gemini-pro-chatbot", 5 | "version": "1.0.2", 6 | "orientation": "portrait", 7 | "icon": "./assets/images/icon.png", 8 | "scheme": "myapp", 9 | "userInterfaceStyle": "automatic", 10 | "newArchEnabled": true, 11 | "ios": { 12 | "supportsTablet": true, 13 | "bundleIdentifier": "com.your.app", 14 | "config": { 15 | "usesNonExemptEncryption": false 16 | } 17 | }, 18 | "android": { 19 | "adaptiveIcon": { 20 | "foregroundImage": "./assets/images/adaptive-icon.png", 21 | "backgroundColor": "#ffffff" 22 | }, 23 | "package": "com.your.app" 24 | }, 25 | "web": { 26 | "bundler": "metro", 27 | "output": "static", 28 | "favicon": "./assets/images/favicon.png" 29 | }, 30 | "plugins": [ 31 | "expo-router", 32 | [ 33 | "expo-splash-screen", 34 | { 35 | "image": "./assets/images/splash-icon.png", 36 | "imageWidth": 200, 37 | "resizeMode": "contain", 38 | "backgroundColor": "#ffffff" 39 | } 40 | ] 41 | ], 42 | "experiments": { 43 | "typedRoutes": true 44 | }, 45 | "extra": { 46 | "router": { 47 | "origin": false 48 | }, 49 | "eas": { 50 | "projectId": "64946f53-ee73-4e8c-820f-42ab0553ecd5" 51 | }, 52 | "proxy": { 53 | "host": "127.0.0.1", 54 | "port": 7890 55 | } 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /components/ui/IconSymbol.tsx: -------------------------------------------------------------------------------- 1 | // This file is a fallback for using MaterialIcons on Android and web. 2 | 3 | import MaterialIcons from '@expo/vector-icons/MaterialIcons'; 4 | import { SymbolWeight } from 'expo-symbols'; 5 | import React from 'react'; 6 | import { OpaqueColorValue, StyleProp, ViewStyle } from 'react-native'; 7 | 8 | // Add your SFSymbol to MaterialIcons mappings here. 9 | const MAPPING = { 10 | // See MaterialIcons here: https://icons.expo.fyi 11 | // See SF Symbols in the SF Symbols app on Mac. 12 | 'house.fill': 'home', 13 | 'paperplane.fill': 'send', 14 | 'chevron.left.forwardslash.chevron.right': 'code', 15 | 'chevron.right': 'chevron-right', 16 | } as Partial< 17 | Record< 18 | import('expo-symbols').SymbolViewProps['name'], 19 | React.ComponentProps['name'] 20 | > 21 | >; 22 | 23 | export type IconSymbolName = keyof typeof MAPPING; 24 | 25 | /** 26 | * An icon component that uses native SFSymbols on iOS, and MaterialIcons on Android and web. This ensures a consistent look across platforms, and optimal resource usage. 27 | * 28 | * Icon `name`s are based on SFSymbols and require manual mapping to MaterialIcons. 29 | */ 30 | export function IconSymbol({ 31 | name, 32 | size = 24, 33 | color, 34 | style, 35 | }: { 36 | name: IconSymbolName; 37 | size?: number; 38 | color: string | OpaqueColorValue; 39 | style?: StyleProp; 40 | weight?: SymbolWeight; 41 | }) { 42 | return ; 43 | } 44 | -------------------------------------------------------------------------------- /components/Collapsible.tsx: -------------------------------------------------------------------------------- 1 | import { PropsWithChildren, useState } from 'react'; 2 | import { StyleSheet, TouchableOpacity } from 'react-native'; 3 | 4 | import { ThemedText } from '@/components/ThemedText'; 5 | import { ThemedView } from '@/components/ThemedView'; 6 | import { IconSymbol } from '@/components/ui/IconSymbol'; 7 | import { Colors } from '@/constants/Colors'; 8 | import { useColorScheme } from '@/hooks/useColorScheme'; 9 | 10 | export function Collapsible({ children, title }: PropsWithChildren & { title: string }) { 11 | const [isOpen, setIsOpen] = useState(false); 12 | const theme = useColorScheme() ?? 'light'; 13 | 14 | return ( 15 | 16 | setIsOpen((value) => !value)} 19 | activeOpacity={0.8}> 20 | 27 | 28 | {title} 29 | 30 | {isOpen && {children}} 31 | 32 | ); 33 | } 34 | 35 | const styles = StyleSheet.create({ 36 | heading: { 37 | flexDirection: 'row', 38 | alignItems: 'center', 39 | gap: 6, 40 | }, 41 | content: { 42 | marginTop: 6, 43 | marginLeft: 24, 44 | }, 45 | }); 46 | -------------------------------------------------------------------------------- /components/ThemedText.tsx: -------------------------------------------------------------------------------- 1 | import { Text, type TextProps, StyleSheet } from 'react-native'; 2 | 3 | import { useThemeColor } from '@/hooks/useThemeColor'; 4 | 5 | export type ThemedTextProps = TextProps & { 6 | lightColor?: string; 7 | darkColor?: string; 8 | type?: 'default' | 'title' | 'defaultSemiBold' | 'subtitle' | 'link'; 9 | }; 10 | 11 | export function ThemedText({ 12 | style, 13 | lightColor, 14 | darkColor, 15 | type = 'default', 16 | ...rest 17 | }: ThemedTextProps) { 18 | const color = useThemeColor({ light: lightColor, dark: darkColor }, 'text'); 19 | 20 | return ( 21 | 33 | ); 34 | } 35 | 36 | const styles = StyleSheet.create({ 37 | default: { 38 | fontSize: 16, 39 | lineHeight: 24, 40 | }, 41 | defaultSemiBold: { 42 | fontSize: 16, 43 | lineHeight: 24, 44 | fontWeight: '600', 45 | }, 46 | title: { 47 | fontSize: 32, 48 | fontWeight: 'bold', 49 | lineHeight: 32, 50 | }, 51 | subtitle: { 52 | fontSize: 20, 53 | fontWeight: 'bold', 54 | }, 55 | link: { 56 | lineHeight: 30, 57 | fontSize: 16, 58 | color: '#0a7ea4', 59 | }, 60 | }); 61 | -------------------------------------------------------------------------------- /app/_layout.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { Stack } from 'expo-router'; 3 | import { StatusBar } from 'expo-status-bar'; 4 | import { SafeAreaProvider } from 'react-native-safe-area-context'; 5 | import { ThemeProvider, useTheme } from '@/contexts/ThemeContext'; 6 | 7 | function RootLayoutNav() { 8 | const { isDarkMode } = useTheme(); 9 | 10 | return ( 11 | 12 | 13 | 27 | 31 | 38 | 45 | 46 | 47 | ); 48 | } 49 | 50 | export default function RootLayout() { 51 | return ( 52 | 53 | 54 | 55 | ); 56 | } 57 | -------------------------------------------------------------------------------- /android/settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | includeBuild(new File(["node", "--print", "require.resolve('@react-native/gradle-plugin/package.json', { paths: [require.resolve('react-native/package.json')] })"].execute(null, rootDir).text.trim()).getParentFile().toString()) 3 | } 4 | plugins { id("com.facebook.react.settings") } 5 | 6 | extensions.configure(com.facebook.react.ReactSettingsExtension) { ex -> 7 | if (System.getenv('EXPO_USE_COMMUNITY_AUTOLINKING') == '1') { 8 | ex.autolinkLibrariesFromCommand() 9 | } else { 10 | def command = [ 11 | 'node', 12 | '--no-warnings', 13 | '--eval', 14 | 'require(require.resolve(\'expo-modules-autolinking\', { paths: [require.resolve(\'expo/package.json\')] }))(process.argv.slice(1))', 15 | 'react-native-config', 16 | '--json', 17 | '--platform', 18 | 'android' 19 | ].toList() 20 | ex.autolinkLibrariesFromCommand(command) 21 | } 22 | } 23 | 24 | rootProject.name = 'gemini-pro-chatbot' 25 | 26 | dependencyResolutionManagement { 27 | versionCatalogs { 28 | reactAndroidLibs { 29 | from(files(new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim(), "../gradle/libs.versions.toml"))) 30 | } 31 | } 32 | } 33 | 34 | apply from: new File(["node", "--print", "require.resolve('expo/package.json')"].execute(null, rootDir).text.trim(), "../scripts/autolinking.gradle"); 35 | useExpoModules() 36 | 37 | include ':app' 38 | includeBuild(new File(["node", "--print", "require.resolve('@react-native/gradle-plugin/package.json', { paths: [require.resolve('react-native/package.json')] })"].execute(null, rootDir).text.trim()).getParentFile()) 39 | -------------------------------------------------------------------------------- /android/build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | ext { 5 | buildToolsVersion = findProperty('android.buildToolsVersion') ?: '35.0.0' 6 | minSdkVersion = Integer.parseInt(findProperty('android.minSdkVersion') ?: '24') 7 | compileSdkVersion = Integer.parseInt(findProperty('android.compileSdkVersion') ?: '35') 8 | targetSdkVersion = Integer.parseInt(findProperty('android.targetSdkVersion') ?: '34') 9 | kotlinVersion = findProperty('android.kotlinVersion') ?: '1.9.25' 10 | 11 | ndkVersion = "26.1.10909125" 12 | } 13 | repositories { 14 | google() 15 | mavenCentral() 16 | } 17 | dependencies { 18 | classpath('com.android.tools.build:gradle') 19 | classpath('com.facebook.react:react-native-gradle-plugin') 20 | classpath('org.jetbrains.kotlin:kotlin-gradle-plugin') 21 | } 22 | } 23 | 24 | apply plugin: "com.facebook.react.rootproject" 25 | 26 | allprojects { 27 | repositories { 28 | maven { 29 | // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm 30 | url(new File(['node', '--print', "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim(), '../android')) 31 | } 32 | maven { 33 | // Android JSC is installed from npm 34 | url(new File(['node', '--print', "require.resolve('jsc-android/package.json', { paths: [require.resolve('react-native/package.json')] })"].execute(null, rootDir).text.trim(), '../dist')) 35 | } 36 | 37 | google() 38 | mavenCentral() 39 | maven { url 'https://www.jitpack.io' } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /components/CodeBlock.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { View, StyleSheet, Text, ScrollView, Platform } from 'react-native'; 3 | import SyntaxHighlighter from 'react-native-syntax-highlighter'; 4 | import { vs2015 } from 'react-syntax-highlighter/dist/cjs/styles/hljs'; 5 | 6 | interface CodeBlockProps { 7 | code: string; 8 | language?: string; 9 | } 10 | 11 | export const CodeBlock: React.FC = ({ code, language = 'javascript' }) => { 12 | return ( 13 | 14 | 15 | {language} 16 | 17 | 22 | 28 | {code} 29 | 30 | 31 | 32 | ); 33 | }; 34 | 35 | const styles = StyleSheet.create({ 36 | container: { 37 | marginVertical: 8, 38 | borderRadius: 12, 39 | overflow: 'hidden', 40 | backgroundColor: '#1E1E1E', 41 | }, 42 | header: { 43 | padding: 8, 44 | borderBottomWidth: StyleSheet.hairlineWidth, 45 | borderBottomColor: '#333333', 46 | }, 47 | language: { 48 | color: '#999999', 49 | fontSize: 12, 50 | textTransform: 'uppercase', 51 | }, 52 | scrollView: { 53 | maxHeight: 300, 54 | }, 55 | codeBlock: { 56 | padding: 12, 57 | fontSize: 14, 58 | backgroundColor: '#1E1E1E', 59 | fontFamily: Platform.select({ 60 | ios: 'Menlo', 61 | android: 'monospace', 62 | }), 63 | }, 64 | }); -------------------------------------------------------------------------------- /android/app/src/main/res/drawable/rn_edit_text_material.xml: -------------------------------------------------------------------------------- 1 | 2 | 16 | 22 | 23 | 24 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /android/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /android/app/src/main/java/com/your/app/MainApplication.kt: -------------------------------------------------------------------------------- 1 | package com.your.app 2 | 3 | import android.app.Application 4 | import android.content.res.Configuration 5 | 6 | import com.facebook.react.PackageList 7 | import com.facebook.react.ReactApplication 8 | import com.facebook.react.ReactNativeHost 9 | import com.facebook.react.ReactPackage 10 | import com.facebook.react.ReactHost 11 | import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load 12 | import com.facebook.react.defaults.DefaultReactNativeHost 13 | import com.facebook.react.soloader.OpenSourceMergedSoMapping 14 | import com.facebook.soloader.SoLoader 15 | 16 | import expo.modules.ApplicationLifecycleDispatcher 17 | import expo.modules.ReactNativeHostWrapper 18 | 19 | class MainApplication : Application(), ReactApplication { 20 | 21 | override val reactNativeHost: ReactNativeHost = ReactNativeHostWrapper( 22 | this, 23 | object : DefaultReactNativeHost(this) { 24 | override fun getPackages(): List { 25 | val packages = PackageList(this).packages 26 | // Packages that cannot be autolinked yet can be added manually here, for example: 27 | // packages.add(new MyReactNativePackage()); 28 | return packages 29 | } 30 | 31 | override fun getJSMainModuleName(): String = ".expo/.virtual-metro-entry" 32 | 33 | override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG 34 | 35 | override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED 36 | override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED 37 | } 38 | ) 39 | 40 | override val reactHost: ReactHost 41 | get() = ReactNativeHostWrapper.createReactHost(applicationContext, reactNativeHost) 42 | 43 | override fun onCreate() { 44 | super.onCreate() 45 | SoLoader.init(this, OpenSourceMergedSoMapping) 46 | if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) { 47 | // If you opted-in for the New Architecture, we load the native entry point for this app. 48 | load() 49 | } 50 | ApplicationLifecycleDispatcher.onApplicationCreate(this) 51 | } 52 | 53 | override fun onConfigurationChanged(newConfig: Configuration) { 54 | super.onConfigurationChanged(newConfig) 55 | ApplicationLifecycleDispatcher.onConfigurationChanged(this, newConfig) 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /contexts/ThemeContext.tsx: -------------------------------------------------------------------------------- 1 | import React, { createContext, useContext, useState, useEffect } from 'react'; 2 | import AsyncStorage from '@react-native-async-storage/async-storage'; 3 | import { useColorScheme } from 'react-native'; 4 | 5 | const THEME_STORAGE_KEY = '@gemini_theme'; 6 | 7 | type ThemeContextType = { 8 | isDarkMode: boolean; 9 | toggleTheme: () => void; 10 | setIsDarkMode: (value: boolean) => void; 11 | }; 12 | 13 | const ThemeContext = createContext(undefined); 14 | 15 | export function ThemeProvider({ children }: { children: React.ReactNode }) { 16 | const systemColorScheme = useColorScheme(); 17 | const [isDarkMode, setIsDarkMode] = useState(systemColorScheme === 'dark'); 18 | const [isLoaded, setIsLoaded] = useState(false); 19 | 20 | // 加载保存的主题设置 21 | useEffect(() => { 22 | loadTheme(); 23 | }, []); 24 | 25 | // 监听系统主题变化 26 | useEffect(() => { 27 | if (!isLoaded) return; 28 | saveTheme(systemColorScheme === 'dark'); 29 | }, [systemColorScheme, isLoaded]); 30 | 31 | const loadTheme = async () => { 32 | try { 33 | const savedTheme = await AsyncStorage.getItem(THEME_STORAGE_KEY); 34 | if (savedTheme !== null) { 35 | setIsDarkMode(savedTheme === 'dark'); 36 | } else { 37 | // 如果没有保存的主题设置,使用系统主题 38 | setIsDarkMode(systemColorScheme === 'dark'); 39 | } 40 | setIsLoaded(true); 41 | } catch (error) { 42 | console.error('Error loading theme:', error); 43 | // 发生错误时使用系统主题 44 | setIsDarkMode(systemColorScheme === 'dark'); 45 | setIsLoaded(true); 46 | } 47 | }; 48 | 49 | const saveTheme = async (isDark: boolean) => { 50 | try { 51 | await AsyncStorage.setItem(THEME_STORAGE_KEY, isDark ? 'dark' : 'light'); 52 | setIsDarkMode(isDark); 53 | } catch (error) { 54 | console.error('Error saving theme:', error); 55 | } 56 | }; 57 | 58 | const toggleTheme = () => { 59 | saveTheme(!isDarkMode); 60 | }; 61 | 62 | return ( 63 | 64 | {children} 65 | 66 | ); 67 | } 68 | 69 | export function useTheme() { 70 | const context = useContext(ThemeContext); 71 | if (context === undefined) { 72 | throw new Error('useTheme must be used within a ThemeProvider'); 73 | } 74 | return context; 75 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "gemini-pro-chatbot", 3 | "main": "expo-router/entry", 4 | "version": "1.0.0", 5 | "scripts": { 6 | "start": "expo start", 7 | "reset-project": "node ./scripts/reset-project.js", 8 | "android": "expo run:android", 9 | "ios": "expo run:ios", 10 | "web": "expo start --web", 11 | "test": "jest --watchAll", 12 | "lint": "expo lint", 13 | "prebuildAndroidLocal": "npx expo prebuild --platform android", 14 | "buildAndroidLocal": "eas build --platform android --local" 15 | }, 16 | "jest": { 17 | "preset": "jest-expo" 18 | }, 19 | "dependencies": { 20 | "@expo/vector-icons": "^14.0.2", 21 | "@react-native-async-storage/async-storage": "^2.1.0", 22 | "@react-navigation/bottom-tabs": "^7.2.0", 23 | "@react-navigation/native": "^7.0.14", 24 | "axios": "^1.7.9", 25 | "crypto": "^1.0.1", 26 | "expo": "~52.0.31", 27 | "expo-blur": "~14.0.3", 28 | "expo-clipboard": "~7.0.1", 29 | "expo-constants": "~17.0.5", 30 | "expo-crypto": "~14.0.2", 31 | "expo-font": "~13.0.3", 32 | "expo-haptics": "~14.0.1", 33 | "expo-linking": "~7.0.5", 34 | "expo-router": "~4.0.17", 35 | "expo-splash-screen": "~0.29.21", 36 | "expo-status-bar": "~2.0.1", 37 | "expo-symbols": "~0.2.2", 38 | "expo-system-ui": "~4.0.8", 39 | "expo-web-browser": "~14.0.2", 40 | "nanoid": "^3.3.4", 41 | "openai": "^4.83.0", 42 | "react": "18.3.1", 43 | "react-dom": "18.3.1", 44 | "react-native": "0.76.7", 45 | "react-native-fetch-api": "^3.0.0", 46 | "react-native-gesture-handler": "~2.20.2", 47 | "react-native-markdown-display": "^7.0.2", 48 | "react-native-reanimated": "~3.16.1", 49 | "react-native-safe-area-context": "4.12.0", 50 | "react-native-screens": "~4.4.0", 51 | "react-native-syntax-highlighter": "^2.1.0", 52 | "react-native-web": "~0.19.13", 53 | "react-native-webview": "13.12.5", 54 | "react-syntax-highlighter": "^15.6.1", 55 | "expo-image-picker": "~16.0.5", 56 | "expo-file-system": "~18.0.10" 57 | }, 58 | "devDependencies": { 59 | "@babel/core": "^7.25.2", 60 | "@types/jest": "^29.5.12", 61 | "@types/react": "~18.3.12", 62 | "@types/react-test-renderer": "^18.3.0", 63 | "jest": "^29.2.1", 64 | "jest-expo": "~52.0.3", 65 | "react-test-renderer": "18.3.1", 66 | "typescript": "^5.3.3" 67 | }, 68 | "private": true 69 | } 70 | -------------------------------------------------------------------------------- /components/ParallaxScrollView.tsx: -------------------------------------------------------------------------------- 1 | import type { PropsWithChildren, ReactElement } from 'react'; 2 | import { StyleSheet } from 'react-native'; 3 | import Animated, { 4 | interpolate, 5 | useAnimatedRef, 6 | useAnimatedStyle, 7 | useScrollViewOffset, 8 | } from 'react-native-reanimated'; 9 | 10 | import { ThemedView } from '@/components/ThemedView'; 11 | import { useBottomTabOverflow } from '@/components/ui/TabBarBackground'; 12 | import { useColorScheme } from '@/hooks/useColorScheme'; 13 | 14 | const HEADER_HEIGHT = 250; 15 | 16 | type Props = PropsWithChildren<{ 17 | headerImage: ReactElement; 18 | headerBackgroundColor: { dark: string; light: string }; 19 | }>; 20 | 21 | export default function ParallaxScrollView({ 22 | children, 23 | headerImage, 24 | headerBackgroundColor, 25 | }: Props) { 26 | const colorScheme = useColorScheme() ?? 'light'; 27 | const scrollRef = useAnimatedRef(); 28 | const scrollOffset = useScrollViewOffset(scrollRef); 29 | const bottom = useBottomTabOverflow(); 30 | const headerAnimatedStyle = useAnimatedStyle(() => { 31 | return { 32 | transform: [ 33 | { 34 | translateY: interpolate( 35 | scrollOffset.value, 36 | [-HEADER_HEIGHT, 0, HEADER_HEIGHT], 37 | [-HEADER_HEIGHT / 2, 0, HEADER_HEIGHT * 0.75] 38 | ), 39 | }, 40 | { 41 | scale: interpolate(scrollOffset.value, [-HEADER_HEIGHT, 0, HEADER_HEIGHT], [2, 1, 1]), 42 | }, 43 | ], 44 | }; 45 | }); 46 | 47 | return ( 48 | 49 | 54 | 60 | {headerImage} 61 | 62 | {children} 63 | 64 | 65 | ); 66 | } 67 | 68 | const styles = StyleSheet.create({ 69 | container: { 70 | flex: 1, 71 | }, 72 | header: { 73 | height: HEADER_HEIGHT, 74 | overflow: 'hidden', 75 | }, 76 | content: { 77 | flex: 1, 78 | padding: 32, 79 | gap: 16, 80 | overflow: 'hidden', 81 | }, 82 | }); 83 | -------------------------------------------------------------------------------- /android/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx512m -XX:MaxMetaspaceSize=256m 13 | org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true 19 | 20 | # AndroidX package structure to make it clearer which packages are bundled with the 21 | # Android operating system, and which are packaged with your app's APK 22 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 23 | android.useAndroidX=true 24 | 25 | # Enable AAPT2 PNG crunching 26 | android.enablePngCrunchInReleaseBuilds=true 27 | 28 | # Use this property to specify which architecture you want to build. 29 | # You can also override it from the CLI using 30 | # ./gradlew -PreactNativeArchitectures=x86_64 31 | reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64 32 | 33 | # Use this property to enable support to the new architecture. 34 | # This will allow you to use TurboModules and the Fabric render in 35 | # your application. You should enable this flag either if you want 36 | # to write custom TurboModules/Fabric components OR use libraries that 37 | # are providing them. 38 | newArchEnabled=true 39 | 40 | # Use this property to enable or disable the Hermes JS engine. 41 | # If set to false, you will be using JSC instead. 42 | hermesEnabled=true 43 | 44 | # Enable GIF support in React Native images (~200 B increase) 45 | expo.gif.enabled=true 46 | # Enable webp support in React Native images (~85 KB increase) 47 | expo.webp.enabled=true 48 | # Enable animated webp support (~3.4 MB increase) 49 | # Disabled by default because iOS doesn't support animated webp 50 | expo.webp.animated=false 51 | 52 | # Enable network inspector 53 | EX_DEV_CLIENT_NETWORK_INSPECTOR=true 54 | 55 | # Use legacy packaging to compress native libraries in the resulting APK. 56 | expo.useLegacyPackaging=false 57 | -------------------------------------------------------------------------------- /app/(tabs)/_layout.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { View } from 'react-native'; 3 | import { Tabs } from 'expo-router'; 4 | import { MaterialIcons } from '@expo/vector-icons'; 5 | import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context'; 6 | import { useTheme } from '@/contexts/ThemeContext'; 7 | 8 | export default function TabLayout() { 9 | const { isDarkMode } = useTheme(); 10 | const insets = useSafeAreaInsets(); 11 | 12 | return ( 13 | 36 | ( 42 | 43 | ), 44 | }} 45 | /> 46 | ( 52 | 53 | ), 54 | }} 55 | /> 56 | ( 62 | 63 | ), 64 | }} 65 | /> 66 | ( 72 | 73 | ), 74 | }} 75 | /> 76 | 77 | ); 78 | } 79 | -------------------------------------------------------------------------------- /constants/Config.ts: -------------------------------------------------------------------------------- 1 | export const GEMINI_API_KEY = process.env.EXPO_PUBLIC_GEMINI_API_KEY || ''; 2 | export const GEMINI_BASE_URL = 'https://generativelanguage.googleapis.com/v1beta/openai'; 3 | 4 | export const DEFAULT_SYSTEM_PROMPT = `You are a helpful AI assistant powered by Google's Gemini Pro model. You can help with various tasks including answering questions, writing code, and analyzing data.`; 5 | 6 | export interface Message { 7 | id: string; 8 | role: 'system' | 'user' | 'assistant'; 9 | content: string; 10 | timestamp: number; 11 | isEdited?: boolean; 12 | image?: string | null; 13 | } 14 | 15 | export interface Chat { 16 | id: string; 17 | title: string; 18 | messages: Message[]; 19 | systemPrompt: string; 20 | createdAt: number; 21 | updatedAt: number; 22 | agentId: string; 23 | } 24 | 25 | export interface Agent { 26 | id: string; 27 | name: string; 28 | description: string; 29 | systemPrompt: string; 30 | icon: string; 31 | color: string; 32 | isDefault?: boolean; 33 | createdAt: number; 34 | updatedAt: number; 35 | } 36 | 37 | export const DEFAULT_AGENTS: Agent[] = [ 38 | { 39 | id: 'default-chat', 40 | name: 'Chat Assistant', 41 | description: 'A friendly AI assistant for general conversation and help', 42 | systemPrompt: 'You are a helpful AI assistant powered by Google\'s Gemini Pro model. You can help with various tasks including answering questions, writing code, and analyzing data.', 43 | icon: 'chat-bubble-outline', 44 | color: '#6B4EFF', 45 | isDefault: true, 46 | createdAt: Date.now(), 47 | updatedAt: Date.now(), 48 | }, 49 | { 50 | id: 'default-writer', 51 | name: 'Content Writer', 52 | description: 'Specialized in writing and editing various types of content', 53 | systemPrompt: 'You are a professional content writer. You excel at creating engaging, well-structured content including articles, blog posts, social media content, and more. Focus on clarity, engagement, and the target audience\'s needs.', 54 | icon: 'edit', 55 | color: '#00C853', 56 | isDefault: true, 57 | createdAt: Date.now(), 58 | updatedAt: Date.now(), 59 | }, 60 | { 61 | id: 'default-coder', 62 | name: 'Code Expert', 63 | description: 'Expert in programming and technical problem-solving', 64 | systemPrompt: 'You are an expert programmer. You excel at writing clean, efficient code, debugging problems, and explaining technical concepts clearly. Provide code examples when helpful and focus on best practices.', 65 | icon: 'code', 66 | color: '#FF6B4E', 67 | isDefault: true, 68 | createdAt: Date.now(), 69 | updatedAt: Date.now(), 70 | }, 71 | ]; -------------------------------------------------------------------------------- /android/app/src/main/java/com/your/app/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.your.app 2 | import expo.modules.splashscreen.SplashScreenManager 3 | 4 | import android.os.Build 5 | import android.os.Bundle 6 | 7 | import com.facebook.react.ReactActivity 8 | import com.facebook.react.ReactActivityDelegate 9 | import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled 10 | import com.facebook.react.defaults.DefaultReactActivityDelegate 11 | 12 | import expo.modules.ReactActivityDelegateWrapper 13 | 14 | class MainActivity : ReactActivity() { 15 | override fun onCreate(savedInstanceState: Bundle?) { 16 | // Set the theme to AppTheme BEFORE onCreate to support 17 | // coloring the background, status bar, and navigation bar. 18 | // This is required for expo-splash-screen. 19 | // setTheme(R.style.AppTheme); 20 | // @generated begin expo-splashscreen - expo prebuild (DO NOT MODIFY) sync-f3ff59a738c56c9a6119210cb55f0b613eb8b6af 21 | SplashScreenManager.registerOnActivity(this) 22 | // @generated end expo-splashscreen 23 | super.onCreate(null) 24 | } 25 | 26 | /** 27 | * Returns the name of the main component registered from JavaScript. This is used to schedule 28 | * rendering of the component. 29 | */ 30 | override fun getMainComponentName(): String = "main" 31 | 32 | /** 33 | * Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate] 34 | * which allows you to enable New Architecture with a single boolean flags [fabricEnabled] 35 | */ 36 | override fun createReactActivityDelegate(): ReactActivityDelegate { 37 | return ReactActivityDelegateWrapper( 38 | this, 39 | BuildConfig.IS_NEW_ARCHITECTURE_ENABLED, 40 | object : DefaultReactActivityDelegate( 41 | this, 42 | mainComponentName, 43 | fabricEnabled 44 | ){}) 45 | } 46 | 47 | /** 48 | * Align the back button behavior with Android S 49 | * where moving root activities to background instead of finishing activities. 50 | * @see onBackPressed 51 | */ 52 | override fun invokeDefaultOnBackPressed() { 53 | if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) { 54 | if (!moveTaskToBack(false)) { 55 | // For non-root activities, use the default implementation to finish them. 56 | super.invokeDefaultOnBackPressed() 57 | } 58 | return 59 | } 60 | 61 | // Use the default back button implementation on Android S 62 | // because it's doing more than [Activity.moveTaskToBack] in fact. 63 | super.invokeDefaultOnBackPressed() 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /requirement.md: -------------------------------------------------------------------------------- 1 | # Google Gemini Chatbot 2 | 3 | ## 需求描述 4 | 5 | 用户已经初始化了 expo 移动端开发框架,并且已经安装了 openai 和 react-native-reanimated 等依赖。 6 | 7 | 用户想实现一个可以和 gemini pro 2.0 对话的 chatbot,并且可以支持流式响应,并且可以支持代码语法高亮,并且可以支持对话历史管理,自定义系统提示词。 8 | 9 | 添加消息持久化存储 10 | 11 | 实现流式响应(streaming response) 12 | 13 | 添加代码语法高亮 14 | 15 | 支持对话历史管理 16 | 17 | 实现消息编辑功能 18 | 19 | 4 个 tab 页面 20 | 21 | 1. 对话 22 | 2. agent 23 | 3. 发现 24 | 4. 设置 25 | 26 | 对话页就是和 gemini 创建的只能提对话的页面 27 | 28 | agent 页就是可以创建多个 agent 的页面,每个 agent 可以有不同的系统提示词,并且可以有不同的对话历史 29 | 30 | 发现页就是可以利用 gemini 的 api 来生成一些有趣的内容,比如图片,视频,音频,文字等,并且可以分享给其他用户,做自媒体等等。 31 | 32 | 设置页就是可以设置一些个人信息,并且可以设置apikey,主题等。 33 | 34 | 35 | 36 | ## 一些补充文档 37 | 38 | 根据 Google 官方文档,可以谁用兼容 openai 的方式访问 gemini 39 | 40 | ### 流式响应 41 | 42 | ```js 43 | import OpenAI from "openai"; 44 | 45 | const openai = new OpenAI({ 46 | apiKey: "GEMINI_API_KEY", 47 | baseURL: "https://generativelanguage.googleapis.com/v1beta/openai/" 48 | }); 49 | 50 | async function main() { 51 | const completion = await openai.chat.completions.create({ 52 | model: "gemini-1.5-flash", 53 | messages: [ 54 | {"role": "system", "content": "You are a helpful assistant."}, 55 | {"role": "user", "content": "Hello!"} 56 | ], 57 | stream: true, 58 | }); 59 | 60 | for await (const chunk of completion) { 61 | console.log(chunk.choices[0].delta.content); 62 | } 63 | } 64 | 65 | main(); 66 | ``` 67 | 68 | ### 图片理解 69 | 70 | ```js 71 | import OpenAI from "openai"; 72 | import fs from 'fs/promises'; 73 | 74 | const openai = new OpenAI({ 75 | apiKey: "GEMINI_API_KEY", 76 | baseURL: "https://generativelanguage.googleapis.com/v1beta/openai/" 77 | }); 78 | 79 | async function encodeImage(imagePath) { 80 | try { 81 | const imageBuffer = await fs.readFile(imagePath); 82 | return imageBuffer.toString('base64'); 83 | } catch (error) { 84 | console.error("Error encoding image:", error); 85 | return null; 86 | } 87 | } 88 | 89 | async function main() { 90 | const imagePath = "Path/to/agi/image.jpeg"; 91 | const base64Image = await encodeImage(imagePath); 92 | 93 | const messages = [ 94 | { 95 | "role": "user", 96 | "content": [ 97 | { 98 | "type": "text", 99 | "text": "What is in this image?", 100 | }, 101 | { 102 | "type": "image_url", 103 | "image_url": { 104 | "url": `data:image/jpeg;base64,${base64Image}` 105 | }, 106 | }, 107 | ], 108 | } 109 | ]; 110 | 111 | try { 112 | const response = await openai.chat.completions.create({ 113 | model: "gemini-2.0-pro-exp-02-05", 114 | messages: messages, 115 | }); 116 | 117 | console.log(response.choices[0]); 118 | } catch (error) { 119 | console.error("Error calling Gemini API:", error); 120 | } 121 | } 122 | 123 | main(); 124 | ``` 125 | 126 | 127 | 128 | 129 | 130 | -------------------------------------------------------------------------------- /android/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 74 | 75 | 76 | @rem Execute Gradle 77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 78 | 79 | :end 80 | @rem End local scope for the variables with windows NT shell 81 | if %ERRORLEVEL% equ 0 goto mainEnd 82 | 83 | :fail 84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 85 | rem the _cmd.exe /c_ return code! 86 | set EXIT_CODE=%ERRORLEVEL% 87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 89 | exit /b %EXIT_CODE% 90 | 91 | :mainEnd 92 | if "%OS%"=="Windows_NT" endlocal 93 | 94 | :omega 95 | -------------------------------------------------------------------------------- /scripts/reset-project.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /** 4 | * This script is used to reset the project to a blank state. 5 | * It deletes or moves the /app, /components, /hooks, /scripts, and /constants directories to /app-example based on user input and creates a new /app directory with an index.tsx and _layout.tsx file. 6 | * You can remove the `reset-project` script from package.json and safely delete this file after running it. 7 | */ 8 | 9 | const fs = require("fs"); 10 | const path = require("path"); 11 | const readline = require("readline"); 12 | 13 | const root = process.cwd(); 14 | const oldDirs = ["app", "components", "hooks", "constants", "scripts"]; 15 | const exampleDir = "app-example"; 16 | const newAppDir = "app"; 17 | const exampleDirPath = path.join(root, exampleDir); 18 | 19 | const indexContent = `import { Text, View } from "react-native"; 20 | 21 | export default function Index() { 22 | return ( 23 | 30 | Edit app/index.tsx to edit this screen. 31 | 32 | ); 33 | } 34 | `; 35 | 36 | const layoutContent = `import { Stack } from "expo-router"; 37 | 38 | export default function RootLayout() { 39 | return ; 40 | } 41 | `; 42 | 43 | const rl = readline.createInterface({ 44 | input: process.stdin, 45 | output: process.stdout, 46 | }); 47 | 48 | const moveDirectories = async (userInput) => { 49 | try { 50 | if (userInput === "y") { 51 | // Create the app-example directory 52 | await fs.promises.mkdir(exampleDirPath, { recursive: true }); 53 | console.log(`📁 /${exampleDir} directory created.`); 54 | } 55 | 56 | // Move old directories to new app-example directory or delete them 57 | for (const dir of oldDirs) { 58 | const oldDirPath = path.join(root, dir); 59 | if (fs.existsSync(oldDirPath)) { 60 | if (userInput === "y") { 61 | const newDirPath = path.join(root, exampleDir, dir); 62 | await fs.promises.rename(oldDirPath, newDirPath); 63 | console.log(`➡️ /${dir} moved to /${exampleDir}/${dir}.`); 64 | } else { 65 | await fs.promises.rm(oldDirPath, { recursive: true, force: true }); 66 | console.log(`❌ /${dir} deleted.`); 67 | } 68 | } else { 69 | console.log(`➡️ /${dir} does not exist, skipping.`); 70 | } 71 | } 72 | 73 | // Create new /app directory 74 | const newAppDirPath = path.join(root, newAppDir); 75 | await fs.promises.mkdir(newAppDirPath, { recursive: true }); 76 | console.log("\n📁 New /app directory created."); 77 | 78 | // Create index.tsx 79 | const indexPath = path.join(newAppDirPath, "index.tsx"); 80 | await fs.promises.writeFile(indexPath, indexContent); 81 | console.log("📄 app/index.tsx created."); 82 | 83 | // Create _layout.tsx 84 | const layoutPath = path.join(newAppDirPath, "_layout.tsx"); 85 | await fs.promises.writeFile(layoutPath, layoutContent); 86 | console.log("📄 app/_layout.tsx created."); 87 | 88 | console.log("\n✅ Project reset complete. Next steps:"); 89 | console.log( 90 | `1. Run \`npx expo start\` to start a development server.\n2. Edit app/index.tsx to edit the main screen.${ 91 | userInput === "y" 92 | ? `\n3. Delete the /${exampleDir} directory when you're done referencing it.` 93 | : "" 94 | }` 95 | ); 96 | } catch (error) { 97 | console.error(`❌ Error during script execution: ${error.message}`); 98 | } 99 | }; 100 | 101 | rl.question( 102 | "Do you want to move existing files to /app-example instead of deleting them? (Y/n): ", 103 | (answer) => { 104 | const userInput = answer.trim().toLowerCase() || "y"; 105 | if (userInput === "y" || userInput === "n") { 106 | moveDirectories(userInput).finally(() => rl.close()); 107 | } else { 108 | console.log("❌ Invalid input. Please enter 'Y' or 'N'."); 109 | rl.close(); 110 | } 111 | } 112 | ); 113 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Gemini Pro Chatbot 2 | 3 | A beautiful and feature-rich mobile chat application powered by Google's Gemini Pro AI model. Built with Expo and React Native. 4 | 5 | ## Features 6 | 7 | - 🤖 Powered by Google's Gemini Pro AI model 8 | - 💬 Real-time streaming responses 9 | - 🎨 Beautiful dark theme UI 10 | - 📝 Code syntax highlighting 11 | - 💾 Persistent message storage 12 | - ✏️ Message editing support 13 | - ⚙️ Customizable system prompts 14 | - 🖼️ Image understanding support 15 | - 🎭 Multiple AI agents with different personalities 16 | - 🔄 Message regeneration 17 | - 📱 Cross-platform (iOS & Android) 18 | 19 | ## Screenshots 20 | 21 | ### Chat Interface 22 | Chat Interface 23 | 24 | - Real-time streaming responses 25 | - Code syntax highlighting 26 | - Support for image input 27 | - Dark mode support 28 | 29 | ### Agents Management 30 | Agents Management 31 | 32 | - Create custom AI agents 33 | - Different personalities and purposes 34 | - Customizable system prompts 35 | - Easy agent switching 36 | 37 | ### Content Discovery 38 | Discover 39 | 40 | - Generate creative content 41 | - Share interesting responses 42 | - Multiple content types 43 | - Community interaction 44 | 45 | ### Settings 46 | Settings 47 | 48 | - Dark mode toggle 49 | - API key management 50 | - System prompt customization 51 | - Stream response settings 52 | 53 | ### Dark Mode 54 | Dark Mode 55 | 56 | 57 | 58 | ## Getting Started 59 | 60 | 1. Install dependencies 61 | ```bash 62 | npm install 63 | ``` 64 | 65 | 2. Configure your API key 66 | - Get your Gemini Pro API key from [Google AI Studio](https://makersuite.google.com/app/apikey) 67 | - Add your API key in the app's settings screen 68 | 69 | 3. Start the app 70 | ```bash 71 | npx expo start 72 | ``` 73 | 74 | 4. Run on your device: 75 | - iOS: Press 'i' to open in iOS Simulator 76 | - Android: Press 'a' to open in Android Emulator 77 | - Scan QR code with Expo Go app on your physical device 78 | 79 | ## Usage 80 | 81 | ### Chat Interface 82 | - Type your message in the input box 83 | - Click the image icon to add images for analysis 84 | - Real-time streaming responses 85 | - Code blocks are automatically highlighted 86 | - Edit or regenerate messages as needed 87 | 88 | ### Agents 89 | - Create custom agents for different purposes 90 | - Each agent has its own personality and system prompt 91 | - Switch between agents for different conversation styles 92 | - Default agents included for common use cases 93 | 94 | ### Discover 95 | - Generate creative content like stories and poems 96 | - Share interesting AI responses 97 | - Like and collect favorite content 98 | - Explore community-shared content 99 | 100 | ### Settings 101 | - Customize your experience 102 | - Toggle dark mode 103 | - Manage your API key 104 | - Configure system-wide preferences 105 | 106 | ## Tech Stack 107 | 108 | - Expo / React Native 109 | - Google Gemini Pro API 110 | - React Navigation 111 | - AsyncStorage for persistence 112 | - Syntax highlighting for code blocks 113 | - Expo Image Picker 114 | - React Native Markdown 115 | 116 | ## Contributing 117 | 118 | Feel free to open issues and pull requests for any improvements you'd like to add! 119 | 120 | ## Follow My WeChat Official Account 121 | 122 | Stay updated with the latest AI development tips and tools: 123 | 124 |
125 | WeChat Official Account QR Code 126 |

WeChat Official Account: LaoMa XiaoZhang

127 |

Scan the QR code to follow and get the latest updates on:

128 |
    129 |
  • 🤖 AI Programming Tips & Tricks
  • 130 |
  • 💻 Full-Stack Development Insights
  • 131 |
  • 🛠️ Productivity Tools and Workflows
  • 132 |
  • 🚀 Latest Tech Trends and Reviews
  • 133 |
134 |
135 | 136 | ## License 137 | 138 | MIT License - feel free to use this code for your own projects! 139 | -------------------------------------------------------------------------------- /utils/storage.ts: -------------------------------------------------------------------------------- 1 | import AsyncStorage from '@react-native-async-storage/async-storage'; 2 | import { Chat, Message, Agent, DEFAULT_AGENTS } from '../constants/Config'; 3 | 4 | const CHATS_STORAGE_KEY = '@gemini_chats'; 5 | const AGENTS_STORAGE_KEY = '@gemini_agents'; 6 | 7 | // Agent 相关操作 8 | export const initializeAgents = async () => { 9 | try { 10 | const existingAgents = await loadAgents(); 11 | if (existingAgents.length === 0) { 12 | await AsyncStorage.setItem(AGENTS_STORAGE_KEY, JSON.stringify(DEFAULT_AGENTS)); 13 | return DEFAULT_AGENTS; 14 | } 15 | return existingAgents; 16 | } catch (error) { 17 | console.error('Error initializing agents:', error); 18 | return DEFAULT_AGENTS; 19 | } 20 | }; 21 | 22 | export const loadAgents = async (): Promise => { 23 | try { 24 | const agentsJson = await AsyncStorage.getItem(AGENTS_STORAGE_KEY); 25 | return agentsJson ? JSON.parse(agentsJson) : []; 26 | } catch (error) { 27 | console.error('Error loading agents:', error); 28 | return []; 29 | } 30 | }; 31 | 32 | export const saveAgent = async (agent: Agent) => { 33 | try { 34 | const existingAgents = await loadAgents(); 35 | const agentIndex = existingAgents.findIndex(a => a.id === agent.id); 36 | 37 | if (agentIndex !== -1) { 38 | existingAgents[agentIndex] = agent; 39 | } else { 40 | existingAgents.push(agent); 41 | } 42 | 43 | await AsyncStorage.setItem(AGENTS_STORAGE_KEY, JSON.stringify(existingAgents)); 44 | } catch (error) { 45 | console.error('Error saving agent:', error); 46 | throw error; 47 | } 48 | }; 49 | 50 | export const deleteAgent = async (agentId: string) => { 51 | try { 52 | const existingAgents = await loadAgents(); 53 | const updatedAgents = existingAgents.filter(agent => agent.id !== agentId); 54 | await AsyncStorage.setItem(AGENTS_STORAGE_KEY, JSON.stringify(updatedAgents)); 55 | } catch (error) { 56 | console.error('Error deleting agent:', error); 57 | throw error; 58 | } 59 | }; 60 | 61 | // 现有的 Chat 相关操作 62 | export const saveChat = async (chat: Chat) => { 63 | try { 64 | const existingChatsJson = await AsyncStorage.getItem(CHATS_STORAGE_KEY); 65 | const existingChats: Chat[] = existingChatsJson ? JSON.parse(existingChatsJson) : []; 66 | 67 | const chatIndex = existingChats.findIndex(c => c.id === chat.id); 68 | if (chatIndex !== -1) { 69 | existingChats[chatIndex] = chat; 70 | } else { 71 | existingChats.push(chat); 72 | } 73 | 74 | await AsyncStorage.setItem(CHATS_STORAGE_KEY, JSON.stringify(existingChats)); 75 | } catch (error) { 76 | console.error('Error saving chat:', error); 77 | throw error; 78 | } 79 | }; 80 | 81 | export const loadChats = async (): Promise => { 82 | try { 83 | const chatsJson = await AsyncStorage.getItem(CHATS_STORAGE_KEY); 84 | return chatsJson ? JSON.parse(chatsJson) : []; 85 | } catch (error) { 86 | console.error('Error loading chats:', error); 87 | throw error; 88 | } 89 | }; 90 | 91 | export const deleteChat = async (chatId: string) => { 92 | try { 93 | const existingChatsJson = await AsyncStorage.getItem(CHATS_STORAGE_KEY); 94 | const existingChats: Chat[] = existingChatsJson ? JSON.parse(existingChatsJson) : []; 95 | 96 | const updatedChats = existingChats.filter(chat => chat.id !== chatId); 97 | await AsyncStorage.setItem(CHATS_STORAGE_KEY, JSON.stringify(updatedChats)); 98 | } catch (error) { 99 | console.error('Error deleting chat:', error); 100 | throw error; 101 | } 102 | }; 103 | 104 | export const updateMessage = async (chatId: string, messageId: string, newContent: string) => { 105 | try { 106 | const existingChatsJson = await AsyncStorage.getItem(CHATS_STORAGE_KEY); 107 | const existingChats: Chat[] = existingChatsJson ? JSON.parse(existingChatsJson) : []; 108 | 109 | const chatIndex = existingChats.findIndex(c => c.id === chatId); 110 | if (chatIndex === -1) return; 111 | 112 | const messageIndex = existingChats[chatIndex].messages.findIndex(m => m.id === messageId); 113 | if (messageIndex === -1) return; 114 | 115 | existingChats[chatIndex].messages[messageIndex].content = newContent; 116 | existingChats[chatIndex].messages[messageIndex].isEdited = true; 117 | existingChats[chatIndex].updatedAt = Date.now(); 118 | 119 | await AsyncStorage.setItem(CHATS_STORAGE_KEY, JSON.stringify(existingChats)); 120 | } catch (error) { 121 | console.error('Error updating message:', error); 122 | throw error; 123 | } 124 | }; -------------------------------------------------------------------------------- /utils/gemini.ts: -------------------------------------------------------------------------------- 1 | import axios, { AxiosError } from 'axios'; 2 | import AsyncStorage from '@react-native-async-storage/async-storage'; 3 | import * as FileSystem from 'expo-file-system'; 4 | 5 | const BASE_URL = 'https://generativelanguage.googleapis.com/v1beta/openai/chat/completions'; 6 | const API_KEY_STORAGE_KEY = '@gemini_api_key'; 7 | 8 | type ChatMessage = { 9 | role: 'system' | 'user' | 'assistant'; 10 | content: string; 11 | image?: string | null; 12 | }; 13 | 14 | export const streamCompletion = async ( 15 | messages: ChatMessage[], 16 | onChunk: (chunk: string) => void, 17 | onError: (error: any) => void, 18 | onComplete: () => void 19 | ) => { 20 | try { 21 | const apiKey = await AsyncStorage.getItem(API_KEY_STORAGE_KEY); 22 | if (!apiKey) { 23 | throw new Error('API key not found'); 24 | } 25 | 26 | // 处理消息中的图片 27 | const processedMessages = await Promise.all(messages.map(async (message) => { 28 | if (message.image) { 29 | try { 30 | const base64 = await FileSystem.readAsStringAsync(message.image, { 31 | encoding: FileSystem.EncodingType.Base64, 32 | }); 33 | 34 | return { 35 | role: message.role, 36 | content: [ 37 | { 38 | type: 'text', 39 | text: message.content, 40 | }, 41 | { 42 | type: 'image_url', 43 | image_url: { 44 | url: `data:image/jpeg;base64,${base64}`, 45 | }, 46 | }, 47 | ], 48 | }; 49 | } catch (error) { 50 | console.error('Error processing image:', error); 51 | return { 52 | role: message.role, 53 | content: message.content, 54 | }; 55 | } 56 | } 57 | return { 58 | role: message.role, 59 | content: message.content, 60 | }; 61 | })); 62 | 63 | console.log('Sending stream request with messages:', JSON.stringify(processedMessages, null, 2)); 64 | console.log('Using API URL:', BASE_URL); 65 | 66 | const requestConfig = { 67 | model: 'gemini-2.0-pro-exp-02-05', 68 | messages: processedMessages, 69 | stream: true, 70 | }; 71 | console.log('Request config:', JSON.stringify(requestConfig, null, 2)); 72 | 73 | const response = await axios.post( 74 | BASE_URL, 75 | requestConfig, 76 | { 77 | headers: { 78 | 'Content-Type': 'application/json', 79 | 'Authorization': `Bearer ${apiKey}`, 80 | 'Accept': 'text/event-stream' 81 | }, 82 | responseType: 'text', 83 | validateStatus: (status) => { 84 | console.log('Response status:', status); 85 | return status >= 200 && status < 300; 86 | } 87 | } 88 | ); 89 | 90 | if (!response.data) { 91 | throw new Error('No response data received'); 92 | } 93 | 94 | console.log('Stream response status:', response.status); 95 | console.log('Stream response headers:', response.headers); 96 | console.log('Raw response data:', response.data); 97 | 98 | const chunks = response.data.split('\n').filter(Boolean); 99 | console.log('Filtered chunks:', chunks); 100 | 101 | if (chunks.length === 0) { 102 | throw new Error('No chunks received in response'); 103 | } 104 | 105 | for (const chunk of chunks) { 106 | try { 107 | console.log('Processing chunk:', chunk); 108 | if (chunk.includes('[DONE]')) { 109 | console.log('Received [DONE] signal'); 110 | continue; 111 | } 112 | const json = JSON.parse(chunk.replace(/^data: /, '')); 113 | console.log('Parsed JSON:', json); 114 | const content = json.choices[0]?.delta?.content; 115 | if (content) { 116 | console.log('Extracted content:', content); 117 | onChunk(content); 118 | } 119 | } catch (e) { 120 | console.error('Error parsing chunk:', e, '\nChunk:', chunk); 121 | } 122 | } 123 | onComplete(); 124 | } catch (error: unknown) { 125 | const axiosError = error as AxiosError; 126 | console.error('Stream request failed:', { 127 | status: axiosError.response?.status, 128 | statusText: axiosError.response?.statusText, 129 | data: axiosError.response?.data, 130 | message: axiosError.message, 131 | code: axiosError.code, 132 | name: axiosError.name 133 | }); 134 | onError(axiosError); 135 | } 136 | }; 137 | 138 | export const generateCompletion = async (messages: ChatMessage[]) => { 139 | try { 140 | const apiKey = await AsyncStorage.getItem(API_KEY_STORAGE_KEY); 141 | if (!apiKey) { 142 | throw new Error('API key not found'); 143 | } 144 | 145 | console.log('Sending completion request with messages:', JSON.stringify(messages, null, 2)); 146 | 147 | const response = await axios.post( 148 | BASE_URL, 149 | { 150 | model: 'gemini-2.0-pro-exp-02-05', 151 | messages, 152 | }, 153 | { 154 | headers: { 155 | 'Content-Type': 'application/json', 156 | 'Authorization': `Bearer ${apiKey}` 157 | } 158 | } 159 | ); 160 | 161 | console.log('Completion response status:', response.status); 162 | console.log('Completion response data:', response.data); 163 | 164 | return response.data.choices[0]?.message?.content || ''; 165 | } catch (error: unknown) { 166 | const axiosError = error as AxiosError; 167 | console.error('Completion request failed:', axiosError.response?.status); 168 | console.error('Error details:', { 169 | message: axiosError.message, 170 | response: axiosError.response?.data, 171 | config: { 172 | url: axiosError.config?.url, 173 | headers: axiosError.config?.headers, 174 | data: axiosError.config?.data 175 | } 176 | }); 177 | throw error; 178 | } 179 | }; -------------------------------------------------------------------------------- /app/(tabs)/agent.tsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from 'react'; 2 | import { 3 | View, 4 | Text, 5 | StyleSheet, 6 | FlatList, 7 | Pressable, 8 | Alert, 9 | } from 'react-native'; 10 | import { SafeAreaView } from 'react-native-safe-area-context'; 11 | import { MaterialIcons } from '@expo/vector-icons'; 12 | import { useRouter } from 'expo-router'; 13 | import { Agent } from '@/constants/Config'; 14 | import { loadAgents, initializeAgents, deleteAgent } from '@/utils/storage'; 15 | import { nanoid } from 'nanoid/non-secure'; 16 | 17 | export default function AgentScreen() { 18 | const [agents, setAgents] = useState([]); 19 | const router = useRouter(); 20 | 21 | useEffect(() => { 22 | loadInitialAgents(); 23 | }, []); 24 | 25 | const loadInitialAgents = async () => { 26 | const initialAgents = await initializeAgents(); 27 | setAgents(initialAgents); 28 | }; 29 | 30 | const handleCreateAgent = () => { 31 | const newAgent: Agent = { 32 | id: nanoid(), 33 | name: 'New Agent', 34 | description: 'Describe your agent\'s purpose', 35 | systemPrompt: 'You are a helpful AI assistant.', 36 | icon: 'android', 37 | color: '#6B4EFF', 38 | createdAt: Date.now(), 39 | updatedAt: Date.now(), 40 | }; 41 | router.push('/agent/new'); 42 | }; 43 | 44 | const handleEditAgent = (agent: Agent) => { 45 | router.push(`/agent/${agent.id}`); 46 | }; 47 | 48 | const handleStartChat = (agent: Agent) => { 49 | router.push({ 50 | pathname: '/', 51 | params: { agentId: agent.id } 52 | }); 53 | }; 54 | 55 | const handleDeleteAgent = async (agent: Agent) => { 56 | if (agent.isDefault) { 57 | Alert.alert('Cannot Delete', 'Default agents cannot be deleted.'); 58 | return; 59 | } 60 | 61 | Alert.alert( 62 | 'Delete Agent', 63 | `Are you sure you want to delete "${agent.name}"?`, 64 | [ 65 | { text: 'Cancel', style: 'cancel' }, 66 | { 67 | text: 'Delete', 68 | style: 'destructive', 69 | onPress: async () => { 70 | try { 71 | await deleteAgent(agent.id); 72 | setAgents(agents.filter(a => a.id !== agent.id)); 73 | } catch (error) { 74 | Alert.alert('Error', 'Failed to delete agent'); 75 | } 76 | }, 77 | }, 78 | ] 79 | ); 80 | }; 81 | 82 | const renderAgentItem = ({ item: agent }: { item: Agent }) => ( 83 | [ 85 | styles.agentItem, 86 | pressed && styles.agentItemPressed, 87 | ]} 88 | onPress={() => handleStartChat(agent)} 89 | onLongPress={() => handleDeleteAgent(agent)} 90 | > 91 | 92 | 93 | 94 | 95 | {agent.name} 96 | 97 | {agent.description} 98 | 99 | 100 | 101 | [ 103 | styles.actionButton, 104 | pressed && styles.actionButtonPressed, 105 | ]} 106 | onPress={() => handleEditAgent(agent)} 107 | hitSlop={8} 108 | > 109 | 110 | 111 | [ 113 | styles.actionButton, 114 | pressed && styles.actionButtonPressed, 115 | ]} 116 | onPress={() => handleStartChat(agent)} 117 | hitSlop={8} 118 | > 119 | 120 | 121 | 122 | 123 | ); 124 | 125 | return ( 126 | 127 | item.id} 131 | contentContainerStyle={styles.listContent} 132 | /> 133 | [ 135 | styles.createButton, 136 | pressed && styles.createButtonPressed, 137 | ]} 138 | onPress={handleCreateAgent} 139 | > 140 | 141 | Create New Agent 142 | 143 | 144 | ); 145 | } 146 | 147 | const styles = StyleSheet.create({ 148 | container: { 149 | flex: 1, 150 | backgroundColor: '#FFFFFF', 151 | }, 152 | listContent: { 153 | padding: 16, 154 | }, 155 | agentItem: { 156 | flexDirection: 'row', 157 | alignItems: 'center', 158 | padding: 16, 159 | backgroundColor: '#FFFFFF', 160 | borderRadius: 12, 161 | marginBottom: 12, 162 | borderWidth: 1, 163 | borderColor: '#E5E5E5', 164 | }, 165 | agentItemPressed: { 166 | opacity: 0.7, 167 | }, 168 | iconContainer: { 169 | width: 40, 170 | height: 40, 171 | borderRadius: 20, 172 | justifyContent: 'center', 173 | alignItems: 'center', 174 | marginRight: 12, 175 | }, 176 | agentInfo: { 177 | flex: 1, 178 | marginRight: 12, 179 | }, 180 | agentName: { 181 | fontSize: 16, 182 | fontWeight: '600', 183 | color: '#000000', 184 | marginBottom: 4, 185 | }, 186 | agentDescription: { 187 | fontSize: 14, 188 | color: '#666666', 189 | }, 190 | createButton: { 191 | flexDirection: 'row', 192 | alignItems: 'center', 193 | justifyContent: 'center', 194 | backgroundColor: '#6B4EFF', 195 | margin: 16, 196 | padding: 16, 197 | borderRadius: 12, 198 | }, 199 | createButtonPressed: { 200 | opacity: 0.7, 201 | }, 202 | createButtonText: { 203 | color: '#FFFFFF', 204 | fontSize: 16, 205 | fontWeight: '600', 206 | marginLeft: 8, 207 | }, 208 | actions: { 209 | flexDirection: 'row', 210 | gap: 8, 211 | }, 212 | actionButton: { 213 | padding: 8, 214 | borderRadius: 20, 215 | backgroundColor: '#F5F5F5', 216 | }, 217 | actionButtonPressed: { 218 | opacity: 0.7, 219 | }, 220 | }); -------------------------------------------------------------------------------- /app/chats.tsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from 'react'; 2 | import { 3 | View, 4 | Text, 5 | StyleSheet, 6 | FlatList, 7 | Pressable, 8 | Alert, 9 | } from 'react-native'; 10 | import { Stack, useRouter } from 'expo-router'; 11 | import { SafeAreaView } from 'react-native-safe-area-context'; 12 | import { MaterialIcons } from '@expo/vector-icons'; 13 | import { Chat } from '@/constants/Config'; 14 | import { loadChats, deleteChat, loadAgents } from '@/utils/storage'; 15 | 16 | export default function ChatsScreen() { 17 | const [chats, setChats] = useState([]); 18 | const [agents, setAgents] = useState>({}); 19 | const router = useRouter(); 20 | 21 | useEffect(() => { 22 | loadChatHistory(); 23 | }, []); 24 | 25 | const loadChatHistory = async () => { 26 | try { 27 | const [loadedChats, loadedAgents] = await Promise.all([ 28 | loadChats(), 29 | loadAgents(), 30 | ]); 31 | 32 | // Create a map of agent details for quick lookup 33 | const agentMap = loadedAgents.reduce((acc, agent) => { 34 | acc[agent.id] = { name: agent.name, color: agent.color }; 35 | return acc; 36 | }, {} as Record); 37 | 38 | setAgents(agentMap); 39 | setChats(loadedChats.sort((a, b) => b.updatedAt - a.updatedAt)); 40 | } catch (error) { 41 | console.error('Error loading chat history:', error); 42 | Alert.alert('Error', 'Failed to load chat history'); 43 | } 44 | }; 45 | 46 | const handleDeleteChat = (chat: Chat) => { 47 | Alert.alert( 48 | 'Delete Chat', 49 | 'Are you sure you want to delete this chat?', 50 | [ 51 | { text: 'Cancel', style: 'cancel' }, 52 | { 53 | text: 'Delete', 54 | style: 'destructive', 55 | onPress: async () => { 56 | try { 57 | await deleteChat(chat.id); 58 | setChats(chats.filter(c => c.id !== chat.id)); 59 | } catch (error) { 60 | console.error('Error deleting chat:', error); 61 | Alert.alert('Error', 'Failed to delete chat'); 62 | } 63 | }, 64 | }, 65 | ] 66 | ); 67 | }; 68 | 69 | const handleOpenChat = (chat: Chat) => { 70 | router.push({ 71 | pathname: '/(tabs)/', 72 | params: { agentId: chat.agentId, chatId: chat.id } 73 | }); 74 | }; 75 | 76 | const formatDate = (timestamp: number) => { 77 | const date = new Date(timestamp); 78 | return date.toLocaleDateString(undefined, { 79 | year: 'numeric', 80 | month: 'short', 81 | day: 'numeric', 82 | }); 83 | }; 84 | 85 | const renderChatItem = ({ item: chat }: { item: Chat }) => { 86 | const agent = agents[chat.agentId]; 87 | const lastMessage = chat.messages[chat.messages.length - 1]; 88 | 89 | return ( 90 | [ 92 | styles.chatItem, 93 | pressed && styles.chatItemPressed, 94 | ]} 95 | onPress={() => handleOpenChat(chat)} 96 | onLongPress={() => handleDeleteChat(chat)} 97 | > 98 | 99 | 100 | 101 | {agent?.name || 'Unknown Agent'} 102 | {formatDate(chat.updatedAt)} 103 | 104 | 105 | {lastMessage?.content || 'No messages'} 106 | 107 | 108 | {chat.messages.length} message{chat.messages.length !== 1 ? 's' : ''} 109 | 110 | 111 | [ 113 | styles.deleteButton, 114 | pressed && styles.deleteButtonPressed, 115 | ]} 116 | onPress={() => handleDeleteChat(chat)} 117 | hitSlop={8} 118 | > 119 | 120 | 121 | 122 | ); 123 | }; 124 | 125 | return ( 126 | <> 127 | ( 131 | router.back()} 133 | style={({ pressed }) => [ 134 | styles.headerButton, 135 | pressed && styles.headerButtonPressed, 136 | ]} 137 | > 138 | 139 | 140 | ), 141 | }} 142 | /> 143 | 144 | item.id} 148 | contentContainerStyle={styles.listContent} 149 | ListEmptyComponent={() => ( 150 | 151 | 152 | No Chats Yet 153 | 154 | Start a conversation with an agent to see your chat history here 155 | 156 | 157 | )} 158 | /> 159 | 160 | 161 | ); 162 | } 163 | 164 | const styles = StyleSheet.create({ 165 | container: { 166 | flex: 1, 167 | backgroundColor: '#FFFFFF', 168 | }, 169 | listContent: { 170 | padding: 16, 171 | }, 172 | chatItem: { 173 | flexDirection: 'row', 174 | alignItems: 'center', 175 | padding: 16, 176 | backgroundColor: '#FFFFFF', 177 | borderRadius: 12, 178 | marginBottom: 12, 179 | borderWidth: 1, 180 | borderColor: '#E5E5E5', 181 | }, 182 | chatItemPressed: { 183 | opacity: 0.7, 184 | }, 185 | agentIndicator: { 186 | width: 4, 187 | height: 40, 188 | borderRadius: 2, 189 | marginRight: 12, 190 | }, 191 | chatInfo: { 192 | flex: 1, 193 | marginRight: 12, 194 | }, 195 | chatHeader: { 196 | flexDirection: 'row', 197 | justifyContent: 'space-between', 198 | alignItems: 'center', 199 | marginBottom: 4, 200 | }, 201 | agentName: { 202 | fontSize: 16, 203 | fontWeight: '600', 204 | color: '#000000', 205 | }, 206 | date: { 207 | fontSize: 12, 208 | color: '#999999', 209 | }, 210 | lastMessage: { 211 | fontSize: 14, 212 | color: '#666666', 213 | marginBottom: 4, 214 | }, 215 | messageCount: { 216 | fontSize: 12, 217 | color: '#999999', 218 | }, 219 | deleteButton: { 220 | padding: 8, 221 | borderRadius: 20, 222 | backgroundColor: '#FFF2F2', 223 | }, 224 | deleteButtonPressed: { 225 | opacity: 0.7, 226 | }, 227 | headerButton: { 228 | padding: 8, 229 | marginLeft: 8, 230 | borderRadius: 8, 231 | backgroundColor: '#F5F5F5', 232 | }, 233 | headerButtonPressed: { 234 | opacity: 0.7, 235 | backgroundColor: '#E5E5E5', 236 | }, 237 | emptyState: { 238 | flex: 1, 239 | alignItems: 'center', 240 | justifyContent: 'center', 241 | padding: 16, 242 | marginTop: 100, 243 | }, 244 | emptyStateTitle: { 245 | fontSize: 20, 246 | fontWeight: '600', 247 | color: '#000000', 248 | marginTop: 16, 249 | marginBottom: 8, 250 | }, 251 | emptyStateDescription: { 252 | fontSize: 16, 253 | color: '#666666', 254 | textAlign: 'center', 255 | }, 256 | }); -------------------------------------------------------------------------------- /android/app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: "com.android.application" 2 | apply plugin: "org.jetbrains.kotlin.android" 3 | apply plugin: "com.facebook.react" 4 | 5 | def projectRoot = rootDir.getAbsoluteFile().getParentFile().getAbsolutePath() 6 | 7 | /** 8 | * This is the configuration block to customize your React Native Android app. 9 | * By default you don't need to apply any configuration, just uncomment the lines you need. 10 | */ 11 | react { 12 | entryFile = file(["node", "-e", "require('expo/scripts/resolveAppEntry')", projectRoot, "android", "absolute"].execute(null, rootDir).text.trim()) 13 | reactNativeDir = new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsoluteFile() 14 | hermesCommand = new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/sdks/hermesc/%OS-BIN%/hermesc" 15 | codegenDir = new File(["node", "--print", "require.resolve('@react-native/codegen/package.json', { paths: [require.resolve('react-native/package.json')] })"].execute(null, rootDir).text.trim()).getParentFile().getAbsoluteFile() 16 | 17 | // Use Expo CLI to bundle the app, this ensures the Metro config 18 | // works correctly with Expo projects. 19 | cliFile = new File(["node", "--print", "require.resolve('@expo/cli', { paths: [require.resolve('expo/package.json')] })"].execute(null, rootDir).text.trim()) 20 | bundleCommand = "export:embed" 21 | 22 | /* Folders */ 23 | // The root of your project, i.e. where "package.json" lives. Default is '../..' 24 | // root = file("../../") 25 | // The folder where the react-native NPM package is. Default is ../../node_modules/react-native 26 | // reactNativeDir = file("../../node_modules/react-native") 27 | // The folder where the react-native Codegen package is. Default is ../../node_modules/@react-native/codegen 28 | // codegenDir = file("../../node_modules/@react-native/codegen") 29 | 30 | /* Variants */ 31 | // The list of variants to that are debuggable. For those we're going to 32 | // skip the bundling of the JS bundle and the assets. By default is just 'debug'. 33 | // If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants. 34 | // debuggableVariants = ["liteDebug", "prodDebug"] 35 | 36 | /* Bundling */ 37 | // A list containing the node command and its flags. Default is just 'node'. 38 | // nodeExecutableAndArgs = ["node"] 39 | 40 | // 41 | // The path to the CLI configuration file. Default is empty. 42 | // bundleConfig = file(../rn-cli.config.js) 43 | // 44 | // The name of the generated asset file containing your JS bundle 45 | // bundleAssetName = "MyApplication.android.bundle" 46 | // 47 | // The entry file for bundle generation. Default is 'index.android.js' or 'index.js' 48 | // entryFile = file("../js/MyApplication.android.js") 49 | // 50 | // A list of extra flags to pass to the 'bundle' commands. 51 | // See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle 52 | // extraPackagerArgs = [] 53 | 54 | /* Hermes Commands */ 55 | // The hermes compiler command to run. By default it is 'hermesc' 56 | // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc" 57 | // 58 | // The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map" 59 | // hermesFlags = ["-O", "-output-source-map"] 60 | 61 | /* Autolinking */ 62 | autolinkLibrariesWithApp() 63 | } 64 | 65 | /** 66 | * Set this to true to Run Proguard on Release builds to minify the Java bytecode. 67 | */ 68 | def enableProguardInReleaseBuilds = (findProperty('android.enableProguardInReleaseBuilds') ?: false).toBoolean() 69 | 70 | /** 71 | * The preferred build flavor of JavaScriptCore (JSC) 72 | * 73 | * For example, to use the international variant, you can use: 74 | * `def jscFlavor = 'org.webkit:android-jsc-intl:+'` 75 | * 76 | * The international variant includes ICU i18n library and necessary data 77 | * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that 78 | * give correct results when using with locales other than en-US. Note that 79 | * this variant is about 6MiB larger per architecture than default. 80 | */ 81 | def jscFlavor = 'org.webkit:android-jsc:+' 82 | 83 | android { 84 | ndkVersion rootProject.ext.ndkVersion 85 | 86 | buildToolsVersion rootProject.ext.buildToolsVersion 87 | compileSdk rootProject.ext.compileSdkVersion 88 | 89 | namespace 'com.your.app' 90 | defaultConfig { 91 | applicationId 'com.your.app' 92 | minSdkVersion rootProject.ext.minSdkVersion 93 | targetSdkVersion rootProject.ext.targetSdkVersion 94 | versionCode 1 95 | versionName "1.0.2" 96 | 97 | splits { 98 | abi { 99 | enable true 100 | reset() 101 | //noinspection ChromeOsAbiSupport 102 | include "arm64-v8a" 103 | universalApk false 104 | } 105 | } 106 | } 107 | signingConfigs { 108 | debug { 109 | storeFile file('debug.keystore') 110 | storePassword 'android' 111 | keyAlias 'androiddebugkey' 112 | keyPassword 'android' 113 | } 114 | } 115 | buildTypes { 116 | debug { 117 | signingConfig signingConfigs.debug 118 | } 119 | release { 120 | // Caution! In production, you need to generate your own keystore file. 121 | // see https://reactnative.dev/docs/signed-apk-android. 122 | signingConfig signingConfigs.debug 123 | shrinkResources (findProperty('android.enableShrinkResourcesInReleaseBuilds')?.toBoolean() ?: false) 124 | minifyEnabled enableProguardInReleaseBuilds 125 | proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" 126 | crunchPngs (findProperty('android.enablePngCrunchInReleaseBuilds')?.toBoolean() ?: true) 127 | } 128 | } 129 | packagingOptions { 130 | jniLibs { 131 | useLegacyPackaging (findProperty('expo.useLegacyPackaging')?.toBoolean() ?: false) 132 | } 133 | } 134 | androidResources { 135 | ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:!CVS:!thumbs.db:!picasa.ini:!*~' 136 | } 137 | } 138 | 139 | // Apply static values from `gradle.properties` to the `android.packagingOptions` 140 | // Accepts values in comma delimited lists, example: 141 | // android.packagingOptions.pickFirsts=/LICENSE,**/picasa.ini 142 | ["pickFirsts", "excludes", "merges", "doNotStrip"].each { prop -> 143 | // Split option: 'foo,bar' -> ['foo', 'bar'] 144 | def options = (findProperty("android.packagingOptions.$prop") ?: "").split(","); 145 | // Trim all elements in place. 146 | for (i in 0.. 0) { 151 | println "android.packagingOptions.$prop += $options ($options.length)" 152 | // Ex: android.packagingOptions.pickFirsts += '**/SCCS/**' 153 | options.each { 154 | android.packagingOptions[prop] += it 155 | } 156 | } 157 | } 158 | 159 | dependencies { 160 | // The version of react-native is set by the React Native Gradle Plugin 161 | implementation("com.facebook.react:react-android") 162 | 163 | def isGifEnabled = (findProperty('expo.gif.enabled') ?: "") == "true"; 164 | def isWebpEnabled = (findProperty('expo.webp.enabled') ?: "") == "true"; 165 | def isWebpAnimatedEnabled = (findProperty('expo.webp.animated') ?: "") == "true"; 166 | 167 | if (isGifEnabled) { 168 | // For animated gif support 169 | implementation("com.facebook.fresco:animated-gif:${reactAndroidLibs.versions.fresco.get()}") 170 | } 171 | 172 | if (isWebpEnabled) { 173 | // For webp support 174 | implementation("com.facebook.fresco:webpsupport:${reactAndroidLibs.versions.fresco.get()}") 175 | if (isWebpAnimatedEnabled) { 176 | // Animated webp support 177 | implementation("com.facebook.fresco:animated-webp:${reactAndroidLibs.versions.fresco.get()}") 178 | } 179 | } 180 | 181 | if (hermesEnabled.toBoolean()) { 182 | implementation("com.facebook.react:hermes-android") 183 | } else { 184 | implementation jscFlavor 185 | } 186 | } 187 | -------------------------------------------------------------------------------- /android/gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s 90 | ' "$PWD" ) || exit 91 | 92 | # Use the maximum available, or set MAX_FD != -1 to use that value. 93 | MAX_FD=maximum 94 | 95 | warn () { 96 | echo "$*" 97 | } >&2 98 | 99 | die () { 100 | echo 101 | echo "$*" 102 | echo 103 | exit 1 104 | } >&2 105 | 106 | # OS specific support (must be 'true' or 'false'). 107 | cygwin=false 108 | msys=false 109 | darwin=false 110 | nonstop=false 111 | case "$( uname )" in #( 112 | CYGWIN* ) cygwin=true ;; #( 113 | Darwin* ) darwin=true ;; #( 114 | MSYS* | MINGW* ) msys=true ;; #( 115 | NONSTOP* ) nonstop=true ;; 116 | esac 117 | 118 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 119 | 120 | 121 | # Determine the Java command to use to start the JVM. 122 | if [ -n "$JAVA_HOME" ] ; then 123 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 124 | # IBM's JDK on AIX uses strange locations for the executables 125 | JAVACMD=$JAVA_HOME/jre/sh/java 126 | else 127 | JAVACMD=$JAVA_HOME/bin/java 128 | fi 129 | if [ ! -x "$JAVACMD" ] ; then 130 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 131 | 132 | Please set the JAVA_HOME variable in your environment to match the 133 | location of your Java installation." 134 | fi 135 | else 136 | JAVACMD=java 137 | if ! command -v java >/dev/null 2>&1 138 | then 139 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 140 | 141 | Please set the JAVA_HOME variable in your environment to match the 142 | location of your Java installation." 143 | fi 144 | fi 145 | 146 | # Increase the maximum file descriptors if we can. 147 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 148 | case $MAX_FD in #( 149 | max*) 150 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 151 | # shellcheck disable=SC2039,SC3045 152 | MAX_FD=$( ulimit -H -n ) || 153 | warn "Could not query maximum file descriptor limit" 154 | esac 155 | case $MAX_FD in #( 156 | '' | soft) :;; #( 157 | *) 158 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 159 | # shellcheck disable=SC2039,SC3045 160 | ulimit -n "$MAX_FD" || 161 | warn "Could not set maximum file descriptor limit to $MAX_FD" 162 | esac 163 | fi 164 | 165 | # Collect all arguments for the java command, stacking in reverse order: 166 | # * args from the command line 167 | # * the main class name 168 | # * -classpath 169 | # * -D...appname settings 170 | # * --module-path (only if needed) 171 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 172 | 173 | # For Cygwin or MSYS, switch paths to Windows format before running java 174 | if "$cygwin" || "$msys" ; then 175 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 176 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 177 | 178 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 179 | 180 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 181 | for arg do 182 | if 183 | case $arg in #( 184 | -*) false ;; # don't mess with options #( 185 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 186 | [ -e "$t" ] ;; #( 187 | *) false ;; 188 | esac 189 | then 190 | arg=$( cygpath --path --ignore --mixed "$arg" ) 191 | fi 192 | # Roll the args list around exactly as many times as the number of 193 | # args, so each arg winds up back in the position where it started, but 194 | # possibly modified. 195 | # 196 | # NB: a `for` loop captures its iteration list before it begins, so 197 | # changing the positional parameters here affects neither the number of 198 | # iterations, nor the values presented in `arg`. 199 | shift # remove old arg 200 | set -- "$@" "$arg" # push replacement arg 201 | done 202 | fi 203 | 204 | 205 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 206 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 207 | 208 | # Collect all arguments for the java command: 209 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 210 | # and any embedded shellness will be escaped. 211 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 212 | # treated as '${Hostname}' itself on the command line. 213 | 214 | set -- \ 215 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 216 | -classpath "$CLASSPATH" \ 217 | org.gradle.wrapper.GradleWrapperMain \ 218 | "$@" 219 | 220 | # Stop when "xargs" is not available. 221 | if ! command -v xargs >/dev/null 2>&1 222 | then 223 | die "xargs is not available" 224 | fi 225 | 226 | # Use "xargs" to parse quoted args. 227 | # 228 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 229 | # 230 | # In Bash we could simply go: 231 | # 232 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 233 | # set -- "${ARGS[@]}" "$@" 234 | # 235 | # but POSIX shell has neither arrays nor command substitution, so instead we 236 | # post-process each arg (as a line of input to sed) to backslash-escape any 237 | # character that might be a shell metacharacter, then use eval to reverse 238 | # that process (while maintaining the separation between arguments), and wrap 239 | # the whole thing up as a single "set" statement. 240 | # 241 | # This will of course break if any of these variables contains a newline or 242 | # an unmatched quote. 243 | # 244 | 245 | eval "set -- $( 246 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 247 | xargs -n1 | 248 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 249 | tr '\n' ' ' 250 | )" '"$@"' 251 | 252 | exec "$JAVACMD" "$@" 253 | -------------------------------------------------------------------------------- /components/Message.tsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from 'react'; 2 | import { View, Text, StyleSheet, Pressable, TextInput, Alert, Platform, Linking, Image } from 'react-native'; 3 | import { CodeBlock } from './CodeBlock'; 4 | import { Message as MessageType } from '@/constants/Config'; 5 | import { MaterialIcons } from '@expo/vector-icons'; 6 | import { useTheme } from '@/contexts/ThemeContext'; 7 | import Markdown from 'react-native-markdown-display'; 8 | 9 | interface MessageProps { 10 | message: MessageType; 11 | onEdit?: (messageId: string, newContent: string) => void; 12 | onRegenerate?: (messageId: string) => void; 13 | onCopy?: (content: string) => void; 14 | } 15 | 16 | export const Message: React.FC = ({ message, onEdit, onRegenerate, onCopy }) => { 17 | const { isDarkMode } = useTheme(); 18 | const [isEditing, setIsEditing] = useState(false); 19 | const [editedContent, setEditedContent] = useState(message.content); 20 | 21 | const handleSaveEdit = () => { 22 | if (editedContent.trim() === '') { 23 | Alert.alert('Error', 'Message cannot be empty'); 24 | return; 25 | } 26 | onEdit?.(message.id, editedContent); 27 | setIsEditing(false); 28 | }; 29 | 30 | const handleCancelEdit = () => { 31 | setEditedContent(message.content); 32 | setIsEditing(false); 33 | }; 34 | 35 | const renderContent = () => { 36 | if (isEditing) { 37 | return ( 38 | 39 | 46 | 47 | 51 | 52 | Cancel 53 | 54 | 55 | 59 | 60 | Save 61 | 62 | 63 | 64 | 65 | ); 66 | } 67 | 68 | return ( 69 | <> 70 | {message.image && ( 71 | 72 | 73 | 74 | )} 75 | { 115 | Alert.alert( 116 | 'Open Link', 117 | 'Do you want to open this link?', 118 | [ 119 | { text: 'Cancel', style: 'cancel' }, 120 | { text: 'Open', onPress: () => Linking.openURL(url) }, 121 | ] 122 | ); 123 | return false; 124 | }} 125 | > 126 | {message.content} 127 | 128 | 129 | ); 130 | }; 131 | 132 | return ( 133 | 134 | {message.role === 'assistant' && ( 135 | 136 | 137 | 138 | )} 139 | 144 | {renderContent()} 145 | {message.isEdited && !isEditing && ( 146 | 147 | (edited) 148 | 149 | )} 150 | 151 | {message.role === 'user' && ( 152 | 153 | onCopy?.(message.content)} 156 | hitSlop={8} 157 | > 158 | 159 | 160 | setIsEditing(true)} 163 | hitSlop={8} 164 | > 165 | 166 | 167 | 168 | )} 169 | {message.role === 'assistant' && ( 170 | 171 | onCopy?.(message.content)} 174 | hitSlop={8} 175 | > 176 | 177 | 178 | onRegenerate?.(message.id)} 181 | hitSlop={8} 182 | > 183 | 184 | 185 | 186 | )} 187 | 188 | ); 189 | }; 190 | 191 | const styles = StyleSheet.create({ 192 | container: { 193 | flexDirection: 'row', 194 | marginVertical: 8, 195 | paddingHorizontal: 16, 196 | alignItems: 'flex-start', 197 | }, 198 | userMessage: { 199 | justifyContent: 'flex-end', 200 | }, 201 | assistantMessage: { 202 | justifyContent: 'flex-start', 203 | }, 204 | avatar: { 205 | width: 32, 206 | height: 32, 207 | borderRadius: 16, 208 | backgroundColor: '#6B4EFF', 209 | justifyContent: 'center', 210 | alignItems: 'center', 211 | marginRight: 8, 212 | }, 213 | messageContent: { 214 | maxWidth: '70%', 215 | borderRadius: 16, 216 | padding: 12, 217 | }, 218 | userMessageContent: { 219 | backgroundColor: '#6B4EFF', 220 | borderBottomRightRadius: 4, 221 | }, 222 | assistantMessageContent: { 223 | backgroundColor: '#F5F5F5', 224 | borderBottomLeftRadius: 4, 225 | }, 226 | darkAssistantMessageContent: { 227 | backgroundColor: '#1C1C1E', 228 | }, 229 | text: { 230 | fontSize: 16, 231 | lineHeight: 22, 232 | }, 233 | darkText: { 234 | color: '#FFFFFF', 235 | }, 236 | codeBlock: { 237 | fontFamily: Platform.select({ 238 | ios: 'Menlo', 239 | android: 'monospace', 240 | }), 241 | backgroundColor: '#1E1E1E', 242 | color: '#FFFFFF', 243 | fontSize: 14, 244 | }, 245 | link: { 246 | color: '#6B4EFF', 247 | textDecorationLine: 'underline', 248 | }, 249 | list: { 250 | marginLeft: 8, 251 | }, 252 | heading: { 253 | fontWeight: 'bold', 254 | marginVertical: 8, 255 | color: '#000000', 256 | }, 257 | heading1: { 258 | fontSize: 24, 259 | }, 260 | heading2: { 261 | fontSize: 20, 262 | }, 263 | heading3: { 264 | fontSize: 18, 265 | }, 266 | actionButtons: { 267 | flexDirection: 'row', 268 | marginLeft: 8, 269 | alignItems: 'center', 270 | }, 271 | actionButton: { 272 | padding: 4, 273 | marginHorizontal: 4, 274 | }, 275 | darkActionButton: { 276 | backgroundColor: '#1C1C1E', 277 | }, 278 | editContainer: { 279 | width: '100%', 280 | }, 281 | editInput: { 282 | backgroundColor: '#FFFFFF', 283 | borderRadius: 8, 284 | padding: 12, 285 | fontSize: 16, 286 | color: '#000000', 287 | minHeight: 100, 288 | textAlignVertical: 'top', 289 | }, 290 | darkEditInput: { 291 | backgroundColor: '#1C1C1E', 292 | color: '#FFFFFF', 293 | }, 294 | editButtons: { 295 | flexDirection: 'row', 296 | justifyContent: 'flex-end', 297 | marginTop: 8, 298 | gap: 8, 299 | }, 300 | editButton: { 301 | paddingHorizontal: 16, 302 | paddingVertical: 8, 303 | borderRadius: 8, 304 | }, 305 | editButtonText: { 306 | fontSize: 14, 307 | fontWeight: '600', 308 | }, 309 | editedLabel: { 310 | fontSize: 12, 311 | color: '#999999', 312 | marginTop: 4, 313 | fontStyle: 'italic', 314 | }, 315 | darkEditedLabel: { 316 | color: '#666666', 317 | }, 318 | imageContainer: { 319 | marginBottom: 8, 320 | borderRadius: 8, 321 | overflow: 'hidden', 322 | }, 323 | image: { 324 | width: '100%', 325 | height: 200, 326 | borderRadius: 8, 327 | }, 328 | }); -------------------------------------------------------------------------------- /app/agent/[id].tsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from 'react'; 2 | import { 3 | View, 4 | Text, 5 | StyleSheet, 6 | TextInput, 7 | ScrollView, 8 | Pressable, 9 | Alert, 10 | } from 'react-native'; 11 | import { useLocalSearchParams, useRouter, Stack } from 'expo-router'; 12 | import { SafeAreaView } from 'react-native-safe-area-context'; 13 | import { MaterialIcons } from '@expo/vector-icons'; 14 | import { Agent } from '@/constants/Config'; 15 | import { loadAgents, saveAgent } from '@/utils/storage'; 16 | import { nanoid } from 'nanoid/non-secure'; 17 | import { useTheme } from '@/contexts/ThemeContext'; 18 | 19 | const COLORS = ['#6B4EFF', '#00C853', '#FF6B4E', '#FF9100', '#2196F3', '#9C27B0']; 20 | const ICONS = ['chat-bubble-outline', 'edit', 'code', 'psychology', 'science', 'school']; 21 | 22 | export default function AgentEditScreen() { 23 | const { id } = useLocalSearchParams<{ id: string }>(); 24 | const router = useRouter(); 25 | const { isDarkMode } = useTheme(); 26 | const [agent, setAgent] = useState({ 27 | id: '', 28 | name: '', 29 | description: '', 30 | systemPrompt: '', 31 | icon: 'chat-bubble-outline', 32 | color: '#6B4EFF', 33 | createdAt: Date.now(), 34 | updatedAt: Date.now(), 35 | }); 36 | const [showColorPicker, setShowColorPicker] = useState(false); 37 | const [showIconPicker, setShowIconPicker] = useState(false); 38 | 39 | useEffect(() => { 40 | if (id === 'new') { 41 | setAgent({ 42 | ...agent, 43 | id: nanoid(), 44 | }); 45 | } else { 46 | loadAgent(); 47 | } 48 | }, [id]); 49 | 50 | const loadAgent = async () => { 51 | const agents = await loadAgents(); 52 | const existingAgent = agents.find(a => a.id === id); 53 | if (existingAgent) { 54 | setAgent(existingAgent); 55 | } 56 | }; 57 | 58 | const handleSave = async () => { 59 | if (!agent.name.trim()) { 60 | Alert.alert('Error', 'Please enter a name for your agent'); 61 | return; 62 | } 63 | 64 | if (!agent.systemPrompt.trim()) { 65 | Alert.alert('Error', 'Please enter a system prompt for your agent'); 66 | return; 67 | } 68 | 69 | try { 70 | await saveAgent({ 71 | ...agent, 72 | updatedAt: Date.now(), 73 | }); 74 | router.back(); 75 | } catch (error) { 76 | Alert.alert('Error', 'Failed to save agent'); 77 | } 78 | }; 79 | 80 | return ( 81 | <> 82 | ( 86 | router.back()} 88 | hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }} 89 | style={({ pressed }) => [ 90 | styles.headerButton, 91 | pressed && styles.headerButtonPressed, 92 | isDarkMode && styles.darkHeaderButton, 93 | ]} 94 | > 95 | 100 | 101 | ), 102 | headerRight: () => ( 103 | [ 107 | styles.headerButton, 108 | pressed && styles.headerButtonPressed, 109 | isDarkMode && styles.darkHeaderButton, 110 | ]} 111 | > 112 | Save 116 | 117 | ), 118 | }} 119 | /> 120 | 127 | 128 | 129 | setShowIconPicker(true)} 132 | > 133 | 134 | 135 | setShowColorPicker(true)} 138 | > 139 | Change Color 140 | 141 | 142 | 143 | Name 144 | setAgent({ ...agent, name })} 151 | placeholder="Enter agent name" 152 | placeholderTextColor={isDarkMode ? '#666666' : '#999999'} 153 | /> 154 | 155 | Description 156 | setAgent({ ...agent, description })} 164 | placeholder="Describe what this agent does" 165 | placeholderTextColor={isDarkMode ? '#666666' : '#999999'} 166 | multiline 167 | numberOfLines={3} 168 | /> 169 | 170 | System Prompt 171 | setAgent({ ...agent, systemPrompt })} 179 | placeholder="Enter the system prompt that defines this agent's behavior" 180 | placeholderTextColor={isDarkMode ? '#666666' : '#999999'} 181 | multiline 182 | numberOfLines={5} 183 | /> 184 | 185 | {showColorPicker && ( 186 | 190 | Select Color 194 | 195 | {COLORS.map(color => ( 196 | { 200 | setAgent({ ...agent, color }); 201 | setShowColorPicker(false); 202 | }} 203 | /> 204 | ))} 205 | 206 | 207 | )} 208 | 209 | {showIconPicker && ( 210 | 214 | Select Icon 218 | 219 | {ICONS.map(icon => ( 220 | { 227 | setAgent({ ...agent, icon }); 228 | setShowIconPicker(false); 229 | }} 230 | > 231 | 236 | 237 | ))} 238 | 239 | 240 | )} 241 | 242 | 243 | 244 | ); 245 | } 246 | 247 | const styles = StyleSheet.create({ 248 | container: { 249 | flex: 1, 250 | backgroundColor: '#FFFFFF', 251 | }, 252 | darkContainer: { 253 | backgroundColor: '#000000', 254 | }, 255 | content: { 256 | flex: 1, 257 | padding: 16, 258 | }, 259 | header: { 260 | flexDirection: 'row', 261 | alignItems: 'center', 262 | marginBottom: 24, 263 | }, 264 | iconContainer: { 265 | width: 48, 266 | height: 48, 267 | borderRadius: 24, 268 | justifyContent: 'center', 269 | alignItems: 'center', 270 | marginRight: 16, 271 | }, 272 | colorButton: { 273 | paddingHorizontal: 16, 274 | paddingVertical: 8, 275 | borderRadius: 8, 276 | }, 277 | colorButtonText: { 278 | color: '#FFFFFF', 279 | fontSize: 14, 280 | fontWeight: '600', 281 | }, 282 | label: { 283 | fontSize: 16, 284 | fontWeight: '600', 285 | color: '#000000', 286 | marginBottom: 8, 287 | }, 288 | darkLabel: { 289 | color: '#FFFFFF', 290 | }, 291 | input: { 292 | backgroundColor: '#F5F5F5', 293 | borderRadius: 8, 294 | padding: 12, 295 | fontSize: 16, 296 | color: '#000000', 297 | marginBottom: 16, 298 | }, 299 | darkInput: { 300 | backgroundColor: '#1C1C1E', 301 | color: '#FFFFFF', 302 | }, 303 | textArea: { 304 | height: 100, 305 | textAlignVertical: 'top', 306 | }, 307 | pickerContainer: { 308 | marginTop: 16, 309 | padding: 16, 310 | backgroundColor: '#F5F5F5', 311 | borderRadius: 12, 312 | }, 313 | darkPickerContainer: { 314 | backgroundColor: '#1C1C1E', 315 | }, 316 | pickerTitle: { 317 | fontSize: 16, 318 | fontWeight: '600', 319 | color: '#000000', 320 | marginBottom: 16, 321 | }, 322 | colorGrid: { 323 | flexDirection: 'row', 324 | flexWrap: 'wrap', 325 | gap: 12, 326 | }, 327 | colorOption: { 328 | width: 40, 329 | height: 40, 330 | borderRadius: 20, 331 | }, 332 | iconGrid: { 333 | flexDirection: 'row', 334 | flexWrap: 'wrap', 335 | gap: 16, 336 | }, 337 | iconOption: { 338 | width: 48, 339 | height: 48, 340 | borderRadius: 24, 341 | backgroundColor: '#FFFFFF', 342 | justifyContent: 'center', 343 | alignItems: 'center', 344 | }, 345 | darkIconOption: { 346 | backgroundColor: '#2C2C2E', 347 | }, 348 | headerButton: { 349 | padding: 8, 350 | marginHorizontal: 8, 351 | borderRadius: 8, 352 | backgroundColor: '#F5F5F5', 353 | }, 354 | darkHeaderButton: { 355 | backgroundColor: '#1C1C1E', 356 | }, 357 | headerButtonPressed: { 358 | opacity: 0.7, 359 | }, 360 | saveButtonText: { 361 | fontSize: 16, 362 | fontWeight: '600', 363 | color: '#6B4EFF', 364 | }, 365 | darkSaveButtonText: { 366 | color: '#6B4EFF', 367 | }, 368 | }); -------------------------------------------------------------------------------- /app/(tabs)/settings.tsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from 'react'; 2 | import { 3 | View, 4 | Text, 5 | TextInput, 6 | StyleSheet, 7 | ScrollView, 8 | Pressable, 9 | Alert, 10 | Switch, 11 | Linking, 12 | KeyboardAvoidingView, 13 | Platform, 14 | } from 'react-native'; 15 | import AsyncStorage from '@react-native-async-storage/async-storage'; 16 | import { StatusBar } from 'expo-status-bar'; 17 | import { MaterialIcons } from '@expo/vector-icons'; 18 | import { DEFAULT_SYSTEM_PROMPT } from '@/constants/Config'; 19 | import { useTheme } from '@/contexts/ThemeContext'; 20 | import { SafeAreaView } from 'react-native-safe-area-context'; 21 | 22 | const API_KEY_STORAGE_KEY = '@gemini_api_key'; 23 | const SYSTEM_PROMPT_STORAGE_KEY = '@gemini_system_prompt'; 24 | const THEME_STORAGE_KEY = '@gemini_theme'; 25 | const STREAM_RESPONSE_KEY = '@gemini_stream_response'; 26 | const CODE_HIGHLIGHT_KEY = '@gemini_code_highlight'; 27 | 28 | export default function SettingsScreen() { 29 | const { isDarkMode, setIsDarkMode } = useTheme(); 30 | const [apiKey, setApiKey] = useState(''); 31 | const [systemPrompt, setSystemPrompt] = useState(DEFAULT_SYSTEM_PROMPT); 32 | const [streamResponse, setStreamResponse] = useState(true); 33 | const [highlightCode, setHighlightCode] = useState(true); 34 | const [isSaving, setIsSaving] = useState(false); 35 | 36 | useEffect(() => { 37 | loadSettings(); 38 | }, []); 39 | 40 | const loadSettings = async () => { 41 | try { 42 | const [ 43 | savedApiKey, 44 | savedSystemPrompt, 45 | savedStreamResponse, 46 | savedHighlightCode, 47 | ] = await Promise.all([ 48 | AsyncStorage.getItem(API_KEY_STORAGE_KEY), 49 | AsyncStorage.getItem(SYSTEM_PROMPT_STORAGE_KEY), 50 | AsyncStorage.getItem(STREAM_RESPONSE_KEY), 51 | AsyncStorage.getItem(CODE_HIGHLIGHT_KEY), 52 | ]); 53 | 54 | if (savedApiKey) setApiKey(savedApiKey); 55 | if (savedSystemPrompt) setSystemPrompt(savedSystemPrompt); 56 | if (savedStreamResponse) setStreamResponse(savedStreamResponse === 'true'); 57 | if (savedHighlightCode) setHighlightCode(savedHighlightCode === 'true'); 58 | } catch (error) { 59 | console.error('Error loading settings:', error); 60 | Alert.alert('Error', 'Failed to load settings'); 61 | } 62 | }; 63 | 64 | const handleSave = async () => { 65 | if (!apiKey.trim()) { 66 | Alert.alert('Error', 'API Key is required'); 67 | return; 68 | } 69 | 70 | setIsSaving(true); 71 | try { 72 | await Promise.all([ 73 | AsyncStorage.setItem(API_KEY_STORAGE_KEY, apiKey.trim()), 74 | AsyncStorage.setItem(SYSTEM_PROMPT_STORAGE_KEY, systemPrompt.trim() || DEFAULT_SYSTEM_PROMPT), 75 | AsyncStorage.setItem(STREAM_RESPONSE_KEY, String(streamResponse)), 76 | AsyncStorage.setItem(CODE_HIGHLIGHT_KEY, String(highlightCode)), 77 | ]); 78 | Alert.alert('Success', 'Settings saved successfully'); 79 | } catch (error) { 80 | console.error('Error saving settings:', error); 81 | Alert.alert('Error', 'Failed to save settings'); 82 | } finally { 83 | setIsSaving(false); 84 | } 85 | }; 86 | 87 | const handleReset = () => { 88 | Alert.alert( 89 | 'Reset Settings', 90 | 'Are you sure you want to reset all settings to default?', 91 | [ 92 | { 93 | text: 'Cancel', 94 | style: 'cancel', 95 | }, 96 | { 97 | text: 'Reset', 98 | style: 'destructive', 99 | onPress: async () => { 100 | try { 101 | await Promise.all([ 102 | AsyncStorage.removeItem(API_KEY_STORAGE_KEY), 103 | AsyncStorage.removeItem(SYSTEM_PROMPT_STORAGE_KEY), 104 | AsyncStorage.removeItem(STREAM_RESPONSE_KEY), 105 | AsyncStorage.removeItem(CODE_HIGHLIGHT_KEY), 106 | ]); 107 | setApiKey(''); 108 | setSystemPrompt(DEFAULT_SYSTEM_PROMPT); 109 | setIsDarkMode(false); 110 | setStreamResponse(true); 111 | setHighlightCode(true); 112 | Alert.alert('Success', 'Settings reset successfully'); 113 | } catch (error) { 114 | console.error('Error resetting settings:', error); 115 | Alert.alert('Error', 'Failed to reset settings'); 116 | } 117 | }, 118 | }, 119 | ] 120 | ); 121 | }; 122 | 123 | const handleGetApiKey = () => { 124 | Linking.openURL('https://makersuite.google.com/app/apikey'); 125 | }; 126 | 127 | return ( 128 | 129 | 130 | 134 | 140 | 141 | API Key 142 | 143 | 153 | 157 | Get API Key 158 | 159 | 160 | 161 | 162 | 163 | System Prompt 164 | 173 | 174 | 175 | 176 | 177 | 178 | Dark Mode 179 | 180 | Enable dark theme for the app 181 | 182 | 183 | 189 | 190 | 191 | 192 | 193 | Stream Response 194 | 195 | Show AI responses as they are generated 196 | 197 | 198 | 204 | 205 | 206 | 207 | 208 | Code Highlighting 209 | 210 | Enable syntax highlighting for code blocks 211 | 212 | 213 | 219 | 220 | 221 | 222 | 223 | 228 | 229 | {isSaving ? 'Saving...' : 'Save Settings'} 230 | 231 | 232 | 233 | 237 | 238 | Reset to Default 239 | 240 | 241 | 242 | 243 | 244 | 245 | ); 246 | } 247 | 248 | const styles = StyleSheet.create({ 249 | container: { 250 | flex: 1, 251 | backgroundColor: '#FFFFFF', 252 | }, 253 | darkContainer: { 254 | backgroundColor: '#000000', 255 | }, 256 | keyboardAvoidingView: { 257 | flex: 1, 258 | }, 259 | scrollView: { 260 | flex: 1, 261 | }, 262 | scrollViewContent: { 263 | padding: 16, 264 | paddingBottom: Platform.OS === 'ios' ? 100 : 80, // Extra padding for bottom tab bar 265 | }, 266 | section: { 267 | marginBottom: 24, 268 | }, 269 | label: { 270 | color: '#000000', 271 | fontSize: 16, 272 | fontWeight: '600', 273 | marginBottom: 8, 274 | }, 275 | darkLabel: { 276 | color: '#FFFFFF', 277 | }, 278 | apiKeyContainer: { 279 | flexDirection: 'row', 280 | gap: 8, 281 | }, 282 | input: { 283 | flex: 1, 284 | backgroundColor: '#F5F5F5', 285 | borderRadius: 8, 286 | padding: 12, 287 | color: '#000000', 288 | fontSize: 16, 289 | }, 290 | darkInput: { 291 | backgroundColor: '#1C1C1E', 292 | color: '#FFFFFF', 293 | }, 294 | getApiKeyButton: { 295 | backgroundColor: '#F5F5F5', 296 | borderRadius: 8, 297 | padding: 12, 298 | justifyContent: 'center', 299 | }, 300 | darkButton: { 301 | backgroundColor: '#1C1C1E', 302 | }, 303 | getApiKeyText: { 304 | color: '#6B4EFF', 305 | fontSize: 14, 306 | fontWeight: '600', 307 | }, 308 | darkButtonText: { 309 | color: '#6B4EFF', 310 | }, 311 | textArea: { 312 | height: 100, 313 | textAlignVertical: 'top', 314 | }, 315 | settingRow: { 316 | flexDirection: 'row', 317 | alignItems: 'center', 318 | justifyContent: 'space-between', 319 | paddingVertical: 12, 320 | borderBottomWidth: StyleSheet.hairlineWidth, 321 | borderBottomColor: '#E5E5E5', 322 | }, 323 | settingInfo: { 324 | flex: 1, 325 | marginRight: 16, 326 | }, 327 | settingLabel: { 328 | fontSize: 16, 329 | fontWeight: '600', 330 | color: '#000000', 331 | marginBottom: 4, 332 | }, 333 | settingDescription: { 334 | fontSize: 14, 335 | color: '#666666', 336 | }, 337 | darkDescription: { 338 | color: '#999999', 339 | }, 340 | buttonContainer: { 341 | gap: 12, 342 | marginTop: 24, 343 | }, 344 | button: { 345 | borderRadius: 8, 346 | padding: 16, 347 | alignItems: 'center', 348 | }, 349 | saveButton: { 350 | backgroundColor: '#6B4EFF', 351 | }, 352 | darkSaveButton: { 353 | backgroundColor: '#6B4EFF', 354 | }, 355 | resetButton: { 356 | backgroundColor: 'transparent', 357 | borderWidth: 1, 358 | borderColor: '#FF3B30', 359 | }, 360 | darkResetButton: { 361 | borderColor: '#FF453A', 362 | }, 363 | buttonText: { 364 | color: '#FFFFFF', 365 | fontSize: 16, 366 | fontWeight: '600', 367 | }, 368 | resetButtonText: { 369 | color: '#FF3B30', 370 | }, 371 | darkResetButtonText: { 372 | color: '#FF453A', 373 | }, 374 | }); -------------------------------------------------------------------------------- /app/(tabs)/discover.tsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from 'react'; 2 | import { 3 | View, 4 | Text, 5 | StyleSheet, 6 | FlatList, 7 | Pressable, 8 | TextInput, 9 | Share, 10 | Alert, 11 | ActivityIndicator, 12 | } from 'react-native'; 13 | import { SafeAreaView } from 'react-native-safe-area-context'; 14 | import { MaterialIcons } from '@expo/vector-icons'; 15 | import AsyncStorage from '@react-native-async-storage/async-storage'; 16 | import { generateCompletion } from '@/utils/gemini'; 17 | import { nanoid } from 'nanoid/non-secure'; 18 | import { useTheme } from '@/contexts/ThemeContext'; 19 | 20 | const DISCOVER_STORAGE_KEY = '@gemini_discover'; 21 | const API_KEY_STORAGE_KEY = '@gemini_api_key'; 22 | 23 | interface DiscoverItem { 24 | id: string; 25 | prompt: string; 26 | content: string; 27 | type: 'story' | 'poem' | 'joke' | 'quote'; 28 | createdAt: number; 29 | likes: number; 30 | } 31 | 32 | const CONTENT_TYPES = [ 33 | { id: 'story', name: 'Story', icon: 'auto-stories', prompt: 'Write a creative short story about' }, 34 | { id: 'poem', name: 'Poem', icon: 'format-quote', prompt: 'Write a poem about' }, 35 | { id: 'joke', name: 'Joke', icon: 'mood', prompt: 'Tell a funny joke about' }, 36 | { id: 'quote', name: 'Quote', icon: 'format-quote', prompt: 'Generate an inspirational quote about' }, 37 | ]; 38 | 39 | export default function DiscoverScreen() { 40 | const { isDarkMode } = useTheme(); 41 | const [items, setItems] = useState([]); 42 | const [selectedType, setSelectedType] = useState(CONTENT_TYPES[0]); 43 | const [prompt, setPrompt] = useState(''); 44 | const [isLoading, setIsLoading] = useState(false); 45 | const [apiKey, setApiKey] = useState(null); 46 | 47 | useEffect(() => { 48 | loadApiKey(); 49 | loadItems(); 50 | }, []); 51 | 52 | const loadApiKey = async () => { 53 | try { 54 | const savedApiKey = await AsyncStorage.getItem(API_KEY_STORAGE_KEY); 55 | setApiKey(savedApiKey); 56 | } catch (error) { 57 | console.error('Error loading API key:', error); 58 | } 59 | }; 60 | 61 | const loadItems = async () => { 62 | try { 63 | const savedItems = await AsyncStorage.getItem(DISCOVER_STORAGE_KEY); 64 | if (savedItems) { 65 | setItems(JSON.parse(savedItems)); 66 | } 67 | } catch (error) { 68 | console.error('Error loading items:', error); 69 | } 70 | }; 71 | 72 | const saveItems = async (newItems: DiscoverItem[]) => { 73 | try { 74 | await AsyncStorage.setItem(DISCOVER_STORAGE_KEY, JSON.stringify(newItems)); 75 | } catch (error) { 76 | console.error('Error saving items:', error); 77 | } 78 | }; 79 | 80 | const handleGenerate = async () => { 81 | if (!prompt.trim() || !apiKey) return; 82 | 83 | setIsLoading(true); 84 | try { 85 | const fullPrompt = `${selectedType.prompt} ${prompt.trim()}`; 86 | const content = await generateCompletion([ 87 | { role: 'user', content: fullPrompt } 88 | ]); 89 | 90 | const newItem: DiscoverItem = { 91 | id: nanoid(), 92 | prompt: prompt.trim(), 93 | content, 94 | type: selectedType.id as any, 95 | createdAt: Date.now(), 96 | likes: 0, 97 | }; 98 | 99 | const updatedItems = [newItem, ...items]; 100 | setItems(updatedItems); 101 | saveItems(updatedItems); 102 | setPrompt(''); 103 | } catch (error) { 104 | console.error('Error generating content:', error); 105 | Alert.alert('Error', 'Failed to generate content'); 106 | } finally { 107 | setIsLoading(false); 108 | } 109 | }; 110 | 111 | const handleShare = async (item: DiscoverItem) => { 112 | try { 113 | await Share.share({ 114 | message: `${item.content}\n\nGenerated by Gemini Pro`, 115 | }); 116 | } catch (error) { 117 | console.error('Error sharing content:', error); 118 | } 119 | }; 120 | 121 | const handleLike = (id: string) => { 122 | const updatedItems = items.map(item => 123 | item.id === id ? { ...item, likes: item.likes + 1 } : item 124 | ); 125 | setItems(updatedItems); 126 | saveItems(updatedItems); 127 | }; 128 | 129 | const renderItem = ({ item }: { item: DiscoverItem }) => ( 130 | 131 | 132 | t.id === item.type)?.icon as any} 134 | size={24} 135 | color={isDarkMode ? '#FFFFFF' : '#000000'} 136 | /> 137 | 138 | {CONTENT_TYPES.find(t => t.id === item.type)?.name} 139 | 140 | 141 | 142 | {item.prompt} 143 | 144 | 145 | {item.content} 146 | 147 | 148 | handleLike(item.id)} 151 | > 152 | 153 | {item.likes} 154 | 155 | handleShare(item)} 158 | > 159 | 160 | 161 | 162 | 163 | ); 164 | 165 | return ( 166 | 167 | 168 | 169 | ( 174 | setSelectedType(type)} 181 | > 182 | 187 | 194 | {type.name} 195 | 196 | 197 | )} 198 | keyExtractor={type => type.id} 199 | contentContainerStyle={styles.typeButtonsContent} 200 | /> 201 | 202 | 203 | 213 | 222 | {isLoading ? ( 223 | 224 | ) : ( 225 | 230 | )} 231 | 232 | 233 | 234 | item.id} 238 | contentContainerStyle={styles.listContent} 239 | ListEmptyComponent={() => ( 240 | 241 | 246 | 247 | No Content Yet 248 | 249 | 250 | Generate some amazing content to share with others 251 | 252 | 253 | )} 254 | /> 255 | 256 | ); 257 | } 258 | 259 | const styles = StyleSheet.create({ 260 | container: { 261 | flex: 1, 262 | backgroundColor: '#FFFFFF', 263 | }, 264 | darkContainer: { 265 | backgroundColor: '#000000', 266 | }, 267 | inputContainer: { 268 | padding: 16, 269 | borderBottomWidth: StyleSheet.hairlineWidth, 270 | borderBottomColor: '#E5E5E5', 271 | backgroundColor: '#FFFFFF', 272 | }, 273 | darkInputContainer: { 274 | backgroundColor: '#000000', 275 | borderBottomColor: '#333333', 276 | }, 277 | typeButtons: { 278 | marginBottom: 16, 279 | }, 280 | typeButtonsContent: { 281 | paddingHorizontal: 16, 282 | }, 283 | typeButton: { 284 | flexDirection: 'row', 285 | alignItems: 'center', 286 | paddingHorizontal: 16, 287 | paddingVertical: 8, 288 | borderRadius: 20, 289 | backgroundColor: '#F5F5F5', 290 | marginRight: 8, 291 | }, 292 | darkTypeButton: { 293 | backgroundColor: '#1C1C1E', 294 | }, 295 | selectedTypeButton: { 296 | backgroundColor: '#6B4EFF', 297 | }, 298 | typeButtonText: { 299 | marginLeft: 4, 300 | fontSize: 14, 301 | fontWeight: '600', 302 | color: '#000000', 303 | }, 304 | selectedTypeButtonText: { 305 | color: '#FFFFFF', 306 | }, 307 | darkText: { 308 | color: '#FFFFFF', 309 | }, 310 | promptContainer: { 311 | flexDirection: 'row', 312 | alignItems: 'flex-end', 313 | }, 314 | input: { 315 | flex: 1, 316 | backgroundColor: '#F5F5F5', 317 | borderRadius: 20, 318 | paddingHorizontal: 16, 319 | paddingTop: 12, 320 | paddingBottom: 12, 321 | marginRight: 8, 322 | color: '#000000', 323 | fontSize: 16, 324 | maxHeight: 100, 325 | }, 326 | darkInput: { 327 | backgroundColor: '#1C1C1E', 328 | color: '#FFFFFF', 329 | }, 330 | generateButton: { 331 | width: 44, 332 | height: 44, 333 | borderRadius: 22, 334 | backgroundColor: '#6B4EFF', 335 | justifyContent: 'center', 336 | alignItems: 'center', 337 | }, 338 | generateButtonDisabled: { 339 | backgroundColor: '#F5F5F5', 340 | }, 341 | darkGenerateButton: { 342 | backgroundColor: '#1C1C1E', 343 | }, 344 | listContent: { 345 | padding: 16, 346 | }, 347 | itemCard: { 348 | backgroundColor: '#FFFFFF', 349 | borderRadius: 12, 350 | padding: 16, 351 | marginBottom: 16, 352 | borderWidth: 1, 353 | borderColor: '#E5E5E5', 354 | }, 355 | darkItemCard: { 356 | backgroundColor: '#1C1C1E', 357 | borderColor: '#333333', 358 | }, 359 | itemHeader: { 360 | flexDirection: 'row', 361 | alignItems: 'center', 362 | marginBottom: 8, 363 | }, 364 | itemType: { 365 | fontSize: 16, 366 | fontWeight: '600', 367 | color: '#000000', 368 | marginLeft: 8, 369 | }, 370 | itemPrompt: { 371 | fontSize: 14, 372 | color: '#666666', 373 | marginBottom: 8, 374 | }, 375 | itemContent: { 376 | fontSize: 16, 377 | color: '#000000', 378 | lineHeight: 24, 379 | }, 380 | itemActions: { 381 | flexDirection: 'row', 382 | justifyContent: 'flex-end', 383 | marginTop: 16, 384 | gap: 8, 385 | }, 386 | actionButton: { 387 | flexDirection: 'row', 388 | alignItems: 'center', 389 | padding: 8, 390 | borderRadius: 20, 391 | backgroundColor: '#F5F5F5', 392 | gap: 4, 393 | }, 394 | darkActionButton: { 395 | backgroundColor: '#2C2C2E', 396 | }, 397 | actionText: { 398 | fontSize: 14, 399 | fontWeight: '600', 400 | }, 401 | emptyState: { 402 | alignItems: 'center', 403 | justifyContent: 'center', 404 | padding: 16, 405 | marginTop: 100, 406 | }, 407 | emptyStateTitle: { 408 | fontSize: 20, 409 | fontWeight: '600', 410 | color: '#000000', 411 | marginTop: 16, 412 | marginBottom: 8, 413 | }, 414 | emptyStateDescription: { 415 | fontSize: 16, 416 | color: '#666666', 417 | textAlign: 'center', 418 | }, 419 | darkEmptyStateDescription: { 420 | color: '#999999', 421 | }, 422 | }); -------------------------------------------------------------------------------- /app/(tabs)/index.tsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect, useRef } from 'react'; 2 | import { 3 | View, 4 | TextInput, 5 | StyleSheet, 6 | FlatList, 7 | KeyboardAvoidingView, 8 | Platform, 9 | Pressable, 10 | ActivityIndicator, 11 | Keyboard, 12 | TouchableWithoutFeedback, 13 | Text, 14 | Alert, 15 | Image, 16 | } from 'react-native'; 17 | import { StatusBar } from 'expo-status-bar'; 18 | import { MaterialIcons } from '@expo/vector-icons'; 19 | import { useLocalSearchParams, useRouter, Stack } from 'expo-router'; 20 | import { SafeAreaView } from 'react-native-safe-area-context'; 21 | import { Message } from '@/components/Message'; 22 | import { Chat, Message as MessageType, Agent } from '@/constants/Config'; 23 | import { streamCompletion } from '@/utils/gemini'; 24 | import { saveChat, loadChats, updateMessage, loadAgents } from '@/utils/storage'; 25 | import { nanoid } from 'nanoid/non-secure'; 26 | import AsyncStorage from '@react-native-async-storage/async-storage'; 27 | import * as Clipboard from 'expo-clipboard'; 28 | import { useTheme } from '@/contexts/ThemeContext'; 29 | import * as ImagePicker from 'expo-image-picker'; 30 | 31 | const API_KEY_STORAGE_KEY = '@gemini_api_key'; 32 | 33 | type ChatMessage = { 34 | role: 'user' | 'system' | 'assistant'; 35 | content: string; 36 | image?: string | null; 37 | }; 38 | 39 | export default function ChatScreen() { 40 | const { agentId, chatId } = useLocalSearchParams<{ agentId: string; chatId: string }>(); 41 | const router = useRouter(); 42 | const [messages, setMessages] = useState([]); 43 | const [inputText, setInputText] = useState(''); 44 | const [isLoading, setIsLoading] = useState(false); 45 | const [currentChat, setCurrentChat] = useState(null); 46 | const [currentAgent, setCurrentAgent] = useState(null); 47 | const [apiKey, setApiKey] = useState(null); 48 | const flatListRef = useRef(null); 49 | const { isDarkMode } = useTheme(); 50 | const [selectedImage, setSelectedImage] = useState(null); 51 | 52 | useEffect(() => { 53 | loadApiKey(); 54 | if (chatId) { 55 | loadExistingChat(); 56 | } else if (agentId) { 57 | loadAgentAndChat(); 58 | } else { 59 | loadDefaultAgentAndChat(); 60 | } 61 | }, [agentId, chatId]); 62 | 63 | const loadApiKey = async () => { 64 | try { 65 | const savedApiKey = await AsyncStorage.getItem(API_KEY_STORAGE_KEY); 66 | setApiKey(savedApiKey); 67 | } catch (error) { 68 | console.error('Error loading API key:', error); 69 | } 70 | }; 71 | 72 | const loadExistingChat = async () => { 73 | try { 74 | const chats = await loadChats(); 75 | const chat = chats.find(c => c.id === chatId); 76 | if (!chat) { 77 | Alert.alert('Error', 'Chat not found'); 78 | return; 79 | } 80 | 81 | const agents = await loadAgents(); 82 | const agent = agents.find(a => a.id === chat.agentId); 83 | if (!agent) { 84 | Alert.alert('Error', 'Agent not found'); 85 | return; 86 | } 87 | 88 | setCurrentChat(chat); 89 | setCurrentAgent(agent); 90 | setMessages(chat.messages); 91 | } catch (error) { 92 | console.error('Error loading chat:', error); 93 | Alert.alert('Error', 'Failed to load chat'); 94 | } 95 | }; 96 | 97 | const loadAgentAndChat = async () => { 98 | try { 99 | // 加载 Agent 100 | const agents = await loadAgents(); 101 | const agent = agents.find(a => a.id === agentId); 102 | if (!agent) { 103 | Alert.alert('Error', 'Agent not found'); 104 | return; 105 | } 106 | setCurrentAgent(agent); 107 | 108 | // 加载或创建聊天 109 | const chats = await loadChats(); 110 | let chat = chats.find(c => c.agentId === agentId); 111 | 112 | if (!chat) { 113 | chat = { 114 | id: nanoid(), 115 | title: `Chat with ${agent.name}`, 116 | messages: [], 117 | systemPrompt: agent.systemPrompt, 118 | createdAt: Date.now(), 119 | updatedAt: Date.now(), 120 | agentId: agent.id, 121 | }; 122 | await saveChat(chat); 123 | } 124 | 125 | setCurrentChat(chat); 126 | setMessages(chat.messages); 127 | } catch (error) { 128 | console.error('Error loading agent and chat:', error); 129 | Alert.alert('Error', 'Failed to load chat'); 130 | } 131 | }; 132 | 133 | const loadDefaultAgentAndChat = async () => { 134 | try { 135 | // 加载默认 Agent 136 | const agents = await loadAgents(); 137 | const defaultAgent = agents.find(a => a.id === 'default-chat'); 138 | if (!defaultAgent) { 139 | Alert.alert('Error', 'Default agent not found'); 140 | return; 141 | } 142 | setCurrentAgent(defaultAgent); 143 | 144 | // 加载或创建默认聊天 145 | const chats = await loadChats(); 146 | let chat = chats.find(c => c.agentId === defaultAgent.id); 147 | 148 | if (!chat) { 149 | chat = { 150 | id: nanoid(), 151 | title: `Chat with ${defaultAgent.name}`, 152 | messages: [], 153 | systemPrompt: defaultAgent.systemPrompt, 154 | createdAt: Date.now(), 155 | updatedAt: Date.now(), 156 | agentId: defaultAgent.id, 157 | }; 158 | await saveChat(chat); 159 | } 160 | 161 | setCurrentChat(chat); 162 | setMessages(chat.messages); 163 | } catch (error) { 164 | console.error('Error loading default agent and chat:', error); 165 | Alert.alert('Error', 'Failed to load chat'); 166 | } 167 | }; 168 | 169 | const pickImage = async () => { 170 | const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync(); 171 | if (status !== 'granted') { 172 | Alert.alert('Permission needed', 'Sorry, we need camera roll permissions to make this work!'); 173 | return; 174 | } 175 | 176 | const result = await ImagePicker.launchImageLibraryAsync({ 177 | mediaTypes: ImagePicker.MediaTypeOptions.Images, 178 | allowsEditing: true, 179 | aspect: [4, 3], 180 | quality: 1, 181 | }); 182 | 183 | if (!result.canceled) { 184 | setSelectedImage(result.assets[0].uri); 185 | } 186 | }; 187 | 188 | const handleSend = async () => { 189 | if ((!inputText.trim() && !selectedImage) || !currentChat || !currentAgent || !apiKey) return; 190 | 191 | const userMessage: MessageType = { 192 | id: nanoid(), 193 | role: 'user', 194 | content: inputText.trim(), 195 | timestamp: Date.now(), 196 | image: selectedImage, 197 | }; 198 | 199 | const updatedMessages = [...messages, userMessage]; 200 | setMessages(updatedMessages); 201 | setInputText(''); 202 | setSelectedImage(null); 203 | setIsLoading(true); 204 | Keyboard.dismiss(); 205 | 206 | try { 207 | let responseContent = ''; 208 | const assistantMessage: MessageType = { 209 | id: nanoid(), 210 | role: 'assistant', 211 | content: '', 212 | timestamp: Date.now(), 213 | }; 214 | 215 | setMessages(prev => [...prev, assistantMessage]); 216 | 217 | // 构建发送给模型的消息 218 | const messagesToSend = [ 219 | { role: 'system', content: currentAgent.systemPrompt }, 220 | ...updatedMessages.map(m => ({ 221 | role: m.role, 222 | content: m.content, 223 | image: m.image, 224 | })) 225 | ]; 226 | 227 | await streamCompletion( 228 | messagesToSend, 229 | (chunk) => { 230 | responseContent += chunk; 231 | setMessages(prev => { 232 | const updated = [...prev]; 233 | updated[updated.length - 1] = { 234 | ...updated[updated.length - 1], 235 | content: responseContent, 236 | }; 237 | return updated; 238 | }); 239 | }, 240 | (error) => { 241 | console.error('Error in stream:', error); 242 | setIsLoading(false); 243 | setMessages(prevMessages => prevMessages.slice(0, -1)); // Remove the failed assistant message 244 | Alert.alert('Error', 'Failed to get response from AI'); 245 | }, 246 | async () => { 247 | setIsLoading(false); 248 | const updatedChat: Chat = { 249 | ...currentChat, 250 | messages: [...updatedMessages, { ...assistantMessage, content: responseContent }], 251 | updatedAt: Date.now(), 252 | }; 253 | await saveChat(updatedChat); 254 | setCurrentChat(updatedChat); 255 | } 256 | ); 257 | } catch (error) { 258 | console.error('Error sending message:', error); 259 | setIsLoading(false); 260 | setMessages(prevMessages => prevMessages.slice(0, -1)); // Remove the failed assistant message 261 | Alert.alert('Error', 'Failed to send message'); 262 | } 263 | }; 264 | 265 | const handleEditMessage = async (messageId: string, newContent: string) => { 266 | if (!currentChat) return; 267 | 268 | try { 269 | await updateMessage(currentChat.id, messageId, newContent); 270 | setMessages(messages.map(msg => 271 | msg.id === messageId 272 | ? { ...msg, content: newContent, isEdited: true } 273 | : msg 274 | )); 275 | } catch (error) { 276 | console.error('Error updating message:', error); 277 | Alert.alert('Error', 'Failed to update message'); 278 | } 279 | }; 280 | 281 | const handleRegenerateMessage = async (messageId: string) => { 282 | if (!currentChat || !currentAgent) return; 283 | 284 | const messageIndex = messages.findIndex(m => m.id === messageId); 285 | if (messageIndex === -1) return; 286 | 287 | // Get all messages up to the message we want to regenerate 288 | const previousMessages = messages.slice(0, messageIndex); 289 | setIsLoading(true); 290 | 291 | try { 292 | let responseContent = ''; 293 | await streamCompletion( 294 | [ 295 | { role: 'system', content: currentAgent.systemPrompt }, 296 | ...previousMessages.map(m => ({ role: m.role, content: m.content })) 297 | ], 298 | (chunk) => { 299 | responseContent += chunk; 300 | setMessages(prev => { 301 | const updated = [...prev]; 302 | updated[messageIndex] = { 303 | ...updated[messageIndex], 304 | content: responseContent, 305 | isEdited: true, 306 | }; 307 | return updated; 308 | }); 309 | }, 310 | (error) => { 311 | console.error('Error in stream:', error); 312 | setIsLoading(false); 313 | Alert.alert('Error', 'Failed to regenerate response'); 314 | }, 315 | () => { 316 | setIsLoading(false); 317 | } 318 | ); 319 | 320 | const updatedChat: Chat = { 321 | ...currentChat, 322 | messages: messages.map((msg, index) => 323 | index === messageIndex 324 | ? { ...msg, content: responseContent, isEdited: true } 325 | : msg 326 | ), 327 | updatedAt: Date.now(), 328 | }; 329 | await saveChat(updatedChat); 330 | setCurrentChat(updatedChat); 331 | } catch (error) { 332 | console.error('Error regenerating message:', error); 333 | setIsLoading(false); 334 | Alert.alert('Error', 'Failed to regenerate message'); 335 | } 336 | }; 337 | 338 | const handleCopyMessage = async (content: string) => { 339 | try { 340 | await Clipboard.setStringAsync(content); 341 | } catch (error) { 342 | console.error('Error copying message:', error); 343 | Alert.alert('Error', 'Failed to copy message'); 344 | } 345 | }; 346 | 347 | const handleNewChat = () => { 348 | if (!currentAgent) return; 349 | 350 | const newChat: Chat = { 351 | id: nanoid(), 352 | title: `Chat with ${currentAgent.name}`, 353 | messages: [], 354 | systemPrompt: currentAgent.systemPrompt, 355 | createdAt: Date.now(), 356 | updatedAt: Date.now(), 357 | agentId: currentAgent.id, 358 | }; 359 | 360 | setCurrentChat(newChat); 361 | setMessages([]); 362 | saveChat(newChat); 363 | }; 364 | 365 | const renderEmptyState = () => ( 366 | 367 | 372 | 373 | {currentAgent?.name || 'Chat Assistant'} 374 | 375 | 376 | {currentAgent?.description || 'Start a conversation!'} 377 | 378 | 379 | ); 380 | 381 | return ( 382 | <> 383 | ( 386 | router.push('/chats')} 388 | style={({ pressed }) => [ 389 | styles.headerButton, 390 | pressed && styles.headerButtonPressed, 391 | isDarkMode && styles.darkHeaderButton, 392 | ]} 393 | > 394 | 395 | 396 | ), 397 | }} 398 | /> 399 | 400 | 401 | 406 | item.id} 410 | renderItem={({ item }) => ( 411 | 417 | )} 418 | style={styles.messageList} 419 | contentContainerStyle={[ 420 | styles.messageListContent, 421 | messages.length === 0 && styles.emptyList, 422 | ]} 423 | onContentSizeChange={() => flatListRef.current?.scrollToEnd()} 424 | onLayout={() => flatListRef.current?.scrollToEnd()} 425 | ListEmptyComponent={renderEmptyState} 426 | keyboardDismissMode="interactive" 427 | keyboardShouldPersistTaps="handled" 428 | /> 429 | 430 | 431 | 439 | 444 | 445 | 446 | {selectedImage && ( 447 | 451 | 456 | setSelectedImage(null)} 459 | hitSlop={8} 460 | > 461 | 462 | 463 | 464 | )} 465 | { 478 | setTimeout(() => { 479 | flatListRef.current?.scrollToEnd({ animated: true }); 480 | }, 100); 481 | }} 482 | /> 483 | 484 | 493 | {isLoading ? ( 494 | 495 | ) : ( 496 | 501 | )} 502 | 503 | 504 | 505 | 506 | 507 | 508 | ); 509 | } 510 | 511 | const styles = StyleSheet.create({ 512 | container: { 513 | flex: 1, 514 | backgroundColor: '#FFFFFF', 515 | }, 516 | darkContainer: { 517 | backgroundColor: '#000000', 518 | }, 519 | keyboardAvoidingView: { 520 | flex: 1, 521 | }, 522 | messageList: { 523 | flex: 1, 524 | }, 525 | messageListContent: { 526 | paddingVertical: 16, 527 | }, 528 | emptyList: { 529 | flexGrow: 1, 530 | }, 531 | emptyState: { 532 | flex: 1, 533 | alignItems: 'center', 534 | justifyContent: 'center', 535 | padding: 16, 536 | }, 537 | emptyStateTitle: { 538 | fontSize: 20, 539 | fontWeight: '600', 540 | color: '#000000', 541 | marginTop: 16, 542 | marginBottom: 8, 543 | }, 544 | darkEmptyStateTitle: { 545 | color: '#FFFFFF', 546 | }, 547 | emptyStateDescription: { 548 | fontSize: 16, 549 | color: '#666666', 550 | textAlign: 'center', 551 | }, 552 | darkEmptyStateDescription: { 553 | color: '#999999', 554 | }, 555 | inputContainer: { 556 | backgroundColor: '#FFFFFF', 557 | borderTopWidth: StyleSheet.hairlineWidth, 558 | borderTopColor: '#E5E5E5', 559 | paddingVertical: 12, 560 | paddingHorizontal: 16, 561 | }, 562 | darkInputContainer: { 563 | backgroundColor: '#000000', 564 | borderTopColor: '#333333', 565 | }, 566 | inputRow: { 567 | flexDirection: 'row', 568 | alignItems: 'flex-end', 569 | }, 570 | inputWrapper: { 571 | flex: 1, 572 | marginHorizontal: 8, 573 | }, 574 | input: { 575 | backgroundColor: '#F5F5F5', 576 | borderRadius: 20, 577 | paddingHorizontal: 16, 578 | paddingVertical: 12, 579 | color: '#000000', 580 | fontSize: 16, 581 | minHeight: 44, 582 | }, 583 | inputWithImage: { 584 | borderTopLeftRadius: 8, 585 | borderTopRightRadius: 8, 586 | }, 587 | darkInput: { 588 | backgroundColor: '#1C1C1E', 589 | color: '#FFFFFF', 590 | }, 591 | attachButton: { 592 | width: 44, 593 | height: 44, 594 | borderRadius: 22, 595 | backgroundColor: '#F5F5F5', 596 | justifyContent: 'center', 597 | alignItems: 'center', 598 | }, 599 | attachButtonActive: { 600 | backgroundColor: '#EDE9FF', 601 | }, 602 | darkAttachButton: { 603 | backgroundColor: '#1C1C1E', 604 | }, 605 | selectedImageContainer: { 606 | backgroundColor: '#F5F5F5', 607 | borderTopLeftRadius: 20, 608 | borderTopRightRadius: 20, 609 | padding: 8, 610 | marginBottom: -1, 611 | }, 612 | darkSelectedImageContainer: { 613 | backgroundColor: '#1C1C1E', 614 | }, 615 | selectedImage: { 616 | width: '100%', 617 | height: 150, 618 | borderRadius: 12, 619 | }, 620 | removeImageButton: { 621 | position: 'absolute', 622 | top: 16, 623 | right: 16, 624 | backgroundColor: 'rgba(0, 0, 0, 0.5)', 625 | borderRadius: 12, 626 | width: 24, 627 | height: 24, 628 | justifyContent: 'center', 629 | alignItems: 'center', 630 | }, 631 | sendButton: { 632 | width: 44, 633 | height: 44, 634 | borderRadius: 22, 635 | backgroundColor: '#6B4EFF', 636 | justifyContent: 'center', 637 | alignItems: 'center', 638 | }, 639 | sendButtonDisabled: { 640 | backgroundColor: '#F5F5F5', 641 | }, 642 | darkSendButton: { 643 | backgroundColor: '#1C1C1E', 644 | }, 645 | headerButton: { 646 | padding: 8, 647 | marginRight: 8, 648 | borderRadius: 8, 649 | backgroundColor: '#F5F5F5', 650 | }, 651 | darkHeaderButton: { 652 | backgroundColor: '#1C1C1E', 653 | }, 654 | headerButtonPressed: { 655 | opacity: 0.7, 656 | backgroundColor: '#E5E5E5', 657 | }, 658 | }); --------------------------------------------------------------------------------