@umang-thakkar/base-template 1.1.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +40 -282
  2. package/package.json +11 -2
  3. package/template/.eslintrc +16 -46
  4. package/template/.prettierrc.js +8 -0
  5. package/template/App.tsx +11 -15
  6. package/template/Main.tsx +29 -5
  7. package/template/__mocks__/react-native-mmkv.ts +59 -0
  8. package/template/__tests__/App.test.tsx +6 -1
  9. package/template/__tests__/helpers.test.ts +43 -0
  10. package/template/babel.config.js +2 -1
  11. package/template/constants/API_Routes.ts +19 -0
  12. package/template/constants/AppConstants.tsx +1 -1
  13. package/template/constants/AppString.ts +36 -0
  14. package/template/constants/StoragePreferences.ts +120 -57
  15. package/template/jest.config.js +5 -0
  16. package/template/jest.setup.js +5 -0
  17. package/template/package.json +4 -4
  18. package/template/src/api/AxiosActions.ts +65 -28
  19. package/template/src/api/AxiosClient.ts +13 -7
  20. package/template/src/api/queries.ts +59 -29
  21. package/template/src/api/service.ts +23 -9
  22. package/template/src/components/ErrorBoundary.tsx +27 -31
  23. package/template/src/components/SnackbarHost.tsx +86 -0
  24. package/template/src/helper/colors.ts +22 -22
  25. package/template/src/helper/common-functions.ts +56 -10
  26. package/template/src/helper/matrics.ts +30 -0
  27. package/template/src/helper/navigation-service.ts +21 -24
  28. package/template/src/helper/snackbar.ts +41 -0
  29. package/template/src/helper/typography.ts +2 -2
  30. package/template/src/helper/utility-functions.ts +41 -69
  31. package/template/src/hooks/ThemeContext.tsx +60 -30
  32. package/template/src/hooks/usePaginatedAPI.ts +96 -0
  33. package/template/src/navigation/AppStack.tsx +36 -27
  34. package/template/src/navigation/screens.ts +17 -11
  35. package/template/src/redux/slice.ts +17 -12
  36. package/template/src/redux/slices/authSlice.ts +11 -14
  37. package/template/src/redux/store.ts +14 -10
  38. package/template/src/redux/types.d.ts +40 -19
  39. package/template/src/screens/HomeScreen.tsx +103 -29
  40. package/template/src/screens/LoginScreen.tsx +101 -69
  41. package/template/src/screens/SplashScreen.tsx +36 -25
  42. package/template/src/theme/darkTheme.ts +13 -6
  43. package/template/src/theme/index.ts +4 -3
  44. package/template/src/theme/lightTheme.ts +13 -5
  45. package/template/ios/.xcode.env.local +0 -1
package/README.md CHANGED
@@ -1,302 +1,60 @@
1
1
  # 🚀 React Native Base Template
2
2
 
3
- A React Native boilerplate to kickstart your mobile app development faster, with preconfigured essentials like:
3
+ A React Native CLI template with the boilerplate already done: Redux Toolkit, Redux Persist on MMKV, React Navigation, React Query, Axios, light/dark theming and TypeScript. Styling uses plain `StyleSheet`.
4
4
 
5
- - 🔁 Redux Toolkit for scalable state management
6
- - 💾 Redux Persist for auth persistence across sessions
7
- - 📍 React Navigation for robust navigation
8
- - 🔗 React Query for powerful API data fetching and caching
9
- - 🌙 Dark/Light theme support with system preference detection
10
- - 🗂️ Scalable folder structure
11
- - 🧰 Common utility functions
12
- - 📦 Pre-installed useful dependencies
13
- - ⚙️ Optimized project setup for faster development
5
+ > Prefer Tailwind-style `className` styling? Use the NativeWind variant: [`@umang-thakkar/base-template-nativewind`](https://www.npmjs.com/package/@umang-thakkar/base-template-nativewind).
14
6
 
15
- ## 📦 Features
7
+ ## Quick start
16
8
 
17
- - ✅ Redux Toolkit with example slices and hooks
18
- - ✅ Redux Persist with auth slice persistence (user data + access token)
19
- - ✅ React Navigation with Stack Navigator setup
20
- - ✅ React Query for API management (see `src/api/queries.ts`)
21
- - ✅ Dark/Light theme support with automatic system detection
22
- - ✅ Organized folder structure for features, helpers, navigation, etc.
23
- - ✅ Useful helpers: debouncers, formatters, navigation service
24
- - ✅ TypeScript support
25
- - ✅ Common third-party libraries installed
26
-
27
- ## 📁 Folder Structure
28
-
29
- ```
30
- template/
31
- ├── App.tsx # Entry point
32
- ├── Main.tsx # Main app logic
33
- ├── app.json # App config
34
- ├── babel.config.js # Babel config
35
- ├── constants/ # App constants
36
- │ ├── AppConstants.tsx
37
- │ └── StoragePreferences.ts
38
- ├── __tests__/ # Test files
39
- │ └── App.test.tsx
40
- ├── android/ # Android project files
41
- ├── ios/ # iOS project files
42
- ├── src/
43
- │ ├── api/ # API clients, actions, and React Query hooks
44
- │ │ ├── AxiosActions.ts
45
- │ │ ├── AxiosClient.ts
46
- │ │ ├── queries.ts # React Query hooks and API calls
47
- │ │ └── service.ts
48
- │ ├── assets/ # Fonts, images, svg
49
- │ │ ├── fonts/
50
- │ │ ├── images/
51
- │ │ └── svg/
52
- │ ├── helper/ # Utility and helper functions
53
- │ │ ├── colors.ts
54
- │ │ ├── common-functions.ts
55
- │ │ ├── font-family.ts
56
- │ │ ├── navigation-service.ts
57
- │ │ ├── typography.ts
58
- │ │ └── utility-functions.ts
59
- │ ├── hooks/ # Custom hooks
60
- │ │ └── ThemeContext.tsx # Theme context and provider
61
- │ ├── navigation/ # Navigation setup
62
- │ │ ├── AppStack.tsx
63
- │ │ ├── AppStackParams.ts
64
- │ │ └── screens.ts
65
- │ ├── redux/ # Redux store, slices, types
66
- │ │ ├── action.ts
67
- │ │ ├── slices/
68
- │ │ │ └── authSlice.ts # Auth slice with user data + token state
69
- │ │ ├── store.ts # Store with redux-persist configuration
70
- │ │ └── types.d.ts
71
- │ ├── screens/ # App screens
72
- │ │ ├── HomeScreen.tsx
73
- │ │ ├── LoginScreen.tsx # Demo login screen — saves user + token to auth slice
74
- │ │ └── SplashScreen.tsx # Reads accessToken from Redux to decide initial route
75
- │ ├── theme/ # Theme configuration
76
- │ │ ├── darkTheme.ts # Dark theme colors
77
- │ │ ├── lightTheme.ts # Light theme colors
78
- │ │ └── index.ts # Theme exports and types
79
- ├── vendor/ # Vendor files
80
- │ └── bundle/
81
- ├── package.json # Project dependencies
82
- ├── tsconfig.json # TypeScript config
83
- └── README.md # Template README
84
- ```
85
-
86
- ## 🚀 Getting Started
87
-
88
- 1. Create a new project using this template:
89
- ```sh
90
- npx @react-native-community/cli init MyApp --template @umang-thakkar/base-template
91
- ```
92
-
93
- ```
94
- Note: Replace MyApp with your own project name.
95
- ```
96
-
97
- 2. Install dependencies:
98
- ```sh
99
- npm install
100
- ```
101
- 3. Start Metro server:
102
- ```sh
103
- npx react-native start
104
- ```
105
- 4. Run the app:
106
-
107
- ```sh
108
- # For Android
109
- npx react-native run-android
110
-
111
- # For iOS
112
- npx react-native run-ios
113
- ```
114
-
115
- > **Note**: With React Native 0.60+, iOS dependencies are automatically linked using autolinking. Manual pod installation is no longer required for most cases.
116
-
117
- ## 🧠 Usage Instructions
118
-
119
- ### 📌 Redux Toolkit
120
-
121
- - Store is configured in `src/redux/store.ts`.
122
- - Example usage:
123
- ```tsx
124
- import { useAppSelector, useAppDispatch } from "../redux/store";
125
- import { increment } from "../redux/slice";
126
- const count = useAppSelector((state) => state.counter.value);
127
- const dispatch = useAppDispatch();
128
- <Button title="Increment" onPress={() => dispatch(increment())} />;
129
- ```
130
-
131
- ### 💾 Redux Persist (Auth Persistence)
132
-
133
- Redux Persist is pre-configured in the template to persist the `auth` slice across app restarts. The user's data and `accessToken` survive kills and relaunches — no need to log in again.
134
-
135
- > `redux-persist` and `@react-native-async-storage/async-storage` are already installed and configured.
136
-
137
- **What's included out of the box:**
138
-
139
- `src/redux/slices/authSlice.ts` stores `user` and `accessToken` with the following actions:
140
-
141
- | Action | Description |
142
- | ---------------- | ---------------------------------------------- |
143
- | `setCredentials` | Sets both `user` and `accessToken` after login |
144
- | `setUser` | Updates only the `user` object |
145
- | `setAccessToken` | Updates only the `accessToken` |
146
- | `clearAuth` | Clears all auth state on logout |
147
-
148
- `src/redux/store.ts` configures `persistReducer` to persist only the `auth` slice via `AsyncStorage` and exports `persistor`.
149
-
150
- `App.tsx` wraps the app with `PersistGate` so persisted state is fully rehydrated before the UI renders.
151
-
152
- `src/screens/SplashScreen.tsx` reads `accessToken` from Redux on startup — if present, navigates to `HomeScreen`, otherwise to `LoginScreen`.
153
-
154
- `src/screens/LoginScreen.tsx` is a demo login screen that dispatches `setCredentials` with dummy `user` and `accessToken` data to demonstrate the persistence flow.
155
-
156
- **Usage example — login:**
157
-
158
- ```tsx
159
- import { useAppDispatch } from "../redux/store";
160
- import { setCredentials } from "../redux/slices/authSlice";
161
-
162
- const dispatch = useAppDispatch();
163
-
164
- // After a successful login API call:
165
- dispatch(setCredentials({ user: userData, accessToken: token }));
166
- // State is automatically persisted to AsyncStorage
167
- ```
168
-
169
- **Usage example — logout:**
170
-
171
- ```tsx
172
- import { useAppDispatch } from "../redux/store";
173
- import { clearAuth } from "../redux/slices/authSlice";
174
-
175
- const dispatch = useAppDispatch();
176
- dispatch(clearAuth()); // Clears Redux state and AsyncStorage
177
- ```
178
-
179
- **Usage example — read auth state:**
180
-
181
- ```tsx
182
- import { useAppSelector } from "../redux/store";
183
-
184
- const { user, accessToken } = useAppSelector((state) => state.auth);
9
+ ```sh
10
+ npx @react-native-community/cli init MyApp --template @umang-thakkar/base-template
11
+ cd MyApp
12
+ npm start
185
13
  ```
186
14
 
187
- **How it works end-to-end:**
188
-
189
- - On login → dispatch `setCredentials` → persisted to `AsyncStorage`
190
- - On app restart → `PersistGate` rehydrates `auth` → `SplashScreen` sees `accessToken` → navigates directly to `HomeScreen`
191
- - On logout → dispatch `clearAuth` → persisted data cleared → `SplashScreen` routes to `LoginScreen`
192
-
193
- ### 🌙 Dark/Light Theme Support
194
-
195
- The template includes a complete theming system with automatic system preference detection:
196
-
197
- - **Theme files**: Located in `src/theme/`
198
- - `darkTheme.ts` - Dark theme colors
199
- - `lightTheme.ts` - Light theme colors
200
- - `index.ts` - Theme exports and TypeScript types
15
+ Then, in another terminal, `npm run android` or `npm run ios`. Requires Node.js 22.11+.
201
16
 
202
- - **Theme Context**: `src/hooks/ThemeContext.tsx` provides theme management
17
+ ## What's included
203
18
 
204
- - **Usage in components**:
19
+ - **Redux Toolkit** store with typed hooks and an `auth` slice (`user` + `accessToken`, typed selectors)
20
+ - **Redux Persist on MMKV**: login survives app restarts
21
+ - **React Navigation 7** native stack with a screen registry, per-screen options and a navigation service for use outside components
22
+ - **React Query 5** hooks over a layered **Axios** API (client → actions → services → queries), with an interceptor that attaches the auth token
23
+ - **Infinite scroll** helper `usePaginatedAPI` with debounced search
24
+ - **Light/dark themes** via `useTheme()`; the user's Light / Dark / System choice is saved in MMKV, and the navigation theme and status bar follow it
25
+ - App-wide **snackbars** (`showSnackbar` / `showErrorSnackbar`) and `getErrorMessage` for API errors
26
+ - Central `API_Routes` and `AppString` constants
27
+ - **ErrorBoundary** with a dev-only error view
28
+ - Responsive scaling, typography presets, formatting, date and platform helpers
29
+ - ESLint (React, TypeScript, React Native, React Query), Prettier, and Jest with MMKV and Reanimated mocks
30
+ - An agent skill (`.agents/skills/umang-design-pattern` in the repo) describing the conventions, so AI coding agents build apps the same way
205
31
 
206
- ```tsx
207
- import { useTheme } from "../hooks/ThemeContext";
32
+ ## Documentation
208
33
 
209
- const MyComponent = () => {
210
- const { theme, mode, toggleTheme } = useTheme();
34
+ Full docs are in [`docs/`](./docs/README.md):
211
35
 
212
- return (
213
- <View style={{ backgroundColor: theme.background }}>
214
- <Text style={{ color: theme.text }}>Current theme: {mode}</Text>
215
- <TouchableOpacity
216
- style={{ backgroundColor: theme.primary }}
217
- onPress={toggleTheme}
218
- >
219
- <Text style={{ color: theme.text }}>Toggle Theme</Text>
220
- </TouchableOpacity>
221
- </View>
222
- );
223
- };
224
- ```
225
-
226
- - **Features**:
227
- - Automatic detection of system color scheme preference
228
- - Manual theme toggle functionality
229
- - Listens for system theme changes
230
- - TypeScript support for theme properties
231
-
232
- ### 🌐 Navigation
233
-
234
- - Navigation setup in `src/navigation/`.
235
- - Register screens in `AppStack.tsx`.
236
-
237
- ### 🔗 React Query
238
-
239
- - API calls and React Query hooks are in `src/api/queries.ts`.
240
- - Example usage:
241
- ```ts
242
- import { useQuery } from "@tanstack/react-query";
243
- import { fetchData } from "../api/queries";
244
- const { data, isLoading } = useQuery({
245
- queryKey: ["data"],
246
- queryFn: fetchData,
247
- });
248
- ```
249
-
250
- ### 🧰 Utility Functions
251
-
252
- - Use helpers from `src/helper/`:
253
- ```ts
254
- import { formatDate } from "../helper/common-functions";
255
- ```
256
-
257
- ## 🪄 Customization Tips
258
-
259
- - Add new slices under `src/redux/`
260
- - Add new API services under `src/api/`
261
- - Organize screens under `src/screens/`
262
- - Keep shared components in a `components/` folder (add as needed)
263
- - Customize theme colors in `src/theme/darkTheme.ts` and `src/theme/lightTheme.ts`
264
- - Extend theme properties by updating the theme type in `src/theme/index.ts`
265
- - To persist additional slices, create a separate `persistConfig` per slice and wrap with `persistReducer`
266
- - To exclude sensitive fields from persistence, use the `blacklist` array in the persist config instead of `whitelist`
267
-
268
- ## 🎨 Theme Customization
269
-
270
- To customize the theme colors, edit the theme files:
271
-
272
- ```ts
273
- // src/theme/lightTheme.ts
274
- export const lightTheme = {
275
- background: "#FFFFFF",
276
- text: "#000000",
277
- primary: "#4045EF",
278
- secondary: "#F4F4F4",
279
- // Add your custom colors here
280
- };
281
-
282
- // src/theme/darkTheme.ts
283
- export const darkTheme = {
284
- background: "#000000",
285
- text: "#FFFFFF",
286
- primary: "#4045EF",
287
- secondary: "#1A1A1A",
288
- // Add your custom colors here
289
- };
290
- ```
36
+ - [Getting Started](./docs/getting-started.md)
37
+ - [Project Structure](./docs/project-structure.md)
38
+ - [State Management](./docs/state-management.md)
39
+ - [Storage (MMKV)](./docs/storage.md)
40
+ - [Networking](./docs/networking.md)
41
+ - [Navigation](./docs/navigation.md)
42
+ - [Theming](./docs/theming.md)
43
+ - [Helpers & Utilities](./docs/helpers.md)
44
+ - [Error Handling](./docs/error-handling.md)
45
+ - [Code Quality & Testing](./docs/code-quality.md)
46
+ - [Customization Recipes](./docs/customization.md)
47
+ - [Roadmap & Known Issues](./docs/roadmap.md)
48
+ - [Publishing the Template](./docs/publishing.md)
291
49
 
292
- ## 🤝 Contributing
50
+ ## Contributing
293
51
 
294
- Feel free to fork and customize this template! Pull requests welcome.
52
+ Fork it and customize it. Pull requests are welcome.
295
53
 
296
- ## 👨‍💻 Author
54
+ ## Author
297
55
 
298
56
  Created with ❤️ by **[Umang Thakkar](https://github.com/Umang2809)**
299
57
 
300
- ## 📜 License
58
+ ## License
301
59
 
302
60
  MIT © [Umang Thakkar](https://github.com/Umang2809)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umang-thakkar/base-template",
3
- "version": "1.1.1",
3
+ "version": "1.2.0",
4
4
  "description": "The template for react native to setup redux and other neccesary boilerplate codes",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -12,7 +12,16 @@
12
12
  "type": "commonjs",
13
13
  "files": [
14
14
  "template/*",
15
- "template.config.js"
15
+ "template.config.js",
16
+ "!template/node_modules",
17
+ "!template/ios/Pods",
18
+ "!template/ios/build",
19
+ "!template/android/build",
20
+ "!template/android/app/build",
21
+ "!template/android/.gradle",
22
+ "!template/ios/.xcode.env.local",
23
+ "!template/package-lock.json",
24
+ "!template/yarn.lock"
16
25
  ],
17
26
  "dependencies": {},
18
27
  "devDependencies": {
@@ -2,7 +2,6 @@
2
2
  "root": true,
3
3
  "extends": [
4
4
  "@react-native",
5
- "@react-native-community",
6
5
  "plugin:@tanstack/eslint-plugin-query/recommended",
7
6
  ],
8
7
  "parser": "@typescript-eslint/parser",
@@ -26,6 +25,11 @@
26
25
  "node": true,
27
26
  "react-native/react-native": true,
28
27
  },
28
+ "settings": {
29
+ "react": {
30
+ "version": "detect",
31
+ },
32
+ },
29
33
  "rules": {
30
34
  // React best practices
31
35
  "react/react-in-jsx-scope": "off",
@@ -43,14 +47,14 @@
43
47
  },
44
48
  ],
45
49
  "@typescript-eslint/no-explicit-any": "warn",
46
- "@typescript-eslint/explicit-function-return-types": "off",
47
50
  "@typescript-eslint/no-non-null-assertion": "warn",
48
51
 
49
- // React Native best practices
52
+ // Styling: StyleSheet.create at the bottom of each file, theme colors from
53
+ // useTheme(), no literal colors or inline style objects.
50
54
  "react-native/no-unused-styles": "warn",
51
- "react-native/split-platform-components": "warn",
52
55
  "react-native/no-inline-styles": "warn",
53
56
  "react-native/no-color-literals": "warn",
57
+ "react-native/split-platform-components": "warn",
54
58
 
55
59
  // General best practices
56
60
  "no-console": [
@@ -64,51 +68,9 @@
64
68
  "prefer-const": "error",
65
69
  "eqeqeq": ["error", "always"],
66
70
  "curly": ["error", "all"],
67
- "brace-style": ["error", "1tbs"],
68
- "space-before-function-paren": [
69
- "error",
70
- {
71
- "anonymous": "always",
72
- "named": "never",
73
- "asyncArrow": "always",
74
- },
75
- ],
76
- "semi": ["error", "always"],
77
- "quotes": ["error", "single", { "avoidEscape": true }],
78
- "indent": ["error", 2],
79
-
80
- // Import organization
81
- "sort-imports": "off",
82
- "import/order": [
83
- "warn",
84
- {
85
- "groups": [
86
- "builtin",
87
- "external",
88
- "internal",
89
- "parent",
90
- "sibling",
91
- "index",
92
- ],
93
- "pathGroups": [
94
- {
95
- "pattern": "react*",
96
- "group": "external",
97
- "position": "before",
98
- },
99
- ],
100
- "alphabeticalOrder": true,
101
- },
102
- ],
103
71
 
104
72
  // React Query best practices
105
73
  "@tanstack/query/exhaustive-deps": "error",
106
- "@tanstack/query/prefer-query-object-syntax": "warn",
107
- },
108
- "settings": {
109
- "react": {
110
- "version": "detect",
111
- },
112
74
  },
113
75
  "overrides": [
114
76
  {
@@ -126,5 +88,13 @@
126
88
  "@typescript-eslint/no-unused-vars": "off",
127
89
  },
128
90
  },
91
+ {
92
+ // ErrorBoundary sits above ThemeProvider, and colors.ts is the static
93
+ // palette, so both use literal colors on purpose.
94
+ "files": ["src/components/ErrorBoundary.tsx", "src/helper/colors.ts", "src/theme/*Theme.ts"],
95
+ "rules": {
96
+ "react-native/no-color-literals": "off",
97
+ },
98
+ },
129
99
  ],
130
100
  }
@@ -0,0 +1,8 @@
1
+ module.exports = {
2
+ singleQuote: true,
3
+ trailingComma: 'all',
4
+ arrowParens: 'avoid',
5
+ bracketSpacing: true,
6
+ bracketSameLine: true,
7
+ printWidth: 100,
8
+ };
package/template/App.tsx CHANGED
@@ -1,12 +1,12 @@
1
- import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
2
- import { StyleSheet } from "react-native";
3
- import { SafeAreaProvider } from "react-native-safe-area-context";
4
- import { Provider } from "react-redux";
5
- import store, { persistor } from "./src/redux/store";
6
- import { PersistGate } from "redux-persist/integration/react";
7
- import Main from "./Main";
8
- import { ThemeProvider } from "./src/hooks/ThemeContext";
9
- import { ErrorBoundary } from "./src/components/ErrorBoundary";
1
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
2
+ import { SafeAreaProvider } from 'react-native-safe-area-context';
3
+ import { Provider } from 'react-redux';
4
+ import store, { persistor } from './src/redux/store';
5
+ import { PersistGate } from 'redux-persist/integration/react';
6
+ import Main from './Main';
7
+ import { ThemeProvider } from './src/hooks/ThemeContext';
8
+ import { ErrorBoundary } from './src/components/ErrorBoundary';
9
+ import SnackbarHost from './src/components/SnackbarHost';
10
10
 
11
11
  const queryClient = new QueryClient({
12
12
  defaultOptions: {
@@ -27,6 +27,8 @@ function App() {
27
27
  <SafeAreaProvider>
28
28
  <ThemeProvider>
29
29
  <Main />
30
+ {/* Shows messages from showSnackbar / showErrorSnackbar above every screen. */}
31
+ <SnackbarHost />
30
32
  </ThemeProvider>
31
33
  </SafeAreaProvider>
32
34
  </PersistGate>
@@ -36,10 +38,4 @@ function App() {
36
38
  );
37
39
  }
38
40
 
39
- const styles = StyleSheet.create({
40
- container: {
41
- flex: 1,
42
- },
43
- });
44
-
45
41
  export default App;
package/template/Main.tsx CHANGED
@@ -1,11 +1,35 @@
1
- import { NavigationContainer } from "@react-navigation/native";
2
- import React from "react";
3
- import AppStack from "./src/navigation/AppStack";
4
- import { navigationRef } from "./src/helper/navigation-service";
1
+ import React, { useMemo } from 'react';
2
+ import { StatusBar } from 'react-native';
3
+ import { DarkTheme, DefaultTheme, NavigationContainer, type Theme } from '@react-navigation/native';
4
+ import AppStack from './src/navigation/AppStack';
5
+ import { navigationRef } from './src/helper/navigation-service';
6
+ import { useTheme } from './src/hooks/ThemeContext';
5
7
 
6
8
  const Main = () => {
9
+ const { theme, mode } = useTheme();
10
+
11
+ // Gives the native screens and transitions the app's colors, so there's no
12
+ // white flash behind screens in dark mode.
13
+ const navigationTheme = useMemo<Theme>(() => {
14
+ const base = mode === 'dark' ? DarkTheme : DefaultTheme;
15
+ return {
16
+ ...base,
17
+ colors: {
18
+ ...base.colors,
19
+ primary: theme.primary,
20
+ background: theme.background,
21
+ card: theme.card,
22
+ text: theme.text,
23
+ border: theme.border,
24
+ notification: theme.error,
25
+ },
26
+ };
27
+ }, [mode, theme]);
28
+
7
29
  return (
8
- <NavigationContainer ref={navigationRef}>
30
+ <NavigationContainer ref={navigationRef} theme={navigationTheme}>
31
+ {/* Status bar icons follow the active theme (light icons on dark backgrounds). */}
32
+ <StatusBar barStyle={mode === 'dark' ? 'light-content' : 'dark-content'} />
9
33
  <AppStack />
10
34
  </NavigationContainer>
11
35
  );
@@ -0,0 +1,59 @@
1
+ const mockStorage = new Map<string, unknown>();
2
+
3
+ export class MMKVMock {
4
+ set(key: string, value: boolean | string | number | Uint8Array) {
5
+ mockStorage.set(key, value);
6
+ }
7
+
8
+ getString(key: string): string | undefined {
9
+ const val = mockStorage.get(key);
10
+ return typeof val === 'string' ? val : undefined;
11
+ }
12
+
13
+ getBoolean(key: string): boolean | undefined {
14
+ const val = mockStorage.get(key);
15
+ return typeof val === 'boolean' ? val : undefined;
16
+ }
17
+
18
+ getNumber(key: string): number | undefined {
19
+ const val = mockStorage.get(key);
20
+ return typeof val === 'number' ? val : undefined;
21
+ }
22
+
23
+ getBuffer(key: string): Uint8Array | undefined {
24
+ const val = mockStorage.get(key);
25
+ return val instanceof Uint8Array ? val : undefined;
26
+ }
27
+
28
+ contains(key: string): boolean {
29
+ return mockStorage.has(key);
30
+ }
31
+
32
+ remove(key: string) {
33
+ mockStorage.delete(key);
34
+ }
35
+
36
+ delete(key: string) {
37
+ mockStorage.delete(key);
38
+ }
39
+
40
+ clearAll() {
41
+ mockStorage.clear();
42
+ }
43
+
44
+ getAllKeys(): string[] {
45
+ return Array.from(mockStorage.keys());
46
+ }
47
+
48
+ addOnValueChangedListener() {
49
+ return { remove: () => {} };
50
+ }
51
+ }
52
+
53
+ export const MMKV = MMKVMock;
54
+
55
+ export function createMMKV() {
56
+ return new MMKVMock();
57
+ }
58
+
59
+ export default createMMKV;
@@ -7,7 +7,12 @@ import ReactTestRenderer from 'react-test-renderer';
7
7
  import App from '../App';
8
8
 
9
9
  test('renders correctly', async () => {
10
+ let renderer: ReactTestRenderer.ReactTestRenderer | undefined;
10
11
  await ReactTestRenderer.act(() => {
11
- ReactTestRenderer.create(<App />);
12
+ renderer = ReactTestRenderer.create(<App />);
13
+ });
14
+ // Unmount so the splash timer is cleared and Jest can exit.
15
+ await ReactTestRenderer.act(() => {
16
+ renderer?.unmount();
12
17
  });
13
18
  });
@@ -0,0 +1,43 @@
1
+ import {
2
+ cleanPayload,
3
+ formatPrice,
4
+ formatWithComma,
5
+ getErrorMessage,
6
+ } from '../src/helper/common-functions';
7
+ import { pushSnackbar, subscribeSnackbar } from '../src/helper/snackbar';
8
+
9
+ describe('common-functions', () => {
10
+ it('formats numbers', () => {
11
+ expect(formatWithComma(1234567)).toBe('1,234,567');
12
+ expect(formatPrice(1234.5)).toBe('1,234.50');
13
+ });
14
+
15
+ it('removes empty values from payloads', () => {
16
+ expect(cleanPayload({ a: 1, b: '', c: null, d: undefined, e: 0, f: false })).toEqual({
17
+ a: 1,
18
+ e: 0,
19
+ f: false,
20
+ });
21
+ });
22
+
23
+ it('reads error messages from API errors', () => {
24
+ expect(getErrorMessage({ message: 'Invalid token' })).toBe('Invalid token');
25
+ expect(getErrorMessage('Plain')).toBe('Plain');
26
+ });
27
+ });
28
+
29
+ describe('snackbar store', () => {
30
+ it('delivers messages to subscribers until they unsubscribe', () => {
31
+ const listener = jest.fn();
32
+ const unsubscribe = subscribeSnackbar(listener);
33
+
34
+ pushSnackbar('Saved', { type: 'success' });
35
+ expect(listener).toHaveBeenCalledWith(
36
+ expect.objectContaining({ title: 'Saved', type: 'success' }),
37
+ );
38
+
39
+ unsubscribe();
40
+ pushSnackbar('Ignored');
41
+ expect(listener).toHaveBeenCalledTimes(1);
42
+ });
43
+ });