Fixed conflics

This commit is contained in:
Urvish Prajapati 2026-10-30 10:58:16 +05:30
commit b6a1e007bf
58 changed files with 1806 additions and 731 deletions

12
.env
View File

@ -22,11 +22,11 @@
# EXPO_PUBLIC_CONTENT_PREVIEW_ENABLED=true
# QA Dev
EXPO_PUBLIC_API_URL=https://api.acupedia.in/api
EXPO_PUBLIC_STOREFRONT_URL=https://acupedia.in/store
EXPO_PUBLIC_CONTENT_PREVIEW_ENABLED=true
#EXPO_PUBLIC_API_URL=https://qa-api.acupedia.in/api
# EXPO_PUBLIC_STOREFRONT_URL=https://qa-acupedia.in/store
# EXPO_PUBLIC_CONTENT_PREVIEW_ENABLED=true
# Local Dev
# EXPO_PUBLIC_API_URL=http://localhost:8000/api
# EXPO_PUBLIC_STOREFRONT_URL=http://localhost:3000
# EXPO_PUBLIC_CONTENT_PREVIEW_ENABLED=true
EXPO_PUBLIC_API_URL=http://localhost:8000/api
EXPO_PUBLIC_STOREFRONT_URL=http://localhost:3000
EXPO_PUBLIC_CONTENT_PREVIEW_ENABLED=true

View File

@ -60,7 +60,7 @@ react {
// hermesFlags = ["-O", "-output-source-map"]
/* Autolinking */
autolinkLibrariesWithApp()
// autolinkLibrariesWithApp() // disabled to bypass codegen errors
}
/**
@ -87,9 +87,9 @@ android {
buildToolsVersion rootProject.ext.buildToolsVersion
compileSdk rootProject.ext.compileSdkVersion
namespace 'com.anonymous.acupedia'
namespace 'com.renownent.mobile.acupedia'
defaultConfig {
applicationId 'com.anonymous.acupedia'
applicationId 'com.renownent.mobile.acupedia'
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1

View File

@ -11,7 +11,7 @@
<data android:scheme="https"/>
</intent>
</queries>
<application android:name=".MainApplication" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:allowBackup="true" android:theme="@style/AppTheme" android:supportsRtl="true" android:enableOnBackInvokedCallback="false">
<application android:name=".MainApplication" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:allowBackup="false" android:theme="@style/AppTheme" android:supportsRtl="true" android:enableOnBackInvokedCallback="false" android:usesCleartextTraffic="true">
<meta-data android:name="expo.modules.updates.ENABLED" android:value="false"/>
<meta-data android:name="expo.modules.updates.ENABLE_BSDIFF_PATCH_SUPPORT" android:value="true"/>
<meta-data android:name="expo.modules.updates.EXPO_UPDATES_CHECK_ON_LAUNCH" android:value="ALWAYS"/>
@ -26,6 +26,7 @@
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="myapp"/>
<data android:scheme="acupedia"/>
</intent-filter>
</activity>
</application>

View File

@ -1,65 +0,0 @@
package com.anonymous.acupedia
import expo.modules.splashscreen.SplashScreenManager
import android.os.Build
import android.os.Bundle
import com.facebook.react.ReactActivity
import com.facebook.react.ReactActivityDelegate
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled
import com.facebook.react.defaults.DefaultReactActivityDelegate
import expo.modules.ReactActivityDelegateWrapper
class MainActivity : ReactActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
// Set the theme to AppTheme BEFORE onCreate to support
// coloring the background, status bar, and navigation bar.
// This is required for expo-splash-screen.
// setTheme(R.style.AppTheme);
// @generated begin expo-splashscreen - expo prebuild (DO NOT MODIFY) sync-f3ff59a738c56c9a6119210cb55f0b613eb8b6af
SplashScreenManager.registerOnActivity(this)
// @generated end expo-splashscreen
super.onCreate(null)
}
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/
override fun getMainComponentName(): String = "main"
/**
* Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate]
* which allows you to enable New Architecture with a single boolean flags [fabricEnabled]
*/
override fun createReactActivityDelegate(): ReactActivityDelegate {
return ReactActivityDelegateWrapper(
this,
BuildConfig.IS_NEW_ARCHITECTURE_ENABLED,
object : DefaultReactActivityDelegate(
this,
mainComponentName,
fabricEnabled
){})
}
/**
* Align the back button behavior with Android S
* where moving root activities to background instead of finishing activities.
* @see <a href="https://developer.android.com/reference/android/app/Activity#onBackPressed()">onBackPressed</a>
*/
override fun invokeDefaultOnBackPressed() {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) {
if (!moveTaskToBack(false)) {
// For non-root activities, use the default implementation to finish them.
super.invokeDefaultOnBackPressed()
}
return
}
// Use the default back button implementation on Android S
// because it's doing more than [Activity.moveTaskToBack] in fact.
super.invokeDefaultOnBackPressed()
}
}

View File

@ -1,57 +0,0 @@
package com.anonymous.acupedia
import android.app.Application
import android.content.res.Configuration
import com.facebook.react.PackageList
import com.facebook.react.ReactApplication
import com.facebook.react.ReactNativeApplicationEntryPoint.loadReactNative
import com.facebook.react.ReactNativeHost
import com.facebook.react.ReactPackage
import com.facebook.react.ReactHost
import com.facebook.react.common.ReleaseLevel
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint
import com.facebook.react.defaults.DefaultReactNativeHost
import expo.modules.ApplicationLifecycleDispatcher
import expo.modules.ReactNativeHostWrapper
class MainApplication : Application(), ReactApplication {
override val reactNativeHost: ReactNativeHost = ReactNativeHostWrapper(
this,
object : DefaultReactNativeHost(this) {
override fun getPackages(): List<ReactPackage> =
PackageList(this).packages.apply {
// Packages that cannot be autolinked yet can be added manually here, for example:
// add(MyReactNativePackage())
}
override fun getJSMainModuleName(): String = ".expo/.virtual-metro-entry"
override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG
override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED
override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED
}
)
override val reactHost: ReactHost
get() = ReactNativeHostWrapper.createReactHost(applicationContext, reactNativeHost)
override fun onCreate() {
super.onCreate()
DefaultNewArchitectureEntryPoint.releaseLevel = try {
ReleaseLevel.valueOf(BuildConfig.REACT_NATIVE_RELEASE_LEVEL.uppercase())
} catch (e: IllegalArgumentException) {
ReleaseLevel.STABLE
}
loadReactNative(this)
ApplicationLifecycleDispatcher.onApplicationCreate(this)
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
ApplicationLifecycleDispatcher.onConfigurationChanged(this, newConfig)
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.7 KiB

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.0 KiB

After

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.1 KiB

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.8 KiB

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

After

Width:  |  Height:  |  Size: 20 KiB

View File

@ -2,4 +2,5 @@
<color name="splashscreen_background">#208AEF</color>
<color name="iconBackground">#E6F4FE</color>
<color name="colorPrimary">#023c69</color>
<color name="colorPrimaryDark">#208AEF</color>
</resources>

View File

@ -2,4 +2,5 @@
<string name="app_name">acupedia</string>
<string name="expo_system_ui_user_interface_style" translatable="false">automatic</string>
<string name="expo_splash_screen_resize_mode" translatable="false">contain</string>
<string name="expo_splash_screen_status_bar_translucent" translatable="false">false</string>
</resources>

View File

@ -1,9 +1,9 @@
<resources xmlns:tools="http://schemas.android.com/tools">
<style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
<item name="android:enforceNavigationBarContrast" tools:targetApi="29">true</item>
<item name="android:editTextBackground">@drawable/rn_edit_text_material</item>
<item name="colorPrimary">@color/colorPrimary</item>
<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:navigationBarColor">@android:color/transparent</item>
<item name="android:statusBarColor">#208AEF</item>
</style>
<style name="Theme.App.SplashScreen" parent="Theme.SplashScreen">
<item name="windowSplashScreenBackground">@color/splashscreen_background</item>

View File

@ -60,4 +60,7 @@ EX_DEV_CLIENT_NETWORK_INSPECTOR=true
# Use legacy packaging to compress native libraries in the resulting APK.
expo.useLegacyPackaging=false
expo.inlineModules.watchedDirectories=[]
expo.inlineModules.watchedDirectories=[]
# Specifies whether the app is configured to use edge-to-edge via the app config or plugin
# WARNING: This property has been deprecated and will be removed in Expo SDK 55. Use `edgeToEdgeEnabled` or `react.edgeToEdgeEnabled` to determine whether the project is using edge-to-edge.
expo.edgeToEdgeEnabled=true

View File

@ -8,7 +8,7 @@
"scheme": "acupedia",
"userInterfaceStyle": "automatic",
"ios": {
"bundleIdentifier": "com.renownent.mobile.acupedia",
"bundleIdentifier": "com.renown.mobile.acupedia",
"supportsTablet": true,
"infoPlist": {
"NSAppTransportSecurity": {
@ -24,7 +24,7 @@
"monochromeImage": "./assets/images/android-icon-monochrome.png"
},
"predictiveBackGestureEnabled": false,
"package": "com.renownent.mobile.acupedia",
"package": "com.renown.mobile.acupedia",
"allowBackup": false
},
"web": {

11
eas.json Normal file
View File

@ -0,0 +1,11 @@
{
"build": {
"production": {
"android": {
"buildType": "apk",
"gradleCommand": "./gradlew assembleRelease",
"artifactPath": "android/app/build/outputs/apk/release/app-release.apk"
}
}
}
}

View File

@ -371,7 +371,7 @@
);
OTHER_SWIFT_FLAGS = "$(inherited) -D EXPO_CONFIGURATION_DEBUG";
PRODUCT_BUNDLE_IDENTIFIER = com.renownent.mobile.acupedia;
PRODUCT_NAME = acupedia;
PRODUCT_NAME = "acupedia";
SWIFT_OBJC_BRIDGING_HEADER = "acupedia/acupedia-Bridging-Header.h";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
@ -405,7 +405,7 @@
);
OTHER_SWIFT_FLAGS = "$(inherited) -D EXPO_CONFIGURATION_RELEASE";
PRODUCT_BUNDLE_IDENTIFIER = com.renownent.mobile.acupedia;
PRODUCT_NAME = acupedia;
PRODUCT_NAME = "acupedia";
SWIFT_OBJC_BRIDGING_HEADER = "acupedia/acupedia-Bridging-Header.h";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";

Binary file not shown.

After

Width:  |  Height:  |  Size: 734 KiB

View File

@ -1,14 +1,14 @@
{
"images": [
{
"filename": "AppIcon.png",
"filename": "App-Icon-1024x1024@1x.png",
"idiom": "universal",
"platform": "ios",
"size": "1024x1024"
}
],
"info": {
"author": "expo",
"version": 1
"version": 1,
"author": "expo"
}
}
}

View File

@ -1,81 +1,81 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CADisableMinimumFrameDurationOnPhone</key>
<true/>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
<string>acupedia</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>1.0.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>myapp</string>
<string>com.renownent.acupedia</string>
</array>
</dict>
</array>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSMinimumSystemVersion</key>
<string>12.0</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
<key>NSUserActivityTypes</key>
<array>
<string>$(PRODUCT_BUNDLE_IDENTIFIER).expo.index_route</string>
</array>
<key>RCTMetroPort</key>
<string>$(RCT_METRO_PORT)</string>
<key>RCTNewArchEnabled</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>SplashScreen</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>arm64</string>
</array>
<key>UIRequiresFullScreen</key>
<false/>
<key>UIStatusBarStyle</key>
<string>UIStatusBarStyleLightContent</string>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIUserInterfaceStyle</key>
<string>Automatic</string>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
</dict>
</plist>
<dict>
<key>CADisableMinimumFrameDurationOnPhone</key>
<true/>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
<string>acupedia</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>1.0.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>acupedia</string>
<string>com.renownent.mobile.acupedia</string>
</array>
</dict>
</array>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSMinimumSystemVersion</key>
<string>12.0</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
<key>NSUserActivityTypes</key>
<array>
<string>$(PRODUCT_BUNDLE_IDENTIFIER).expo.index_route</string>
</array>
<key>RCTMetroPort</key>
<string>$(RCT_METRO_PORT)</string>
<key>RCTNewArchEnabled</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>SplashScreen</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>arm64</string>
</array>
<key>UIRequiresFullScreen</key>
<false/>
<key>UIStatusBarStyle</key>
<string>UIStatusBarStyleLightContent</string>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIUserInterfaceStyle</key>
<string>Automatic</string>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
</dict>
</plist>

680
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -11,7 +11,7 @@
"@tanstack/react-query": "^5.101.2",
"axios": "^1.18.1",
"expo": "~54.0.0",
"expo-build-properties": "~1.0.10",
"expo-build-properties": "~57.0.22",
"expo-constants": "~18.0.10",
"expo-device": "~8.0.9",
"expo-font": "~14.0.9",

View File

@ -2,7 +2,48 @@ import axios, { AxiosHeaders } from "axios";
import { getApiAccessToken } from "@/api/access-token";
import { normalizeApiError } from "@/api/error-utils";
import { notifyUnauthorized } from "@/api/session-events";
const apiClient=axios.create({baseURL:process.env.EXPO_PUBLIC_API_URL ?? process.env.EXPO_PUBLIC_API_BASE_URL ?? "http://localhost:8000/api",timeout:30000,headers:{"Content-Type":"application/json",Accept:"application/json","Bypass-Tunnel-Reminder":"true"}});
apiClient.interceptors.request.use((config)=>{const token=getApiAccessToken(); if(token){const headers=AxiosHeaders.from(config.headers); headers.set("Authorization",`Bearer ${token}`); config.headers=headers;} return config;},(error)=>Promise.reject(normalizeApiError(error)));
apiClient.interceptors.response.use((response)=>response,(error:unknown)=>{const apiError=normalizeApiError(error); const requestHeaders=axios.isAxiosError(error)?AxiosHeaders.from(error.config?.headers):null; const hadBearerToken=Boolean(requestHeaders?.get("Authorization")?.toString().startsWith("Bearer ")); if(hadBearerToken && apiError.status===401) notifyUnauthorized(); return Promise.reject(apiError);});
import { getActiveApiUrl } from "@/store/environment.store";
const apiClient = axios.create({
baseURL: getActiveApiUrl(),
timeout: 30000,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"Bypass-Tunnel-Reminder": "true",
},
});
apiClient.interceptors.request.use(
(config) => {
const activeBaseUrl = getActiveApiUrl();
if (activeBaseUrl) {
config.baseURL = activeBaseUrl;
}
const token = getApiAccessToken();
if (token) {
const headers = AxiosHeaders.from(config.headers);
headers.set("Authorization", `Bearer ${token}`);
config.headers = headers;
}
return config;
},
(error) => Promise.reject(normalizeApiError(error))
);
apiClient.interceptors.response.use(
(response) => response,
(error: unknown) => {
const apiError = normalizeApiError(error);
const requestHeaders = axios.isAxiosError(error)
? AxiosHeaders.from(error.config?.headers)
: null;
const hadBearerToken = Boolean(
requestHeaders?.get("Authorization")?.toString().startsWith("Bearer ")
);
if (hadBearerToken && apiError.status === 401) notifyUnauthorized();
return Promise.reject(apiError);
}
);
export default apiClient;

View File

@ -19,6 +19,7 @@ import Constants from "expo-constants";
import { Colors } from "@/theme";
import { useAuthStore } from "@/store/auth.store";
import { getActiveStorefrontUrl } from "@/store/environment.store";
import PrimaryButton from "@/components/buttons/PrimaryButton";
function param(value: string | string[] | undefined): string {
@ -26,6 +27,9 @@ function param(value: string | string[] | undefined): string {
}
function resolveStorefrontUrl(): string {
const dynamicUrl = getActiveStorefrontUrl();
if (dynamicUrl) return dynamicUrl;
const envUrl = process.env.EXPO_PUBLIC_STOREFRONT_URL?.trim();
if (envUrl) return envUrl;

View File

@ -0,0 +1,371 @@
import React from "react";
import {
Alert,
Modal,
Platform,
Pressable,
StyleSheet,
Text,
TouchableOpacity,
View,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { useRouter } from "expo-router";
import { moderateScale, scale, verticalScale } from "react-native-size-matters";
import {
DEFAULT_ENV_LABEL,
ENABLE_ENV_SWITCHER,
ENVIRONMENTS,
EnvironmentKey,
} from "@/config/environments";
import { useEnvironmentStore } from "@/store/environment.store";
import { Colors } from "@/theme";
interface EnvironmentSelectorModalProps {
visible: boolean;
onClose: () => void;
}
export default function EnvironmentSelectorModal({
visible,
onClose,
}: EnvironmentSelectorModalProps) {
const router = useRouter();
const currentEnv = useEnvironmentStore((state) => state.currentEnv);
const switchEnvironment = useEnvironmentStore(
(state) => state.switchEnvironment
);
if (!ENABLE_ENV_SWITCHER) {
return null;
}
const handleSelectEnvironment = (key: EnvironmentKey) => {
if (key === currentEnv) {
onClose();
return;
}
const targetLabel =
key === "default" ? DEFAULT_ENV_LABEL : ENVIRONMENTS[key].label;
const executeSwitch = async () => {
onClose();
try {
await switchEnvironment(key);
// Navigate cleanly to Login screen after logout
router.replace("/login");
Alert.alert(
"Environment Switched",
`Active backend is now: ${targetLabel}`
);
} catch (err) {
console.error("Failed to switch environment:", err);
}
};
if (Platform.OS === "web") {
const confirmed = window.confirm(
`Switching to "${targetLabel}" will log you out and reload data. Continue?`
);
if (confirmed) {
executeSwitch();
}
} else {
Alert.alert(
"Switch Environment",
`Switching to "${targetLabel}" will log you out and reset cached data. Are you sure?`,
[
{ text: "Cancel", style: "cancel" },
{
text: "Switch & Logout",
style: "destructive",
onPress: executeSwitch,
},
],
{ cancelable: true }
);
}
};
const options: {
key: EnvironmentKey;
label: string;
url: string;
badge: string;
badgeColor: string;
}[] = [
{
key: "prod",
label: ENVIRONMENTS.prod.label,
url: ENVIRONMENTS.prod.apiUrl,
badge: "PROD",
badgeColor: "#10B981", // Emerald green
},
{
key: "qa",
label: ENVIRONMENTS.qa.label,
url: ENVIRONMENTS.qa.apiUrl,
badge: "QA",
badgeColor: "#F59E0B", // Amber
},
{
key: "default",
label: DEFAULT_ENV_LABEL,
url: "Uses build / .env defaults",
badge: "ENV",
badgeColor: "#6B7280", // Gray
},
];
return (
<Modal
visible={visible}
transparent
animationType="fade"
onRequestClose={onClose}
>
<Pressable style={styles.backdrop} onPress={onClose}>
<Pressable
style={styles.modalCard}
onPress={(e) => e.stopPropagation()}
>
{/* Header */}
<View style={styles.header}>
<View style={styles.headerLeft}>
<View style={styles.iconCircle}>
<Ionicons
name="server-outline"
size={moderateScale(20)}
color={Colors.primary || "#2563EB"}
/>
</View>
<View>
<Text style={styles.title}>Select Environment</Text>
<Text style={styles.subtitle}>
Switch server for testing
</Text>
</View>
</View>
<TouchableOpacity
onPress={onClose}
hitSlop={12}
style={styles.closeBtn}
>
<Ionicons
name="close"
size={moderateScale(22)}
color="#64748B"
/>
</TouchableOpacity>
</View>
{/* Options */}
<View style={styles.optionsList}>
{options.map((opt) => {
const isSelected = currentEnv === opt.key;
return (
<TouchableOpacity
key={opt.key}
activeOpacity={0.7}
onPress={() => handleSelectEnvironment(opt.key)}
style={[
styles.optionItem,
isSelected && styles.optionItemSelected,
]}
>
<View style={styles.optionContent}>
<View style={styles.optionTitleRow}>
<Text
style={[
styles.optionLabel,
isSelected && styles.optionLabelSelected,
]}
>
{opt.label}
</Text>
<View
style={[
styles.badge,
{ backgroundColor: opt.badgeColor },
]}
>
<Text style={styles.badgeText}>{opt.badge}</Text>
</View>
</View>
<Text
style={styles.optionUrl}
numberOfLines={1}
ellipsizeMode="tail"
>
{opt.url}
</Text>
</View>
<View
style={[
styles.radioCircle,
isSelected && styles.radioCircleSelected,
]}
>
{isSelected && <View style={styles.radioDot} />}
</View>
</TouchableOpacity>
);
})}
</View>
{/* Notice */}
<View style={styles.noticeBox}>
<Ionicons
name="information-circle-outline"
size={moderateScale(16)}
color="#64748B"
/>
<Text style={styles.noticeText}>
Switching environment logs out the user and clears cache.
</Text>
</View>
</Pressable>
</Pressable>
</Modal>
);
}
const styles = StyleSheet.create({
backdrop: {
flex: 1,
backgroundColor: "rgba(0, 0, 0, 0.5)",
justifyContent: "center",
alignItems: "center",
paddingHorizontal: scale(20),
},
modalCard: {
width: "100%",
maxWidth: scale(380),
backgroundColor: "#FFFFFF",
borderRadius: moderateScale(16),
padding: scale(20),
shadowColor: "#000",
shadowOffset: { width: 0, height: 4 },
shadowOpacity: 0.15,
shadowRadius: 12,
elevation: 8,
},
header: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
marginBottom: verticalScale(16),
},
headerLeft: {
flexDirection: "row",
alignItems: "center",
gap: scale(10),
},
iconCircle: {
width: scale(38),
height: scale(38),
borderRadius: scale(19),
backgroundColor: "#EFF6FF",
justifyContent: "center",
alignItems: "center",
},
title: {
fontSize: moderateScale(17),
fontWeight: "700",
color: "#0F172A",
},
subtitle: {
fontSize: moderateScale(12),
color: "#64748B",
marginTop: verticalScale(2),
},
closeBtn: {
padding: scale(4),
},
optionsList: {
gap: verticalScale(10),
marginBottom: verticalScale(14),
},
optionItem: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
padding: scale(14),
borderRadius: moderateScale(12),
borderWidth: 1.5,
borderColor: "#E2E8F0",
backgroundColor: "#F8FAFC",
},
optionItemSelected: {
borderColor: Colors.primary || "#2563EB",
backgroundColor: "#EFF6FF",
},
optionContent: {
flex: 1,
marginRight: scale(10),
},
optionTitleRow: {
flexDirection: "row",
alignItems: "center",
gap: scale(8),
},
optionLabel: {
fontSize: moderateScale(14),
fontWeight: "600",
color: "#1E293B",
},
optionLabelSelected: {
color: Colors.primary || "#2563EB",
fontWeight: "700",
},
badge: {
paddingHorizontal: scale(6),
paddingVertical: verticalScale(2),
borderRadius: moderateScale(4),
},
badgeText: {
fontSize: moderateScale(10),
fontWeight: "700",
color: "#FFFFFF",
},
optionUrl: {
fontSize: moderateScale(11),
color: "#64748B",
marginTop: verticalScale(4),
},
radioCircle: {
width: scale(20),
height: scale(20),
borderRadius: scale(10),
borderWidth: 2,
borderColor: "#CBD5E1",
justifyContent: "center",
alignItems: "center",
},
radioCircleSelected: {
borderColor: Colors.primary || "#2563EB",
},
radioDot: {
width: scale(10),
height: scale(10),
borderRadius: scale(5),
backgroundColor: Colors.primary || "#2563EB",
},
noticeBox: {
flexDirection: "row",
alignItems: "center",
gap: scale(6),
backgroundColor: "#F1F5F9",
padding: scale(10),
borderRadius: moderateScale(8),
},
noticeText: {
fontSize: moderateScale(11),
color: "#64748B",
flex: 1,
},
});

View File

@ -0,0 +1,43 @@
/**
* Environment configuration for Acupedia Mobile.
*
* Set ENABLE_ENV_SWITCHER = false (or comment out) to completely disable
* the environment switcher UI for production App Store / Google Play builds.
*/
export const ENABLE_ENV_SWITCHER = true;
export type EnvironmentKey = "default" | "prod" | "qa";
export interface EnvironmentConfig {
key: EnvironmentKey;
label: string;
badge: string;
apiUrl: string;
storefrontUrl: string;
mediaBaseUrl: string;
description: string;
}
export const ENVIRONMENTS: Record<"prod" | "qa", EnvironmentConfig> = {
prod: {
key: "prod",
label: "Production",
badge: "PROD",
apiUrl: "https://api.acupedia.in/api",
storefrontUrl: "https://acupedia.in/store",
mediaBaseUrl: "https://api.acupedia.in",
description: "Official live server (api.acupedia.in)",
},
qa: {
key: "qa",
label: "QA / Staging",
badge: "QA",
apiUrl: "https://qa-api.acupedia.in/api",
storefrontUrl: "https://qa.acupedia.in/store",
mediaBaseUrl: "https://qa-api.acupedia.in",
description: "Testing & QA server (qa-api.acupedia.in)",
},
};
export const DEFAULT_ENV_LABEL = "Default (.env)";

View File

@ -145,8 +145,13 @@ export const validatePhoneNumber = (
return "Phone number cannot contain alphabetic characters.";
}
// Strictly enforce numeric digits with optional leading '+' and standard formatting separators
if (!/^\+?[\d\s\-()]+$/.test(trimmed)) {
// Strictly disallow hyphens, dashes, and invalid characters
if (/[\-()_]/.test(trimmed)) {
return "Phone number cannot contain hyphens or special symbols.";
}
// Strictly enforce numeric digits with optional leading '+' and whitespace
if (!/^\+?[\d\s]+$/.test(trimmed)) {
return "Please enter a valid phone number containing only numeric digits.";
}
@ -210,3 +215,44 @@ export const isValidPhoneNumber = (
): boolean => {
return validatePhoneNumber(val, dialCode, country) === null;
};
/**
* Updates the dial code prefix of an existing phone number when country changes.
* Automatically clamps remaining digits to the new country's maxLength.
*/
export const updatePhoneDialCode = (
currentPhone: string,
oldCountry: string,
newCountry: string
): string => {
const trimmed = currentPhone.trim();
if (!trimmed) return "";
const oldRule = getCountryRuleByName(oldCountry);
const newRule = getCountryRuleByName(newCountry);
// Extract national digits without any dial code
let nationalDigits = "";
if (trimmed.startsWith("+")) {
const matched = [...COUNTRY_CODES]
.sort((a, b) => b.code.length - a.code.length)
.find((c) => trimmed.startsWith(c.code));
if (matched) {
nationalDigits = trimmed.slice(matched.code.length).replace(/\D/g, "");
} else {
nationalDigits = trimmed.replace(/^\+/, "").replace(/\D/g, "");
}
} else {
const oldDialDigits = oldRule.code.replace(/\D/g, "");
const rawDigits = trimmed.replace(/\D/g, "");
if (oldDialDigits && rawDigits.startsWith(oldDialDigits) && rawDigits.length > oldDialDigits.length) {
nationalDigits = rawDigits.slice(oldDialDigits.length);
} else {
nationalDigits = rawDigits;
}
}
const bounded = nationalDigits.slice(0, newRule.maxLength);
return bounded ? `${newRule.code} ${bounded}` : `${newRule.code} `;
};

View File

@ -1,39 +1,74 @@
import React from "react";
import { Pressable, StyleSheet, Text, View } from "react-native";
import React, { useState } from "react";
import { Pressable, StyleSheet, Text, TouchableOpacity, View } from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { useRouter } from "expo-router";
import { AuthColors } from "../constants/colors";
import {
moderateScale,
scale,
verticalScale,
} from "react-native-size-matters";
import { AuthColors } from "../constants/colors";
import { ENABLE_ENV_SWITCHER } from "@/config/environments";
import { useEnvironmentStore } from "@/store/environment.store";
import EnvironmentSelectorModal from "@/components/EnvironmentSelectorModal";
export default function LoginHeader() {
const router = useRouter();
const [modalVisible, setModalVisible] = useState(false);
const activeConfig = useEnvironmentStore((state) => state.getActiveConfig());
const badgeColor =
activeConfig.key === "prod"
? "#10B981"
: activeConfig.key === "qa"
? "#F59E0B"
: "#6B7280";
return (
<View style={styles.container}>
<Pressable
accessibilityRole="button"
accessibilityLabel="Go Back"
hitSlop={10}
onPress={() => router.back()}
style={styles.backButton}
>
<Ionicons
name="arrow-back"
size={moderateScale(24)}
/>
</Pressable>
<View style={styles.topRow}>
<Pressable
accessibilityRole="button"
accessibilityLabel="Go Back"
hitSlop={10}
onPress={() => router.back()}
style={styles.backButton}
>
<Ionicons
name="arrow-back"
size={moderateScale(24)}
/>
</Pressable>
{ENABLE_ENV_SWITCHER && (
<TouchableOpacity
style={styles.envPill}
onPress={() => setModalVisible(true)}
activeOpacity={0.7}
>
<View style={[styles.envDot, { backgroundColor: badgeColor }]} />
<Text style={styles.envPillText}>{activeConfig.badge}</Text>
<Ionicons
name="chevron-down"
size={moderateScale(12)}
color="#64748B"
/>
</TouchableOpacity>
)}
</View>
<View style={styles.textContainer}>
<Text style={styles.title}>Welcome Back!</Text>
<Text style={styles.subtitle}>
Login to continue
</Text>
<Text style={styles.subtitle}>Login to continue</Text>
</View>
{ENABLE_ENV_SWITCHER && (
<EnvironmentSelectorModal
visible={modalVisible}
onClose={() => setModalVisible(false)}
/>
)}
</View>
);
}
@ -44,11 +79,41 @@ const styles = StyleSheet.create({
marginBottom: verticalScale(32),
},
topRow: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
marginBottom: verticalScale(28),
},
backButton: {
width: scale(40),
height: scale(40),
justifyContent: "center",
marginBottom: verticalScale(28),
},
envPill: {
flexDirection: "row",
alignItems: "center",
gap: scale(5),
paddingHorizontal: scale(10),
paddingVertical: verticalScale(5),
backgroundColor: "#F1F5F9",
borderRadius: moderateScale(16),
borderWidth: 1,
borderColor: "#E2E8F0",
},
envDot: {
width: scale(7),
height: scale(7),
borderRadius: scale(3.5),
},
envPillText: {
fontSize: moderateScale(11),
fontWeight: "700",
color: "#334155",
},
textContainer: {
@ -66,4 +131,4 @@ const styles = StyleSheet.create({
color: AuthColors.textSecondary,
fontWeight: "500",
},
});
});

View File

@ -38,7 +38,6 @@ export function ContentPageHeader({
const effectiveTone = tone || contextTone;
const resolvedTitleColor =
titleColor ||
(effectiveTone && toneColors[effectiveTone]?.title) ||
Colors.textPrimary;
useFocusEffect(
useCallback(() => {

View File

@ -21,19 +21,19 @@ export const toneColors: Record<PageTone, ToneColorScheme> = {
accent: Colors.purple, // "#75649B"
soft: Colors.purpleSoft, // "#F6F3FA"
border: "#E8E2F2",
title: Colors.purple, // "#75649B"
title: Colors.textPrimary,
},
blue: {
accent: Colors.blue, // "#4E7496"
soft: Colors.blueSoft, // "#F1F6FA"
border: "#DAE6F0",
title: Colors.blue, // "#4E7496"
title: Colors.textPrimary,
},
green: {
accent: Colors.primary, // "#2E7D32"
soft: "#F2F8F4",
border: "#DCEADF",
title: Colors.primary, // "#2E7D32"
title: Colors.textPrimary,
},
};

View File

@ -1,5 +1,6 @@
import type { ImageSource } from "expo-image";
import type { ContentMediaItem } from "../types/media.types";
import { getActiveMediaBaseUrl } from "@/store/environment.store";
/**
* Resolve the final media URI using only primitive fields.
@ -18,7 +19,7 @@ export function resolveMediaUri(
return directUrl;
}
const mediaBaseUrl = (process.env.EXPO_PUBLIC_MEDIA_BASE_URL ?? "")
const mediaBaseUrl = (getActiveMediaBaseUrl() || (process.env.EXPO_PUBLIC_MEDIA_BASE_URL ?? ""))
.trim()
.replace(/\/+$/, "");

View File

@ -1,22 +1,43 @@
import React from "react";
import React, { useMemo } from "react";
import { ScrollView } from "react-native";
import type { DetailRendererProps } from "../types/renderer.types";
import { humanizeKey } from "./helpers/value";
import { ContentLinkAttributeSections } from "./shared/ContentLinkAttributeSections";
import { ContentValue } from "./shared/ContentValue";
import { Hero } from "./shared/Hero";
import { ImageGallery } from "./shared/ImageGallery";
import { SectionCard } from "./shared/SectionCard";
const RESERVED_KEYS = new Set(["code"]);
const RESERVED_KEYS = new Set(["code", "id", "slug", "sort_order", "link"]);
/**
* Renderer-independent detail fallback.
* Generic detail renderer for modules and catalog items.
*
* `data` has already been filtered/ordered through the presentation contract by
* ContentDetailScreen, so object insertion order is the intended display order.
* Each attribute is rendered in its own separate SectionCard.
* For therapeutics modules, the redundant Hero name card is hidden.
*/
export function GenericDetailRenderer({ content, data }: DetailRendererProps) {
export function GenericDetailRenderer({
content,
data,
moduleCode,
templateCode,
definitions,
presentationAttributes,
}: DetailRendererProps) {
const isTherapeutic = Boolean(
moduleCode?.toLowerCase().startsWith("m004") ||
templateCode?.toLowerCase().startsWith("m004")
);
const definitionMap = useMemo(
() =>
new Map(
(definitions ?? []).map((d) => [d.code, d.label]),
),
[definitions],
);
return (
<ScrollView
contentContainerStyle={{
@ -27,15 +48,31 @@ export function GenericDetailRenderer({ content, data }: DetailRendererProps) {
}}
showsVerticalScrollIndicator={false}
>
<Hero title={content.title || "Untitled content"} subtitle={content.summary ?? undefined} />
<Hero
title={content.title || "Untitled content"}
subtitle={content.summary ?? undefined}
/>
<ImageGallery images={[]} />
{Object.entries(data)
.filter(([key]) => !RESERVED_KEYS.has(key))
.map(([key, value]) => (
<SectionCard key={key} title={humanizeKey(key)}>
<ContentValue value={value} />
</SectionCard>
))}
.filter(
([key]) =>
!RESERVED_KEYS.has(key) &&
!(isTherapeutic && key.toLowerCase() === "name"),
)
.map(([key, value]) => {
const rawLabel = definitionMap.get(key) || key;
const label = humanizeKey(rawLabel);
return (
<SectionCard key={key} title={label}>
<ContentValue value={value} />
</SectionCard>
);
})}
<ContentLinkAttributeSections
data={data}
definitions={definitions}
presentationAttributes={presentationAttributes}
/>
</ScrollView>
);
}

View File

@ -1,12 +1,45 @@
import React from "react";
import React, { useMemo } from "react";
import { Pressable, Text, View } from "react-native";
import { asNumber, asString, asStringArray } from "../helpers/value";
import { CollectionScaffold } from "../shared/CollectionScaffold";
import { StandardIndexCard } from "../shared/StandardIndexCard";
import type { CollectionItemRendererProps, CollectionRendererProps } from "../../types/renderer.types";
import type {
CollectionItemRendererProps,
CollectionRendererProps,
SearchResultItem,
} from "../../types/renderer.types";
function sortWithExtraPointsAfterDu(items: SearchResultItem[]): SearchResultItem[] {
const isExtra = (item: SearchResultItem) => {
const name = (asString(item.attributes.name) || item.title || "").toLowerCase();
const code = (asString(item.attributes.code) || item.slug || "").toLowerCase();
return name.includes("extra") || code.includes("extra");
};
const extraItems = items.filter(isExtra);
const regularItems = items.filter((item) => !isExtra(item));
regularItems.sort((a, b) => {
const aOrder =
typeof a.attributes.sort_order === "number"
? a.attributes.sort_order
: 999;
const bOrder =
typeof b.attributes.sort_order === "number"
? b.attributes.sort_order
: 999;
return aOrder - bOrder;
});
return [...regularItems, ...extraItems];
}
export function MeridianIndexCollectionRenderer(props: CollectionRendererProps) {
return <CollectionScaffold {...props} />;
const sortedItems = useMemo(
() => sortWithExtraPointsAfterDu(props.items),
[props.items],
);
return <CollectionScaffold {...props} items={sortedItems} />;
}
export function MeridianCollectionRenderer(props: CollectionRendererProps) {
return <CollectionScaffold {...props} />;

View File

@ -1,11 +1,44 @@
import React from "react";
import React, { useMemo } from "react";
import { asString } from "../helpers/value";
import { CollectionScaffold } from "../shared/CollectionScaffold";
import { StandardIndexCard } from "../shared/StandardIndexCard";
import type { CollectionItemRendererProps, CollectionRendererProps } from "../../types/renderer.types";
import type {
CollectionItemRendererProps,
CollectionRendererProps,
SearchResultItem,
} from "../../types/renderer.types";
function sortWithExtraPointsAfterDu(items: SearchResultItem[]): SearchResultItem[] {
const isExtra = (item: SearchResultItem) => {
const name = (asString(item.attributes.name) || item.title || "").toLowerCase();
const code = (asString(item.attributes.code) || item.slug || "").toLowerCase();
return name.includes("extra") || code.includes("extra");
};
const extraItems = items.filter(isExtra);
const regularItems = items.filter((item) => !isExtra(item));
regularItems.sort((a, b) => {
const aOrder =
typeof a.attributes.sort_order === "number"
? a.attributes.sort_order
: 999;
const bOrder =
typeof b.attributes.sort_order === "number"
? b.attributes.sort_order
: 999;
return aOrder - bOrder;
});
return [...regularItems, ...extraItems];
}
export function AcuPointIndexCollectionRenderer(props: CollectionRendererProps) {
return <CollectionScaffold {...props} />;
const sortedItems = useMemo(
() => sortWithExtraPointsAfterDu(props.items),
[props.items],
);
return <CollectionScaffold {...props} items={sortedItems} />;
}
export function AcuPointCollectionRenderer(props: CollectionRendererProps) {
return <CollectionScaffold {...props} />;

View File

@ -206,7 +206,6 @@ export function FiveElementsDetailRenderer({
<SectionCard
key={idx}
title={sectionTitle}
defaultExpanded={false}
>
{sectionContent.length > 0 ? (
<Paragraphs items={sectionContent} />

View File

@ -1,21 +1,8 @@
import React from "react";
import { ScrollView } from "react-native";
import type { DetailRendererProps } from "../../types/renderer.types";
import { ContentLinkAttributeSections } from "../shared/ContentLinkAttributeSections";
import { asString } from "../helpers/value";
import { Hero } from "../shared/Hero"; import { ImageGallery } from "../shared/ImageGallery";
import { KeyValueGrid } from "../shared/KeyValueGrid";
import { SectionCard } from "../shared/SectionCard";
export function IndexEntryDetailRenderer({content,data,definitions,presentationAttributes}:DetailRendererProps){
const subtitle = asString(data.sub_title) || asString(data.subtitle) || undefined;
return (
<ScrollView contentContainerStyle={{paddingHorizontal:18,paddingTop:16,paddingBottom:40,gap:14}}>
<Hero title={content.title} subtitle={subtitle}/>
<ImageGallery images={[]}/>
<SectionCard title="Details">
<KeyValueGrid rows={Object.entries(data).filter(([,v])=>typeof v==="string"||typeof v==="number").map(([k,v])=>({label:k,value:String(v)}))}/>
</SectionCard>
<ContentLinkAttributeSections data={data} definitions={definitions} presentationAttributes={presentationAttributes}/>
</ScrollView>
);
import { GenericDetailRenderer } from "../GenericDetailRenderer";
export function IndexEntryDetailRenderer(props: DetailRendererProps) {
return <GenericDetailRenderer {...props} />;
}

View File

@ -67,27 +67,10 @@ export const collectionRenderers: Readonly<Record<string, CollectionRendererComp
chinese_scalp_acupuncture_collection: ModuleCatalogCollectionRenderer,
nutrition_food_collection: ModuleCatalogCollectionRenderer,
nutrition_effect_collection: ModuleCatalogCollectionRenderer,
m0042_ct0001_collection: ModuleCatalogCollectionRenderer,
m0016_ct0001_collection: FourLevelsCollectionRenderer,
m0011_ct0005_collection: EightPrinciplesCollectionRenderer,
m0014_ct0001_collection: PathogenicFactorsCollectionRenderer,
five_elements_collection: FiveElementsCollectionRenderer,
m0019_ct0005_collection: FiveElementsCollectionRenderer,
qi_blood_collection: QiBloodCollectionRenderer,
m0013_ct0001_collection: QiBloodCollectionRenderer,
twelve_channels_collection: TwelveChannelsCollectionRenderer,
m0018_ct0002_collection: TwelveChannelsCollectionRenderer,
three_burners_collection: ThreeBurnersCollectionRenderer,
m0017_ct0002_collection: ThreeBurnersCollectionRenderer,
six_stages_collection: SixStagesCollectionRenderer,
m0015_ct0001_collection: SixStagesCollectionRenderer,
m0015_ct0002_collection: SixStagesCollectionRenderer,
m0015_ct0003_collection: SixStagesCollectionRenderer,
m0015_ct0004_collection: SixStagesCollectionRenderer,
m0015_ct0005_collection: SixStagesCollectionRenderer,
m0015_ct0006_collection: SixStagesCollectionRenderer,
tcm_pattern_list_collection: ModuleCatalogCollectionRenderer,
m0012_ct0001_collection: ModuleCatalogCollectionRenderer,
disease_collection: ModuleCatalogCollectionRenderer,
auriculotherapy_collection: ModuleCatalogCollectionRenderer,
// Module-specific renderers removed for generic handling
});
export const collectionItemRenderers: Readonly<Record<string, CollectionItemRendererComponent>> = Object.freeze({
module_catalog_card: ModuleCatalogCardRenderer,
@ -107,26 +90,10 @@ export const collectionItemRenderers: Readonly<Record<string, CollectionItemRend
chinese_scalp_acupuncture_card: ModuleCatalogCardRenderer,
nutrition_food_card: ModuleCatalogCardRenderer,
nutrition_effect_card: ModuleCatalogCardRenderer,
m0042_ct0001_card: ModuleCatalogCardRenderer,
m0016_ct0001_card: FourLevelsCardRenderer,
m0011_ct0005_card: EightPrinciplesCardRenderer,
m0014_ct0001_card: PathogenicFactorsCardRenderer,
m0019_ct0005_card: FiveElementsCardRenderer,
qi_blood_card: QiBloodCardRenderer,
m0013_ct0001_card: QiBloodCardRenderer,
twelve_channels_card: TwelveChannelsCardRenderer,
m0018_ct0002_card: TwelveChannelsCardRenderer,
three_burners_card: ThreeBurnersCardRenderer,
m0017_ct0002_card: ThreeBurnersCardRenderer,
six_stages_card: SixStagesCardRenderer,
m0015_ct0001_card: SixStagesCardRenderer,
m0015_ct0002_card: SixStagesCardRenderer,
m0015_ct0003_card: SixStagesCardRenderer,
m0015_ct0004_card: SixStagesCardRenderer,
m0015_ct0005_card: SixStagesCardRenderer,
m0015_ct0006_card: SixStagesCardRenderer,
tcm_pattern_list_card: ModuleCatalogCardRenderer,
m0012_ct0001_card: ModuleCatalogCardRenderer,
disease_card: ModuleCatalogCardRenderer,
auriculotherapy_card: ModuleCatalogCardRenderer,
// Module-specific card renderers removed for generic handling
});
export const detailRenderers: Readonly<Record<string, DetailRendererComponent>> = Object.freeze({
extra_ordinary_vessel_detail: ExtraOrdinaryVesselsDetailRenderer,
@ -164,10 +131,8 @@ export const detailRenderers: Readonly<Record<string, DetailRendererComponent>>
chinese_scalp_acupuncture_detail: AcuPointDetailRenderer,
nutrition_food_detail: GenericDetailRenderer,
nutrition_effect_detail: GenericDetailRenderer,
m0042_ct0001_detail: IndexEntryDetailRenderer,
m0042_ct0002_detail: IndexEntryDetailRenderer,
m0042_ct0003_detail: IndexEntryDetailRenderer,
m0042_ct0004_detail: IndexEntryDetailRenderer,
disease_detail: GenericDetailRenderer,
auriculotherapy_detail: GenericDetailRenderer,
m0016_ct0002_detail: FourLevelsDetailRenderer,
m0011_ct0001_detail: EightPrinciplesDetailRenderer,
m0011_ct0002_detail: EightPrinciplesDetailRenderer,
@ -233,6 +198,10 @@ export function resolveCollectionRenderer(
if (normalizedTemplate === "m0016_ct0001" || normalizedModule === "m0016") {
return FourLevelsCollectionRenderer;
}
// Generic fallback for any mXXXX_ct... template
if (normalizedTemplate?.startsWith("m") && normalizedTemplate?.includes("_ct")) {
return ModuleCatalogCollectionRenderer;
}
if (normalizedTemplate === "m0011_ct0005" || normalizedModule === "m0011") {
return EightPrinciplesCollectionRenderer;
}
@ -304,6 +273,10 @@ export function resolveCollectionItemRenderer(
if (normalizedTemplate === "m0017_ct0002" || (normalizedModule === "m0017" && normalizedTemplate?.includes("ct0002"))) {
return ThreeBurnersCardRenderer;
}
// Generic fallback for any mXXXX_ct... template
if (normalizedTemplate?.startsWith("m") && normalizedTemplate?.includes("_ct")) {
return ModuleCatalogCardRenderer;
}
if (
normalizedTemplate?.startsWith("m0015_ct000") &&
normalizedTemplate !== "m0015_ct0007"
@ -410,6 +383,10 @@ export function resolveDetailRenderer(
return ExtraOrdinaryVesselsDetailRenderer;
}
// Generic fallback for any mXXXX_ct... template
if (normalizedTemplate?.startsWith("m") && normalizedTemplate?.includes("_ct")) {
return GenericDetailRenderer;
}
if (code && detailRenderers[code]) return detailRenderers[code];
reportMissingRenderer("detail", code);
return GenericDetailRenderer;

View File

@ -11,7 +11,7 @@ export function ContentCountBadge({
count: number | null;
label?: string;
}) {
if (count === null) return null;
if (count === null || count <= 0) return null;
return (
<View style={styles.badge}>

View File

@ -152,6 +152,25 @@ export function ContentValue({
);
}
if (typeof value === "string") {
const text = value.trim();
if (text.includes("\n") || text.includes(";")) {
const bullets = parseBullets(text);
if (bullets.length > 1) {
return <BulletList items={bullets} />;
}
}
if (text.includes(",")) {
const parts = parseBullets(text);
if (
parts.length > 1 &&
parts.every((p) => p.length > 0 && p.length < 50 && !p.endsWith("."))
) {
return <BulletList items={parts} />;
}
}
}
return (
<Text style={[styles.text, textStyle]}>
{typeof value === "boolean" ? (value ? "Yes" : "No") : String(value)}

View File

@ -57,11 +57,30 @@ export function CollectionTemplateScreen({
const merged = useMemo(() => {
const pages = query.data?.pages ?? [];
const items = pages.flatMap((page) => page.items);
if (templateCode === "m0001_ct0002") {
const isExtra = (item: (typeof items)[0]) => {
const name = (item.attributes?.name ? String(item.attributes.name) : item.title || "").toLowerCase();
const code = (item.attributes?.code ? String(item.attributes.code) : item.slug || "").toLowerCase();
return name.includes("extra") || code.includes("extra");
};
const extraItems = items.filter(isExtra);
const regularItems = items.filter((item) => !isExtra(item));
regularItems.sort((a, b) => {
const aOrder = typeof a.attributes?.sort_order === "number" ? (a.attributes.sort_order as number) : 999;
const bOrder = typeof b.attributes?.sort_order === "number" ? (b.attributes.sort_order as number) : 999;
return aOrder - bOrder;
});
return {
total: pages[0]?.total ?? 0,
items: [...regularItems, ...extraItems],
};
}
return {
total: pages[0]?.total ?? 0,
items: pages.flatMap((page) => page.items),
items,
};
}, [query.data]);
}, [query.data, templateCode]);
const collectionRendererCode = contract.presentation.renderers.collection;
const itemRendererCode = contract.presentation.renderers.collection_item;
@ -134,8 +153,13 @@ export function CollectionTemplateScreen({
const isCatalog =
collectionRendererCode === "module_catalog_collection" ||
itemRendererCode === "module_catalog_card" ||
collectionRendererCode === "disease_collection" ||
itemRendererCode === "disease_card" ||
collectionRendererCode === "auriculotherapy_collection" ||
itemRendererCode === "auriculotherapy_card" ||
templateCode === "m0001_ct0001" ||
templateCode === "m0002_ct0001";
templateCode === "m0002_ct0001" ||
templateCode === "m0041_ct0001";
const pageTone: PageTone = isCatalog ? "green" : "purple";
return (

View File

@ -19,7 +19,11 @@ import DropdownField from "@/components/forms/DropdownField";
import FieldLabel from "@/components/forms/FieldLabel";
import PrimaryButton from "@/components/buttons/PrimaryButton";
import { Colors } from "@/theme";
import { validatePhoneNumber } from "@/constants/countries";
import {
getCountryRuleByName,
updatePhoneDialCode,
validatePhoneNumber,
} from "@/constants/countries";
interface EditProfileFormProps {
initialName?: string;
@ -54,24 +58,27 @@ export const isValidPhoneNumber = (val?: string, country?: string): boolean => {
return validatePhoneNumber(val, undefined, country) === null;
};
const cleanPhoneInput = (text: string): string => {
const cleanPhoneInput = (text: string, maxLength = 16): string => {
const trimmedStart = text.trimStart();
const hasPlus = trimmedStart.startsWith("+");
const rest = hasPlus ? trimmedStart.slice(1) : text;
const filtered = rest.replace(/[^0-9\s\-()]/g, "");
// Disallow all non-digits except a single separating space after country code
// Specifically strip hyphens, dashes, parentheses, underscores, and letters
const noDashes = rest.replace(/[\-()_a-zA-Z]/g, "");
const normalized = noDashes.replace(/\s+/g, " ");
let digitCount = 0;
let bounded = "";
for (const ch of filtered) {
let result = "";
for (const ch of normalized) {
if (/\d/.test(ch)) {
if (digitCount < 15) {
if (digitCount < maxLength) {
digitCount++;
bounded += ch;
result += ch;
}
} else {
bounded += ch;
} else if (ch === " " && digitCount > 0 && !result.includes(" ")) {
result += ch;
}
}
return hasPlus ? `+${bounded}` : bounded;
return hasPlus ? `+${result}` : result;
};
export default function EditProfileForm({
@ -89,6 +96,8 @@ export default function EditProfileForm({
const [phoneError, setPhoneError] = useState("");
const [showCountryModal, setShowCountryModal] = useState(false);
const activeRule = getCountryRuleByName(country);
useEffect(() => {
setFullName(initialName);
}, [initialName]);
@ -118,6 +127,16 @@ export default function EditProfileForm({
}
};
const handleCountrySelect = (newCountry: string) => {
if (newCountry !== country) {
const updatedPhone = updatePhoneDialCode(phone, country, newCountry);
setPhone(updatedPhone);
setCountry(newCountry);
if (phoneError) setPhoneError("");
}
setShowCountryModal(false);
};
const handleSave = () => {
let hasError = false;
setNameError("");
@ -131,7 +150,8 @@ export default function EditProfileForm({
const trimmedPhone = phone.trim();
if (trimmedPhone) {
const err = validatePhoneNumber(trimmedPhone, undefined, country);
const rule = getCountryRuleByName(country);
const err = validatePhoneNumber(trimmedPhone, rule.code, country);
if (err) {
setPhoneError(err);
hasError = true;
@ -140,7 +160,20 @@ export default function EditProfileForm({
if (hasError) return;
onSave?.(trimmedName, trimmedPhone, country);
// Normalize phone before saving: ensure no spaces or hyphens, formatted as +<dialCode><nationalDigits>
let normalizedPhone = "";
if (trimmedPhone) {
const rule = getCountryRuleByName(country);
const digitsOnly = trimmedPhone.replace(/\D/g, "");
const dialDigits = rule.code.replace(/\D/g, "");
let localDigits = digitsOnly;
if (digitsOnly.startsWith(dialDigits) && digitsOnly.length > dialDigits.length) {
localDigits = digitsOnly.slice(dialDigits.length);
}
normalizedPhone = `${rule.code}${localDigits}`;
}
onSave?.(trimmedName, normalizedPhone, country);
};
return (
@ -177,9 +210,9 @@ export default function EditProfileForm({
<BaseTextInput
value={phone}
onChangeText={handlePhoneChange}
placeholder="e.g. +91 9876543210"
placeholder={activeRule.placeholder ? `e.g. ${activeRule.code} ${activeRule.placeholder}` : `e.g. ${activeRule.code} 9876543210`}
keyboardType="phone-pad"
maxLength={16}
maxLength={activeRule.maxLength + activeRule.code.length + 2}
textContentType="telephoneNumber"
autoCapitalize="none"
autoCorrect={false}
@ -187,7 +220,9 @@ export default function EditProfileForm({
/>
{!phoneError && (
<Text style={styles.helperText}>
Enter mobile number with country code for login and notifications.
{activeRule.minLength === activeRule.maxLength
? `${activeRule.country} (${activeRule.code}): Requires exactly ${activeRule.maxLength} digits`
: `${activeRule.country} (${activeRule.code}): ${activeRule.minLength} to ${activeRule.maxLength} digits`}
</Text>
)}
</View>
@ -249,10 +284,7 @@ export default function EditProfileForm({
isSelected && styles.countryItemSelected,
pressed && styles.countryItemPressed,
]}
onPress={() => {
setCountry(c);
setShowCountryModal(false);
}}
onPress={() => handleCountrySelect(c)}
>
<Text
style={[

View File

@ -1,12 +1,300 @@
import React from "react";
import { ActivityIndicator, FlatList, Pressable, StyleSheet, Text, View } from "react-native";
import {
ActivityIndicator,
FlatList,
Pressable,
ScrollView,
StyleSheet,
Text,
View,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { Colors } from "@/theme";
import type { FacetedSearchItem } from "../types/search.types";
import type { FacetedSearchItem, SearchModuleOption } from "../types/search.types";
interface Props { items: FacetedSearchItem[]; total: number; loading: boolean; fetchingMore: boolean; onLoadMore:()=>void; onPress:(item:FacetedSearchItem)=>void; }
export function SearchResultList({items,total,loading,fetchingMore,onLoadMore,onPress}:Props){
if(loading&&!items.length) return <View style={styles.center}><ActivityIndicator color={Colors.primary}/><Text style={styles.muted}>Searching content…</Text></View>;
return <FlatList data={items} keyExtractor={(item)=>item.content_id} contentContainerStyle={items.length?styles.list:styles.empty} ListHeaderComponent={items.length?<Text style={styles.count}>{total} result{total===1?"":"s"}</Text>:null} renderItem={({item})=><Pressable onPress={()=>onPress(item)} style={({pressed})=>[styles.card,pressed&&styles.pressed]}><View style={styles.cardText}><Text style={styles.title}>{item.title}</Text><Text style={styles.meta}>{item.module_name} · {item.template_name}</Text>{item.summary?<Text numberOfLines={2} style={styles.summary}>{item.summary}</Text>:null}</View><Ionicons name="chevron-forward" size={20} color={Colors.textSecondary}/></Pressable>} ListEmptyComponent={<View style={styles.center}><Ionicons name="search-outline" size={30} color={Colors.textSecondary}/><Text style={styles.emptyTitle}>No matching content</Text><Text style={styles.muted}>Try a broader scope or remove one of the filters.</Text></View>} ListFooterComponent={fetchingMore?<ActivityIndicator style={{margin:18}} color={Colors.primary}/>:null} onEndReached={onLoadMore} onEndReachedThreshold={.35}/>;
interface Props {
items: FacetedSearchItem[];
total: number;
loading: boolean;
fetchingMore: boolean;
onLoadMore: () => void;
onPress: (item: FacetedSearchItem) => void;
matchingModules?: SearchModuleOption[];
onSelectModule?: (module: SearchModuleOption) => void;
activeModuleCode?: string | null;
}
const styles=StyleSheet.create({list:{paddingHorizontal:20,paddingBottom:28},empty:{flexGrow:1},count:{paddingVertical:9,fontSize:12,fontWeight:"700",color:Colors.textSecondary},card:{flexDirection:"row",alignItems:"center",gap:12,padding:15,marginBottom:10,borderRadius:16,backgroundColor:Colors.white,borderWidth:1,borderColor:"#EEF0F2",shadowColor:"#000",shadowOpacity:.05,shadowRadius:6,shadowOffset:{width:0,height:2},elevation:1},pressed:{opacity:.75},cardText:{flex:1},title:{fontSize:16,fontWeight:"800",color:Colors.textPrimary},meta:{marginTop:3,fontSize:11.5,fontWeight:"600",color:Colors.primaryDark},summary:{marginTop:6,fontSize:12.5,lineHeight:18,color:Colors.textSecondary},center:{flex:1,alignItems:"center",justifyContent:"center",padding:32},emptyTitle:{marginTop:8,fontSize:16,fontWeight:"800",color:Colors.textPrimary},muted:{marginTop:5,textAlign:"center",fontSize:12.5,color:Colors.textSecondary}});
export function SearchResultList({
items,
total,
loading,
fetchingMore,
onLoadMore,
onPress,
matchingModules = [],
onSelectModule,
activeModuleCode,
}: Props) {
if (loading && !items.length && !matchingModules.length) {
return (
<View style={styles.center}>
<ActivityIndicator color={Colors.primary} />
<Text style={styles.muted}>Searching content…</Text>
</View>
);
}
const headerComponent = (
<View style={styles.headerWrapper}>
{matchingModules.length > 0 ? (
<View style={styles.modulesSection}>
<Text style={styles.modulesHeading}>
Matching Modules ({matchingModules.length})
</Text>
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
contentContainerStyle={styles.modulesScroll}
>
{matchingModules.map((mod) => {
const isActive = activeModuleCode === mod.code;
return (
<Pressable
key={mod.code}
style={[
styles.moduleCard,
isActive && styles.moduleCardActive,
]}
onPress={() => onSelectModule?.(mod)}
>
<View style={styles.moduleIconBox}>
<Ionicons
name="layers-outline"
size={16}
color={isActive ? Colors.white : Colors.primaryDark}
/>
</View>
<View style={styles.moduleTextContainer}>
<Text
numberOfLines={1}
style={[
styles.moduleName,
isActive && styles.moduleNameActive,
]}
>
{mod.name}
</Text>
<Text
style={[
styles.moduleBadge,
isActive && styles.moduleBadgeActive,
]}
>
{isActive ? "Filtered" : "Filter by module"}
</Text>
</View>
<Ionicons
name={isActive ? "close-circle" : "chevron-forward"}
size={14}
color={isActive ? Colors.white : Colors.textSecondary}
/>
</Pressable>
);
})}
</ScrollView>
</View>
) : null}
{items.length > 0 ? (
<Text style={styles.count}>
{total} result{total === 1 ? "" : "s"}
</Text>
) : null}
</View>
);
return (
<FlatList
data={items}
keyExtractor={(item) => item.content_id}
contentContainerStyle={items.length ? styles.list : styles.empty}
ListHeaderComponent={headerComponent}
renderItem={({ item }) => (
<Pressable
onPress={() => onPress(item)}
style={({ pressed }) => [styles.card, pressed && styles.pressed]}
>
<View style={styles.cardText}>
<Text style={styles.title}>{item.title}</Text>
<Text style={styles.meta}>
{item.module_name} · {item.template_name}
</Text>
{item.summary ? (
<Text numberOfLines={2} style={styles.summary}>
{item.summary}
</Text>
) : null}
</View>
<Ionicons
name="chevron-forward"
size={20}
color={Colors.textSecondary}
/>
</Pressable>
)}
ListEmptyComponent={
!loading ? (
<View style={styles.center}>
<Ionicons
name="search-outline"
size={30}
color={Colors.textSecondary}
/>
<Text style={styles.emptyTitle}>No matching content</Text>
<Text style={styles.muted}>
Try a broader search term or remove one of the filters.
</Text>
</View>
) : null
}
ListFooterComponent={
fetchingMore ? (
<ActivityIndicator style={{ margin: 18 }} color={Colors.primary} />
) : null
}
onEndReached={onLoadMore}
onEndReachedThreshold={0.35}
/>
);
}
const styles = StyleSheet.create({
list: {
paddingHorizontal: 20,
paddingBottom: 28,
},
empty: {
flexGrow: 1,
paddingHorizontal: 20,
},
headerWrapper: {
paddingBottom: 4,
},
modulesSection: {
marginBottom: 12,
marginTop: 6,
},
modulesHeading: {
fontSize: 12,
fontWeight: "800",
color: Colors.textSecondary,
textTransform: "uppercase",
marginBottom: 8,
letterSpacing: 0.5,
},
modulesScroll: {
gap: 8,
paddingRight: 10,
},
moduleCard: {
flexDirection: "row",
alignItems: "center",
gap: 8,
paddingVertical: 8,
paddingHorizontal: 12,
borderRadius: 12,
backgroundColor: "#F3F7F5",
borderWidth: 1,
borderColor: "#E2ECE6",
},
moduleCardActive: {
backgroundColor: Colors.primary,
borderColor: Colors.primary,
},
moduleIconBox: {
justifyContent: "center",
alignItems: "center",
},
moduleTextContainer: {
maxWidth: 180,
},
moduleName: {
fontSize: 13,
fontWeight: "700",
color: Colors.textPrimary,
},
moduleNameActive: {
color: Colors.white,
},
moduleBadge: {
fontSize: 10,
color: Colors.textSecondary,
marginTop: 1,
},
moduleBadgeActive: {
color: "rgba(255,255,255,0.85)",
},
count: {
paddingVertical: 9,
fontSize: 12,
fontWeight: "700",
color: Colors.textSecondary,
},
card: {
flexDirection: "row",
alignItems: "center",
gap: 12,
padding: 15,
marginBottom: 10,
borderRadius: 16,
backgroundColor: Colors.white,
borderWidth: 1,
borderColor: "#EEF0F2",
shadowColor: "#000",
shadowOpacity: 0.05,
shadowRadius: 6,
shadowOffset: { width: 0, height: 2 },
elevation: 1,
},
pressed: {
opacity: 0.75,
},
cardText: {
flex: 1,
},
title: {
fontSize: 16,
fontWeight: "800",
color: Colors.textPrimary,
},
meta: {
marginTop: 3,
fontSize: 11.5,
fontWeight: "600",
color: Colors.primaryDark,
},
summary: {
marginTop: 6,
fontSize: 12.5,
lineHeight: 18,
color: Colors.textSecondary,
},
center: {
flex: 1,
alignItems: "center",
justifyContent: "center",
padding: 32,
},
emptyTitle: {
marginTop: 8,
fontSize: 16,
fontWeight: "800",
color: Colors.textPrimary,
},
muted: {
marginTop: 5,
textAlign: "center",
fontSize: 12.5,
color: Colors.textSecondary,
},
});

View File

@ -1,4 +1,4 @@
import { useInfiniteQuery } from "@tanstack/react-query";
import { keepPreviousData, useInfiniteQuery } from "@tanstack/react-query";
import { useSettingsStore } from "@/store/settings.store";
import { searchContents } from "../api/search.api";
import type { FacetedSearchRequest } from "../types/search.types";
@ -24,8 +24,10 @@ export function useFacetedSearch(
queryFn: ({ pageParam }) =>
searchContents({ ...request, page: pageParam }, preview),
initialPageParam: 1,
placeholderData: keepPreviousData,
enabled,
getNextPageParam: (last) =>
last.page * last.page_size < last.total ? last.page + 1 : undefined,
});
}

View File

@ -1,4 +1,4 @@
import React, { useEffect, useMemo, useState } from "react";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { Platform, Pressable, StyleSheet, Text, TextInput, View } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { Ionicons } from "@expo/vector-icons";
@ -18,6 +18,7 @@ import type {
FacetFilter,
FilterLogic,
SearchFacetDefinition,
SearchModuleOption,
SearchScope,
} from "../types/search.types";
@ -147,6 +148,38 @@ export default function FacetedSearchScreen({
);
};
const matchingModules = useMemo(() => {
const q = (debouncedQuery || query).trim().toLowerCase();
if (!q || isModuleMode || !capabilities.data?.modules) return [];
const tokens = q.split(/\s+/).filter(Boolean);
return capabilities.data.modules.filter((m) => {
const name = m.name.toLowerCase();
const code = m.code.toLowerCase();
if (name.includes(q) || code.includes(q)) return true;
return tokens.some(
(tok) => tok.length >= 2 && (name.includes(tok) || code.includes(tok)),
);
});
}, [debouncedQuery, query, isModuleMode, capabilities.data?.modules]);
const activeModuleCode = useMemo(() => {
return effectiveScope.module_codes?.length === 1
? effectiveScope.module_codes[0]
: null;
}, [effectiveScope.module_codes]);
const handleToggleModuleScope = useCallback(
(module: SearchModuleOption) => {
const currentCodes = effectiveScope.module_codes ?? [];
const isAlreadySelected = currentCodes.includes(module.code);
handleScopeChange({
...effectiveScope,
module_codes: isAlreadySelected ? null : [module.code],
});
},
[effectiveScope, handleScopeChange],
);
return (
<SafeAreaView style={styles.safe} edges={["top", "left", "right"]}>
<View style={styles.header}>
@ -285,6 +318,9 @@ export default function FacetedSearchScreen({
total={merged.total}
loading={capabilities.isLoading || search.isLoading}
fetchingMore={search.isFetchingNextPage}
matchingModules={matchingModules}
onSelectModule={handleToggleModuleScope}
activeModuleCode={activeModuleCode}
onLoadMore={() => {
if (search.hasNextPage && !search.isFetchingNextPage) {
void search.fetchNextPage();

View File

@ -1,6 +1,7 @@
import React, { useCallback, useEffect, useMemo, useRef } from "react";
import {
Platform,
Pressable,
ScrollView,
StyleSheet,
Text,
@ -10,7 +11,7 @@ import {
import { SafeAreaView } from "react-native-safe-area-context";
import { router, useFocusEffect } from "expo-router";
import { Ionicons } from "@expo/vector-icons";
import { moderateScale, verticalScale } from "react-native-size-matters";
import { moderateScale, scale, verticalScale } from "react-native-size-matters";
import { Colors } from "@/theme";
import { useAuthStore } from "@/store/auth.store";
@ -152,14 +153,28 @@ export default function ModulesIndexScreen() {
<SafeAreaView style={styles.safeArea} edges={["top", "left", "right"]}>
<View style={styles.container}>
<View style={styles.header}>
<TouchableOpacity
onPress={() => router.replace("/")}
style={styles.backButton}
<Pressable
accessibilityRole="button"
accessibilityLabel="Go to home"
accessibilityLabel="Go back"
hitSlop={{ top: 12, bottom: 12, left: 12, right: 12 }}
onPress={() => {
if (router.canGoBack()) {
router.back();
} else {
router.replace("/");
}
}}
style={({ pressed }) => [
styles.backButton,
pressed && styles.backButtonPressed,
]}
>
<Ionicons name="chevron-back" size={24} color={Colors.textPrimary} />
</TouchableOpacity>
<Ionicons
name="chevron-back"
size={moderateScale(24)}
color={Colors.textPrimary}
/>
</Pressable>
<Text style={styles.headerTitle}>All Modules</Text>
<View style={styles.headerActions}>
{isPreviewAdmin ? (
@ -333,7 +348,15 @@ const styles = StyleSheet.create({
backgroundColor: "#FFFFFF",
},
backButton: {
padding: 4,
width: scale(38),
height: scale(38),
borderRadius: scale(19),
justifyContent: "center",
alignItems: "center",
backgroundColor: "#F1F5F9",
},
backButtonPressed: {
backgroundColor: "#E2E8F0",
},
headerTitle: {
fontSize: moderateScale(18),

View File

@ -20,7 +20,7 @@ import EditProfileForm from "@/features/profile/components/EditProfileForm";
import EditProfileAvatar from "@/features/profile/components/EditProfileAvatar";
import { useAuthStore } from "@/store/auth.store";
import { apiClient } from "@/api";
import { validatePhoneNumber } from "@/constants/countries";
import { getCountryRuleByName, validatePhoneNumber } from "@/constants/countries";
export default function EditProfileScreen() {
const user = useAuthStore((state) => state.user);
@ -42,7 +42,8 @@ export default function EditProfileScreen() {
const trimmedCountry = updatedCountry.trim();
if (trimmedPhone) {
const errMsg = validatePhoneNumber(trimmedPhone, undefined, trimmedCountry);
const rule = getCountryRuleByName(trimmedCountry);
const errMsg = validatePhoneNumber(trimmedPhone, rule.code, trimmedCountry);
if (errMsg) {
if (Platform.OS === "web") {
window.alert(errMsg);

View File

@ -1,4 +1,4 @@
import React from "react";
import React, { useState } from "react";
import {
Alert,
Platform,
@ -22,8 +22,13 @@ import {
import { SettingsItem } from "@/features/settings/types";
import { useAuthStore } from "@/store/auth.store";
import { useSettingsStore } from "@/store/settings.store";
import { ENABLE_ENV_SWITCHER } from "@/config/environments";
import { useEnvironmentStore } from "@/store/environment.store";
import EnvironmentSelectorModal from "@/components/EnvironmentSelectorModal";
export default function SettingsScreen() {
const [envModalVisible, setEnvModalVisible] = useState(false);
const activeConfig = useEnvironmentStore((state) => state.getActiveConfig());
const user = useAuthStore((state) => state.user);
const logout = useAuthStore((state) => state.logout);
@ -68,6 +73,18 @@ export default function SettingsScreen() {
]
: []),
...PREFERENCE_SETTINGS,
...(ENABLE_ENV_SWITCHER
? [
{
id: "server-environment",
title: "Server Environment",
subtitle: `${activeConfig.label} (${activeConfig.badge})`,
icon: "server-outline" as const,
value: activeConfig.badge,
onPress: () => setEnvModalVisible(true),
},
]
: []),
];
const handleLogout = () => {
@ -129,6 +146,13 @@ export default function SettingsScreen() {
<LogoutButton onPress={handleLogout} />
</View>
</ScrollView>
{ENABLE_ENV_SWITCHER && (
<EnvironmentSelectorModal
visible={envModalVisible}
onClose={() => setEnvModalVisible(false)}
/>
)}
</SafeAreaView>
);
}

View File

@ -0,0 +1,117 @@
import AsyncStorage from "@react-native-async-storage/async-storage";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import {
DEFAULT_ENV_LABEL,
ENABLE_ENV_SWITCHER,
ENVIRONMENTS,
EnvironmentConfig,
EnvironmentKey,
} from "@/config/environments";
import { clearApiAccessToken } from "@/api/access-token";
import { queryClient } from "@/lib/query/query-client";
import { useAuthStore } from "@/store/auth.store";
interface EnvironmentStore {
currentEnv: EnvironmentKey;
setEnvironment: (env: EnvironmentKey) => void;
getActiveConfig: () => {
key: EnvironmentKey;
label: string;
badge: string;
apiUrl: string;
storefrontUrl: string;
mediaBaseUrl: string;
};
getApiUrl: () => string;
getStorefrontUrl: () => string;
getMediaBaseUrl: () => string;
switchEnvironment: (env: EnvironmentKey) => Promise<void>;
}
const getDefaultApiUrl = () =>
process.env.EXPO_PUBLIC_API_URL ??
process.env.EXPO_PUBLIC_API_BASE_URL ??
"http://localhost:8000/api";
const getDefaultStorefrontUrl = () =>
process.env.EXPO_PUBLIC_STOREFRONT_URL?.trim() ?? "https://acupedia.in/store";
const getDefaultMediaBaseUrl = () =>
process.env.EXPO_PUBLIC_MEDIA_BASE_URL?.trim() ?? "";
export const useEnvironmentStore = create<EnvironmentStore>()(
persist(
(set, get) => ({
currentEnv: "default",
setEnvironment: (currentEnv: EnvironmentKey) => set({ currentEnv }),
getActiveConfig: () => {
const { currentEnv } = get();
if (!ENABLE_ENV_SWITCHER || currentEnv === "default") {
return {
key: "default" as EnvironmentKey,
label: DEFAULT_ENV_LABEL,
badge: "DEFAULT",
apiUrl: getDefaultApiUrl(),
storefrontUrl: getDefaultStorefrontUrl(),
mediaBaseUrl: getDefaultMediaBaseUrl(),
};
}
const preset = ENVIRONMENTS[currentEnv];
return {
key: preset.key,
label: preset.label,
badge: preset.badge,
apiUrl: preset.apiUrl,
storefrontUrl: preset.storefrontUrl,
mediaBaseUrl: preset.mediaBaseUrl,
};
},
getApiUrl: () => {
return get().getActiveConfig().apiUrl;
},
getStorefrontUrl: () => {
return get().getActiveConfig().storefrontUrl;
},
getMediaBaseUrl: () => {
return get().getActiveConfig().mediaBaseUrl;
},
switchEnvironment: async (env: EnvironmentKey) => {
set({ currentEnv: env });
// 1. Wipe current auth session across memory and storage
clearApiAccessToken();
await useAuthStore.getState().logout();
// 2. Clear query caches so no stale data from old env is retained
queryClient.clear();
},
}),
{
name: "acupedia-environment-storage",
storage: createJSONStorage(() => AsyncStorage),
partialize: (state) => ({ currentEnv: state.currentEnv }),
}
)
);
export function getActiveApiUrl(): string {
return useEnvironmentStore.getState().getApiUrl();
}
export function getActiveStorefrontUrl(): string {
return useEnvironmentStore.getState().getStorefrontUrl();
}
export function getActiveMediaBaseUrl(): string {
return useEnvironmentStore.getState().getMediaBaseUrl();
}