Compare commits

..

No commits in common. "main" and "extra-ordinary-vessel" have entirely different histories.

121 changed files with 1752 additions and 6992 deletions

12
.env
View File

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

2
.gitignore vendored
View File

@ -1,5 +1,7 @@
# Learn more https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files # Learn more https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files
android/
# dependencies # dependencies
node_modules/ node_modules/

View File

@ -11,7 +11,7 @@ def projectRoot = rootDir.getAbsoluteFile().getParentFile().getAbsolutePath()
react { react {
entryFile = file(["node", "-e", "require('expo/scripts/resolveAppEntry')", projectRoot, "android", "absolute"].execute(null, rootDir).text.trim()) entryFile = file(["node", "-e", "require('expo/scripts/resolveAppEntry')", projectRoot, "android", "absolute"].execute(null, rootDir).text.trim())
reactNativeDir = new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsoluteFile() reactNativeDir = new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsoluteFile()
// hermesCommand = new File(["node", "--print", "require.resolve('hermes-compiler/package.json', { paths: [require.resolve('react-native/package.json')] })"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/hermesc/%OS-BIN%/hermesc" hermesCommand = new File(["node", "--print", "require.resolve('hermes-compiler/package.json', { paths: [require.resolve('react-native/package.json')] })"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/hermesc/%OS-BIN%/hermesc"
codegenDir = new File(["node", "--print", "require.resolve('@react-native/codegen/package.json', { paths: [require.resolve('react-native/package.json')] })"].execute(null, rootDir).text.trim()).getParentFile().getAbsoluteFile() codegenDir = new File(["node", "--print", "require.resolve('@react-native/codegen/package.json', { paths: [require.resolve('react-native/package.json')] })"].execute(null, rootDir).text.trim()).getParentFile().getAbsoluteFile()
enableBundleCompression = (findProperty('android.enableBundleCompression') ?: false).toBoolean() enableBundleCompression = (findProperty('android.enableBundleCompression') ?: false).toBoolean()
@ -87,9 +87,9 @@ android {
buildToolsVersion rootProject.ext.buildToolsVersion buildToolsVersion rootProject.ext.buildToolsVersion
compileSdk rootProject.ext.compileSdkVersion compileSdk rootProject.ext.compileSdkVersion
namespace 'com.renown.mobile.acupedia' namespace 'com.anonymous.acupedia'
defaultConfig { defaultConfig {
applicationId 'com.renown.mobile.acupedia' applicationId 'com.anonymous.acupedia'
minSdkVersion rootProject.ext.minSdkVersion minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1 versionCode 1
@ -123,7 +123,9 @@ android {
signingConfig signingConfigs.debug signingConfig signingConfigs.debug
} }
release { release {
signingConfig (keystorePropertiesFile.exists() ? signingConfigs.release : signingConfigs.debug) // Caution! In production, you need to generate your own keystore file.
// see https://reactnative.dev/docs/signed-apk-android.
signingConfig signingConfigs.debug
def enableShrinkResources = findProperty('android.enableShrinkResourcesInReleaseBuilds') ?: 'false' def enableShrinkResources = findProperty('android.enableShrinkResourcesInReleaseBuilds') ?: 'false'
shrinkResources enableShrinkResources.toBoolean() shrinkResources enableShrinkResources.toBoolean()
minifyEnabled enableMinifyInReleaseBuilds minifyEnabled enableMinifyInReleaseBuilds

View File

@ -11,7 +11,7 @@
<data android:scheme="https"/> <data android:scheme="https"/>
</intent> </intent>
</queries> </queries>
<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"> <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">
<meta-data android:name="expo.modules.updates.ENABLED" android:value="false"/> <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.ENABLE_BSDIFF_PATCH_SUPPORT" android:value="true"/>
<meta-data android:name="expo.modules.updates.EXPO_UPDATES_CHECK_ON_LAUNCH" android:value="ALWAYS"/> <meta-data android:name="expo.modules.updates.EXPO_UPDATES_CHECK_ON_LAUNCH" android:value="ALWAYS"/>
@ -26,7 +26,6 @@
<category android:name="android.intent.category.DEFAULT"/> <category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/> <category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="myapp"/> <data android:scheme="myapp"/>
<data android:scheme="acupedia"/>
</intent-filter> </intent-filter>
</activity> </activity>
</application> </application>

View File

@ -1,4 +1,4 @@
package com.renown.mobile.acupedia package com.anonymous.acupedia
import expo.modules.splashscreen.SplashScreenManager import expo.modules.splashscreen.SplashScreenManager
import android.os.Build import android.os.Build
@ -63,4 +63,3 @@ class MainActivity : ReactActivity() {
super.invokeDefaultOnBackPressed() super.invokeDefaultOnBackPressed()
} }
} }

View File

@ -1,4 +1,4 @@
package com.renown.mobile.acupedia package com.anonymous.acupedia
import android.app.Application import android.app.Application
import android.content.res.Configuration import android.content.res.Configuration
@ -6,38 +6,26 @@ import android.content.res.Configuration
import com.facebook.react.PackageList import com.facebook.react.PackageList
import com.facebook.react.ReactApplication import com.facebook.react.ReactApplication
import com.facebook.react.ReactNativeApplicationEntryPoint.loadReactNative import com.facebook.react.ReactNativeApplicationEntryPoint.loadReactNative
import com.facebook.react.ReactNativeHost
import com.facebook.react.ReactPackage import com.facebook.react.ReactPackage
import com.facebook.react.ReactHost import com.facebook.react.ReactHost
import com.facebook.react.common.ReleaseLevel import com.facebook.react.common.ReleaseLevel
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint
import com.facebook.react.defaults.DefaultReactNativeHost
import expo.modules.ApplicationLifecycleDispatcher import expo.modules.ApplicationLifecycleDispatcher
import expo.modules.ReactNativeHostWrapper import expo.modules.ExpoReactHostFactory
class MainApplication : Application(), ReactApplication { class MainApplication : Application(), ReactApplication {
override val reactNativeHost: ReactNativeHost = ReactNativeHostWrapper( override val reactHost: ReactHost by lazy {
this, ExpoReactHostFactory.getDefaultReactHost(
object : DefaultReactNativeHost(this) { context = applicationContext,
override fun getPackages(): List<ReactPackage> = packageList =
PackageList(this).packages.apply { PackageList(this).packages.apply {
// Packages that cannot be autolinked yet can be added manually here, for example: // Packages that cannot be autolinked yet can be added manually here, for example:
// add(MyReactNativePackage()) // 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() { override fun onCreate() {
super.onCreate() super.onCreate()
@ -55,4 +43,3 @@ class MainApplication : Application(), ReactApplication {
ApplicationLifecycleDispatcher.onConfigurationChanged(this, newConfig) ApplicationLifecycleDispatcher.onConfigurationChanged(this, newConfig)
} }
} }

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.3 KiB

After

Width:  |  Height:  |  Size: 3.3 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: 7.5 KiB

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.7 KiB

After

Width:  |  Height:  |  Size: 7.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.1 KiB

After

Width:  |  Height:  |  Size: 6.8 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: 3.0 KiB

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.6 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.7 KiB

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

After

Width:  |  Height:  |  Size: 32 KiB

View File

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

View File

@ -2,5 +2,4 @@
<string name="app_name">acupedia</string> <string name="app_name">acupedia</string>
<string name="expo_system_ui_user_interface_style" translatable="false">automatic</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_resize_mode" translatable="false">contain</string>
<string name="expo_splash_screen_status_bar_translucent" translatable="false">false</string>
</resources> </resources>

View File

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

View File

@ -60,7 +60,4 @@ EX_DEV_CLIENT_NETWORK_INSPECTOR=true
# Use legacy packaging to compress native libraries in the resulting APK. # Use legacy packaging to compress native libraries in the resulting APK.
expo.useLegacyPackaging=false 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", "scheme": "acupedia",
"userInterfaceStyle": "automatic", "userInterfaceStyle": "automatic",
"ios": { "ios": {
"bundleIdentifier": "com.renown.mobile.acupedia", "bundleIdentifier": "com.renownent.mobile.acupedia",
"supportsTablet": true, "supportsTablet": true,
"infoPlist": { "infoPlist": {
"NSAppTransportSecurity": { "NSAppTransportSecurity": {
@ -24,7 +24,7 @@
"monochromeImage": "./assets/images/android-icon-monochrome.png" "monochromeImage": "./assets/images/android-icon-monochrome.png"
}, },
"predictiveBackGestureEnabled": false, "predictiveBackGestureEnabled": false,
"package": "com.renown.mobile.acupedia", "package": "com.renownent.mobile.acupedia",
"allowBackup": false "allowBackup": false
}, },
"web": { "web": {

View File

@ -1,11 +0,0 @@
{
"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"; OTHER_SWIFT_FLAGS = "$(inherited) -D EXPO_CONFIGURATION_DEBUG";
PRODUCT_BUNDLE_IDENTIFIER = com.renownent.mobile.acupedia; PRODUCT_BUNDLE_IDENTIFIER = com.renownent.mobile.acupedia;
PRODUCT_NAME = "acupedia"; PRODUCT_NAME = acupedia;
SWIFT_OBJC_BRIDGING_HEADER = "acupedia/acupedia-Bridging-Header.h"; SWIFT_OBJC_BRIDGING_HEADER = "acupedia/acupedia-Bridging-Header.h";
SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0; SWIFT_VERSION = 5.0;
@ -405,7 +405,7 @@
); );
OTHER_SWIFT_FLAGS = "$(inherited) -D EXPO_CONFIGURATION_RELEASE"; OTHER_SWIFT_FLAGS = "$(inherited) -D EXPO_CONFIGURATION_RELEASE";
PRODUCT_BUNDLE_IDENTIFIER = com.renownent.mobile.acupedia; PRODUCT_BUNDLE_IDENTIFIER = com.renownent.mobile.acupedia;
PRODUCT_NAME = "acupedia"; PRODUCT_NAME = acupedia;
SWIFT_OBJC_BRIDGING_HEADER = "acupedia/acupedia-Bridging-Header.h"; SWIFT_OBJC_BRIDGING_HEADER = "acupedia/acupedia-Bridging-Header.h";
SWIFT_VERSION = 5.0; SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2"; TARGETED_DEVICE_FAMILY = "1,2";

Binary file not shown.

Before

Width:  |  Height:  |  Size: 734 KiB

View File

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

View File

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

687
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", "@tanstack/react-query": "^5.101.2",
"axios": "^1.18.1", "axios": "^1.18.1",
"expo": "~54.0.0", "expo": "~54.0.0",
"expo-build-properties": "~57.0.22", "expo-build-properties": "~1.0.10",
"expo-constants": "~18.0.10", "expo-constants": "~18.0.10",
"expo-device": "~8.0.9", "expo-device": "~8.0.9",
"expo-font": "~14.0.9", "expo-font": "~14.0.9",
@ -27,7 +27,6 @@
"expo-symbols": "~1.0.7", "expo-symbols": "~1.0.7",
"expo-system-ui": "~6.0.9", "expo-system-ui": "~6.0.9",
"expo-web-browser": "~15.0.11", "expo-web-browser": "~15.0.11",
"libphonenumber-js": "^1.13.16",
"react": "19.1.0", "react": "19.1.0",
"react-dom": "19.1.0", "react-dom": "19.1.0",
"react-native": "0.81.5", "react-native": "0.81.5",

View File

@ -2,48 +2,7 @@ import axios, { AxiosHeaders } from "axios";
import { getApiAccessToken } from "@/api/access-token"; import { getApiAccessToken } from "@/api/access-token";
import { normalizeApiError } from "@/api/error-utils"; import { normalizeApiError } from "@/api/error-utils";
import { notifyUnauthorized } from "@/api/session-events"; import { notifyUnauthorized } from "@/api/session-events";
import { getActiveApiUrl } from "@/store/environment.store"; 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)));
const apiClient = axios.create({ 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);});
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; export default apiClient;

View File

@ -1,11 +1,9 @@
import { useState } from "react";
import { Tabs, router } from "expo-router"; import { Tabs, router } from "expo-router";
import { Ionicons } from "@expo/vector-icons"; import { Ionicons } from "@expo/vector-icons";
import { Platform } from "react-native"; import { Alert, Platform } from "react-native";
import { AuthColors } from "@/features/auth/constants/colors"; import { AuthColors } from "@/features/auth/constants/colors";
import { useSafeAreaInsets } from "react-native-safe-area-context"; import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useAuthStore } from "@/store/auth.store"; import { useAuthStore } from "@/store/auth.store";
import LogoutConfirmModal from "@/components/LogoutConfirmModal";
export default function TabsLayout() { export default function TabsLayout() {
const insets = useSafeAreaInsets(); const insets = useSafeAreaInsets();
@ -15,24 +13,40 @@ export default function TabsLayout() {
const { accessToken, logout } = useAuthStore(); const { accessToken, logout } = useAuthStore();
const isAuthenticated = !!accessToken; const isAuthenticated = !!accessToken;
const [logoutModalVisible, setLogoutModalVisible] = useState(false);
const doLogout = () => {
setLogoutModalVisible(false);
logout();
router.replace("/login");
};
const handleAuthAction = () => { const handleAuthAction = () => {
if (isAuthenticated) { if (isAuthenticated) {
setLogoutModalVisible(true); const doLogout = () => {
logout();
router.replace("/login");
};
if (Platform.OS === "web") {
const confirmed = typeof window !== "undefined" ? window.confirm("Are you sure you want to logout?") : true;
if (confirmed) {
doLogout();
}
} else {
Alert.alert(
"Logout",
"Are you sure you want to logout?",
[
{ text: "Cancel", style: "cancel" },
{
text: "Yes",
style: "destructive",
onPress: doLogout,
},
],
{ cancelable: true }
);
}
} else { } else {
router.push("/login"); router.push("/login");
} }
}; };
return ( return (
<>
<Tabs <Tabs
screenOptions={{ screenOptions={{
headerShown: false, headerShown: false,
@ -128,11 +142,5 @@ export default function TabsLayout() {
}} }}
/> />
</Tabs> </Tabs>
<LogoutConfirmModal
visible={logoutModalVisible}
onCancel={() => setLogoutModalVisible(false)}
onConfirm={doLogout}
/>
</>
); );
} }

View File

@ -56,11 +56,10 @@ export default function LibraryScreen() {
useFocusEffect( useFocusEffect(
useCallback(() => { useCallback(() => {
isNavigatingRef.current = false; isNavigatingRef.current = false;
void modulesQuery.refetch().catch((error) => console.warn("Unable to refresh modules:", error));
if (accessToken) { if (accessToken) {
void refreshAccess().catch((error) => console.warn("Unable to refresh library access:", error)); void refreshAccess().catch((error) => console.warn("Unable to refresh library access:", error));
} }
}, [accessToken, modulesQuery.refetch, refreshAccess]), }, [accessToken, refreshAccess]),
); );
const items = useMemo( const items = useMemo(

View File

@ -18,7 +18,6 @@ import BaseTextInput from "@/components/forms/BaseTextInput";
import PasswordInput from "@/components/forms/PasswordInput"; import PasswordInput from "@/components/forms/PasswordInput";
import PrimaryButton from "@/components/buttons/PrimaryButton"; import PrimaryButton from "@/components/buttons/PrimaryButton";
import FieldLabel from "@/components/forms/FieldLabel"; import FieldLabel from "@/components/forms/FieldLabel";
import { validateEmail } from "@/constants/countries";
import { forgotPassword, resetPassword } from "@/features/auth/api/auth.api"; import { forgotPassword, resetPassword } from "@/features/auth/api/auth.api";
export default function ForgotPasswordScreen() { export default function ForgotPasswordScreen() {
@ -37,9 +36,12 @@ export default function ForgotPasswordScreen() {
const handleRequestOtp = async () => { const handleRequestOtp = async () => {
setEmailError(""); setEmailError("");
const cleanEmail = email.trim().toLowerCase(); const cleanEmail = email.trim().toLowerCase();
const emailErr = validateEmail(cleanEmail); if (!cleanEmail) {
if (emailErr) { setEmailError("Email is required");
setEmailError(emailErr); return;
}
if (!/\S+@\S+\.\S+/.test(cleanEmail)) {
setEmailError("Please enter a valid email address");
return; return;
} }
@ -87,7 +89,7 @@ export default function ForgotPasswordScreen() {
} else if (!/[0-9]/.test(newPassword)) { } else if (!/[0-9]/.test(newPassword)) {
setPasswordError("Must contain at least one number"); setPasswordError("Must contain at least one number");
hasError = true; hasError = true;
} else if (!/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?~`]/.test(newPassword)) { } else if (!/[^A-Za-z0-9\s]/.test(newPassword)) {
setPasswordError("Must contain at least one special character"); setPasswordError("Must contain at least one special character");
hasError = true; hasError = true;
} }

View File

@ -54,7 +54,7 @@ export default function ChangePasswordScreen() {
} else if (!/[0-9]/.test(newPassword)) { } else if (!/[0-9]/.test(newPassword)) {
setNewError("Must contain at least one number"); setNewError("Must contain at least one number");
hasError = true; hasError = true;
} else if (!/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?~`]/.test(newPassword)) { } else if (!/[^A-Za-z0-9\s]/.test(newPassword)) {
setNewError("Must contain at least one special character"); setNewError("Must contain at least one special character");
hasError = true; hasError = true;
} }
@ -63,7 +63,7 @@ export default function ChangePasswordScreen() {
setConfirmError("Please confirm your new password"); setConfirmError("Please confirm your new password");
hasError = true; hasError = true;
} else if (newPassword !== confirmPassword) { } else if (newPassword !== confirmPassword) {
setConfirmError("Confirm password do not match."); setConfirmError("Passwords do not match");
hasError = true; hasError = true;
} }
@ -89,23 +89,11 @@ export default function ChangePasswordScreen() {
const errMsg = const errMsg =
err?.response?.data?.detail || err?.response?.data?.detail ||
"Failed to update password. Please check your current password."; "Failed to update password. Please check your current password.";
if ( setCurrentError(errMsg);
typeof errMsg === "string" && if (Platform.OS === "web") {
errMsg.toLowerCase().includes("same") window.alert(errMsg);
) {
setNewError(errMsg);
} else if (
typeof errMsg === "string" &&
(errMsg.toLowerCase().includes("current") || errMsg.toLowerCase().includes("old"))
) {
setCurrentError(errMsg);
} else if (
typeof errMsg === "string" &&
errMsg.toLowerCase().includes("confirm")
) {
setConfirmError(errMsg);
} else { } else {
setCurrentError(errMsg); Alert.alert("Error", errMsg);
} }
} finally { } finally {
setIsLoading(false); setIsLoading(false);
@ -131,10 +119,7 @@ export default function ChangePasswordScreen() {
<FieldLabel label="Current Password" required /> <FieldLabel label="Current Password" required />
<PasswordInput <PasswordInput
value={currentPassword} value={currentPassword}
onChangeText={(text) => { onChangeText={setCurrentPassword}
setCurrentPassword(text);
if (currentError) setCurrentError("");
}}
placeholder="Enter current password" placeholder="Enter current password"
error={currentError} error={currentError}
/> />
@ -144,10 +129,7 @@ export default function ChangePasswordScreen() {
<FieldLabel label="New Password" required /> <FieldLabel label="New Password" required />
<PasswordInput <PasswordInput
value={newPassword} value={newPassword}
onChangeText={(text) => { onChangeText={setNewPassword}
setNewPassword(text);
if (newError) setNewError("");
}}
placeholder="Min. 8 characters with numbers & symbols" placeholder="Min. 8 characters with numbers & symbols"
error={newError} error={newError}
/> />
@ -157,10 +139,7 @@ export default function ChangePasswordScreen() {
<FieldLabel label="Confirm New Password" required /> <FieldLabel label="Confirm New Password" required />
<PasswordInput <PasswordInput
value={confirmPassword} value={confirmPassword}
onChangeText={(text) => { onChangeText={setConfirmPassword}
setConfirmPassword(text);
if (confirmError) setConfirmError("");
}}
placeholder="Re-enter new password" placeholder="Re-enter new password"
error={confirmError} error={confirmError}
/> />

View File

@ -4,7 +4,6 @@ import {
BackHandler, BackHandler,
Linking, Linking,
Platform, Platform,
Pressable,
ScrollView, ScrollView,
StyleSheet, StyleSheet,
Text, Text,
@ -14,12 +13,11 @@ import {
import { SafeAreaView } from "react-native-safe-area-context"; import { SafeAreaView } from "react-native-safe-area-context";
import { router, useFocusEffect, useLocalSearchParams } from "expo-router"; import { router, useFocusEffect, useLocalSearchParams } from "expo-router";
import { Ionicons } from "@expo/vector-icons"; import { Ionicons } from "@expo/vector-icons";
import { moderateScale, scale, verticalScale } from "react-native-size-matters"; import { moderateScale, verticalScale } from "react-native-size-matters";
import Constants from "expo-constants"; import Constants from "expo-constants";
import { Colors } from "@/theme"; import { Colors } from "@/theme";
import { useAuthStore } from "@/store/auth.store"; import { useAuthStore } from "@/store/auth.store";
import { getActiveStorefrontUrl } from "@/store/environment.store";
import PrimaryButton from "@/components/buttons/PrimaryButton"; import PrimaryButton from "@/components/buttons/PrimaryButton";
function param(value: string | string[] | undefined): string { function param(value: string | string[] | undefined): string {
@ -27,9 +25,6 @@ function param(value: string | string[] | undefined): string {
} }
function resolveStorefrontUrl(): string { function resolveStorefrontUrl(): string {
const dynamicUrl = getActiveStorefrontUrl();
if (dynamicUrl) return dynamicUrl;
const envUrl = process.env.EXPO_PUBLIC_STOREFRONT_URL?.trim(); const envUrl = process.env.EXPO_PUBLIC_STOREFRONT_URL?.trim();
if (envUrl) return envUrl; if (envUrl) return envUrl;
@ -171,22 +166,15 @@ export default function SubscriptionScreen() {
return ( return (
<SafeAreaView style={styles.safeArea} edges={["top", "bottom", "left", "right"]}> <SafeAreaView style={styles.safeArea} edges={["top", "bottom", "left", "right"]}>
<View style={styles.header}> <View style={styles.header}>
<Pressable <TouchableOpacity
onPress={handleBack} onPress={handleBack}
style={({ pressed }) => [ style={styles.backButton}
styles.backButton,
pressed && styles.backButtonPressed,
]}
hitSlop={{ top: 12, bottom: 12, left: 12, right: 12 }} hitSlop={{ top: 12, bottom: 12, left: 12, right: 12 }}
accessibilityRole="button" accessibilityRole="button"
accessibilityLabel="Go back" accessibilityLabel="Go back"
> >
<Ionicons <Ionicons name="chevron-back" size={24} color={Colors.textPrimary} />
name="chevron-back" </TouchableOpacity>
size={moderateScale(24)}
color={Colors.textPrimary}
/>
</Pressable>
<Text style={styles.headerTitle} numberOfLines={1}> <Text style={styles.headerTitle} numberOfLines={1}>
{title} {title}
</Text> </Text>
@ -249,15 +237,10 @@ const styles = StyleSheet.create({
backgroundColor: "#FFFFFF", backgroundColor: "#FFFFFF",
}, },
backButton: { backButton: {
width: scale(38), width: moderateScale(36),
height: scale(38), height: moderateScale(36),
borderRadius: scale(19),
justifyContent: "center",
alignItems: "center", alignItems: "center",
backgroundColor: "#F1F5F9", justifyContent: "center",
},
backButtonPressed: {
backgroundColor: "#E2E8F0",
}, },
headerTitle: { headerTitle: {
flex: 1, flex: 1,
@ -267,7 +250,7 @@ const styles = StyleSheet.create({
textAlign: "center", textAlign: "center",
marginHorizontal: moderateScale(8), marginHorizontal: moderateScale(8),
}, },
placeholder: { width: scale(38), height: scale(38) }, placeholder: { width: moderateScale(36) },
scrollContent: { scrollContent: {
flexGrow: 1, flexGrow: 1,
justifyContent: "center", justifyContent: "center",

View File

@ -1,371 +0,0 @@
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

@ -1,145 +0,0 @@
import React from "react";
import {
Modal,
Pressable,
StyleSheet,
Text,
TouchableOpacity,
View,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { moderateScale, scale, verticalScale } from "react-native-size-matters";
import { Colors } from "@/theme";
interface LogoutConfirmModalProps {
visible: boolean;
onCancel: () => void;
onConfirm: () => void;
}
export default function LogoutConfirmModal({
visible,
onCancel,
onConfirm,
}: LogoutConfirmModalProps) {
return (
<Modal
visible={visible}
transparent
animationType="fade"
onRequestClose={onCancel}
>
<Pressable style={styles.backdrop} onPress={onCancel}>
<Pressable style={styles.card} onPress={() => {}}>
<View style={styles.iconContainer}>
<Ionicons name="log-out-outline" size={26} color="#DC2626" />
</View>
<Text style={styles.title}>Log Out</Text>
<Text style={styles.message}>
Are you sure you want to log out of Acupedia?
</Text>
<View style={styles.actions}>
<TouchableOpacity
style={[styles.button, styles.cancelButton]}
onPress={onCancel}
activeOpacity={0.8}
accessibilityRole="button"
accessibilityLabel="Cancel"
>
<Text style={styles.cancelText}>Cancel</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.button, styles.confirmButton]}
onPress={onConfirm}
activeOpacity={0.8}
accessibilityRole="button"
accessibilityLabel="Log Out"
>
<Text style={styles.confirmText}>Log Out</Text>
</TouchableOpacity>
</View>
</Pressable>
</Pressable>
</Modal>
);
}
const styles = StyleSheet.create({
backdrop: {
flex: 1,
backgroundColor: "rgba(15, 23, 42, 0.55)",
justifyContent: "center",
alignItems: "center",
paddingHorizontal: scale(24),
},
card: {
width: "100%",
maxWidth: 360,
backgroundColor: Colors.surface ?? "#FFFFFF",
borderRadius: moderateScale(20),
padding: moderateScale(22),
alignItems: "center",
shadowColor: "#000",
shadowOffset: { width: 0, height: 10 },
shadowOpacity: 0.18,
shadowRadius: 20,
elevation: 8,
},
iconContainer: {
width: scale(48),
height: scale(48),
borderRadius: scale(24),
backgroundColor: "#FEE2E2",
justifyContent: "center",
alignItems: "center",
marginBottom: verticalScale(12),
},
title: {
fontSize: moderateScale(18),
fontWeight: "700",
color: Colors.textPrimary ?? "#0F172A",
marginBottom: verticalScale(6),
textAlign: "center",
},
message: {
fontSize: moderateScale(14),
color: Colors.textSecondary ?? "#475569",
textAlign: "center",
lineHeight: moderateScale(20),
marginBottom: verticalScale(20),
},
actions: {
flexDirection: "row",
gap: scale(10),
width: "100%",
},
button: {
flex: 1,
paddingVertical: verticalScale(11),
borderRadius: moderateScale(12),
alignItems: "center",
justifyContent: "center",
},
cancelButton: {
backgroundColor: "#F1F5F9",
borderWidth: 1,
borderColor: "#E2E8F0",
},
confirmButton: {
backgroundColor: "#DC2626",
},
cancelText: {
fontSize: moderateScale(14),
fontWeight: "600",
color: "#334155",
},
confirmText: {
fontSize: moderateScale(14),
fontWeight: "700",
color: "#FFFFFF",
},
});

View File

@ -1,43 +0,0 @@
/**
* 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

@ -1,408 +0,0 @@
import { parsePhoneNumberFromString, type CountryCode as LibCountryCode } from "libphonenumber-js/max";
export interface CountryCode {
iso2: LibCountryCode;
code: string;
label: string;
country: string;
currency: string;
minLength: number;
maxLength: number;
placeholder: string;
}
export const COUNTRY_CODES: CountryCode[] = [
// South Asia
{ iso2: "IN", code: "+91", label: "🇮🇳 +91", country: "India", currency: "INR", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number" },
{ iso2: "PK", code: "+92", label: "🇵🇰 +92", country: "Pakistan", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number" },
{ iso2: "BD", code: "+880", label: "🇧🇩 +880", country: "Bangladesh", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number" },
{ iso2: "LK", code: "+94", label: "🇱🇰 +94", country: "Sri Lanka", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "NP", code: "+977", label: "🇳🇵 +977", country: "Nepal", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number" },
{ iso2: "BT", code: "+975", label: "🇧🇹 +975", country: "Bhutan", currency: "USD", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number" },
{ iso2: "MV", code: "+960", label: "🇲🇻 +960", country: "Maldives", currency: "USD", minLength: 7, maxLength: 7, placeholder: "7-digit mobile number" },
// North America
{ iso2: "US", code: "+1", label: "🇺🇸 +1", country: "United States", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit phone number" },
{ iso2: "CA", code: "+1", label: "🇨🇦 +1", country: "Canada", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit phone number" },
{ iso2: "MX", code: "+52", label: "🇲🇽 +52", country: "Mexico", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number" },
// Europe & UK
{ iso2: "GB", code: "+44", label: "🇬🇧 +44", country: "United Kingdom", currency: "USD", minLength: 10, maxLength: 11, placeholder: "10 to 11 digits" },
{ iso2: "DE", code: "+49", label: "🇩🇪 +49", country: "Germany", currency: "EUR", minLength: 10, maxLength: 11, placeholder: "10 to 11 digits" },
{ iso2: "FR", code: "+33", label: "🇫🇷 +33", country: "France", currency: "EUR", minLength: 9, maxLength: 10, placeholder: "9 to 10 digits" },
{ iso2: "IT", code: "+39", label: "🇮🇹 +39", country: "Italy", currency: "EUR", minLength: 9, maxLength: 10, placeholder: "9 to 10 digits" },
{ iso2: "ES", code: "+34", label: "🇪🇸 +34", country: "Spain", currency: "EUR", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "NL", code: "+31", label: "🇳🇱 +31", country: "Netherlands", currency: "EUR", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "CH", code: "+41", label: "🇨🇭 +41", country: "Switzerland", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "BE", code: "+32", label: "🇧🇪 +32", country: "Belgium", currency: "EUR", minLength: 8, maxLength: 9, placeholder: "8 to 9 digits" },
{ iso2: "AT", code: "+43", label: "🇦🇹 +43", country: "Austria", currency: "EUR", minLength: 10, maxLength: 11, placeholder: "10 to 11 digits" },
{ iso2: "IE", code: "+353", label: "🇮🇪 +353", country: "Ireland", currency: "EUR", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "SE", code: "+46", label: "🇸🇪 +46", country: "Sweden", currency: "EUR", minLength: 7, maxLength: 10, placeholder: "7 to 10 digits" },
{ iso2: "NO", code: "+47", label: "🇳🇴 +47", country: "Norway", currency: "USD", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number" },
{ iso2: "DK", code: "+45", label: "🇩🇰 +45", country: "Denmark", currency: "EUR", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number" },
{ iso2: "FI", code: "+358", label: "🇫🇮 +358", country: "Finland", currency: "EUR", minLength: 6, maxLength: 10, placeholder: "6 to 10 digits" },
{ iso2: "PT", code: "+351", label: "🇵🇹 +351", country: "Portugal", currency: "EUR", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "GR", code: "+30", label: "🇬🇷 +30", country: "Greece", currency: "EUR", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number" },
{ iso2: "PL", code: "+48", label: "🇵🇱 +48", country: "Poland", currency: "EUR", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "CZ", code: "+420", label: "🇨🇿 +420", country: "Czech Republic", currency: "EUR", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "HU", code: "+36", label: "🇭🇺 +36", country: "Hungary", currency: "EUR", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "RO", code: "+40", label: "🇷🇴 +40", country: "Romania", currency: "EUR", minLength: 9, maxLength: 10, placeholder: "9 to 10 digits" },
{ iso2: "UA", code: "+380", label: "🇺🇦 +380", country: "Ukraine", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "IS", code: "+354", label: "🇮🇸 +354", country: "Iceland", currency: "EUR", minLength: 7, maxLength: 9, placeholder: "7 to 9 digits" },
{ iso2: "LU", code: "+352", label: "🇱🇺 +352", country: "Luxembourg", currency: "EUR", minLength: 8, maxLength: 10, placeholder: "8 to 10 digits" },
{ iso2: "HR", code: "+385", label: "🇭🇷 +385", country: "Croatia", currency: "EUR", minLength: 8, maxLength: 9, placeholder: "8 to 9 digits" },
{ iso2: "SK", code: "+421", label: "🇸🇰 +421", country: "Slovakia", currency: "EUR", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "BG", code: "+359", label: "🇧🇬 +359", country: "Bulgaria", currency: "EUR", minLength: 8, maxLength: 9, placeholder: "8 to 9 digits" },
{ iso2: "RU", code: "+7", label: "🇷🇺 +7", country: "Russia", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number" },
{ iso2: "TR", code: "+90", label: "🇹🇷 +90", country: "Turkey", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number" },
// Asia-Pacific
{ iso2: "AU", code: "+61", label: "🇦🇺 +61", country: "Australia", currency: "USD", minLength: 9, maxLength: 10, placeholder: "9 to 10 digits" },
{ iso2: "NZ", code: "+64", label: "🇳🇿 +64", country: "New Zealand", currency: "USD", minLength: 8, maxLength: 10, placeholder: "8 to 10 digits" },
{ iso2: "JP", code: "+81", label: "🇯🇵 +81", country: "Japan", currency: "USD", minLength: 10, maxLength: 11, placeholder: "10 to 11 digits" },
{ iso2: "CN", code: "+86", label: "🇨🇳 +86", country: "China", currency: "USD", minLength: 11, maxLength: 11, placeholder: "11-digit mobile number" },
{ iso2: "KR", code: "+82", label: "🇰🇷 +82", country: "South Korea", currency: "USD", minLength: 9, maxLength: 11, placeholder: "9 to 11 digits" },
{ iso2: "HK", code: "+852", label: "🇭🇰 +852", country: "Hong Kong", currency: "USD", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number" },
{ iso2: "TW", code: "+886", label: "🇹🇼 +886", country: "Taiwan", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "SG", code: "+65", label: "🇸🇬 +65", country: "Singapore", currency: "USD", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number" },
{ iso2: "MY", code: "+60", label: "🇲🇾 +60", country: "Malaysia", currency: "USD", minLength: 9, maxLength: 10, placeholder: "9 to 10 digits" },
{ iso2: "ID", code: "+62", label: "🇮🇩 +62", country: "Indonesia", currency: "USD", minLength: 9, maxLength: 12, placeholder: "9 to 12 digits" },
{ iso2: "PH", code: "+63", label: "🇵🇭 +63", country: "Philippines", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number" },
{ iso2: "TH", code: "+66", label: "🇹🇭 +66", country: "Thailand", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "VN", code: "+84", label: "🇻🇳 +84", country: "Vietnam", currency: "USD", minLength: 9, maxLength: 10, placeholder: "9 to 10 digits" },
// Middle East
{ iso2: "AE", code: "+971", label: "🇦🇪 +971", country: "UAE", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "SA", code: "+966", label: "🇸🇦 +966", country: "Saudi Arabia", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "QA", code: "+974", label: "🇶🇦 +974", country: "Qatar", currency: "USD", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number" },
{ iso2: "KW", code: "+965", label: "🇰🇼 +965", country: "Kuwait", currency: "USD", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number" },
{ iso2: "OM", code: "+968", label: "🇴🇲 +968", country: "Oman", currency: "USD", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number" },
{ iso2: "BH", code: "+973", label: "🇧🇭 +973", country: "Bahrain", currency: "USD", minLength: 8, maxLength: 8, placeholder: "8-digit mobile number" },
{ iso2: "IL", code: "+972", label: "🇮🇱 +972", country: "Israel", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "JO", code: "+962", label: "🇯🇴 +962", country: "Jordan", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "LB", code: "+961", label: "🇱🇧 +961", country: "Lebanon", currency: "USD", minLength: 7, maxLength: 8, placeholder: "7 to 8 digits" },
// Latin America
{ iso2: "BR", code: "+55", label: "🇧🇷 +55", country: "Brazil", currency: "USD", minLength: 10, maxLength: 11, placeholder: "10 to 11 digits" },
{ iso2: "AR", code: "+54", label: "🇦🇷 +54", country: "Argentina", currency: "USD", minLength: 10, maxLength: 11, placeholder: "10 to 11 digits" },
{ iso2: "CL", code: "+56", label: "🇨🇱 +56", country: "Chile", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "CO", code: "+57", label: "🇨🇴 +57", country: "Colombia", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number" },
{ iso2: "PE", code: "+51", label: "🇵🇪 +51", country: "Peru", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
// Africa
{ iso2: "ZA", code: "+27", label: "🇿🇦 +27", country: "South Africa", currency: "USD", minLength: 9, maxLength: 10, placeholder: "9 to 10 digits" },
{ iso2: "NG", code: "+234", label: "🇳🇬 +234", country: "Nigeria", currency: "USD", minLength: 10, maxLength: 11, placeholder: "10 to 11 digits" },
{ iso2: "KE", code: "+254", label: "🇰🇪 +254", country: "Kenya", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "GH", code: "+233", label: "🇬🇭 +233", country: "Ghana", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "EG", code: "+20", label: "🇪🇬 +20", country: "Egypt", currency: "USD", minLength: 10, maxLength: 10, placeholder: "10-digit mobile number" },
{ iso2: "MA", code: "+212", label: "🇲🇦 +212", country: "Morocco", currency: "USD", minLength: 9, maxLength: 9, placeholder: "9-digit mobile number" },
{ iso2: "MU", code: "+230", label: "🇲🇺 +230", country: "Mauritius", currency: "USD", minLength: 7, maxLength: 8, placeholder: "7 to 8 digits" },
];
export const SORTED_COUNTRY_CODES: CountryCode[] = [...COUNTRY_CODES].sort((a, b) =>
a.country.localeCompare(b.country)
);
export const DEFAULT_COUNTRY = COUNTRY_CODES[0]; // India (+91)
export const getCountryRuleByIso = (iso?: string | null): CountryCode => {
if (!iso) return DEFAULT_COUNTRY;
const upper = iso.toUpperCase().trim();
return COUNTRY_CODES.find((c) => c.iso2 === upper) || DEFAULT_COUNTRY;
};
export const getCountryRuleByName = (countryName?: string | null): CountryCode => {
if (!countryName) return DEFAULT_COUNTRY;
const normalized = countryName.toLowerCase().trim();
return (
COUNTRY_CODES.find(
(c) =>
c.country.toLowerCase() === normalized ||
c.iso2.toLowerCase() === normalized ||
normalized.includes(c.country.toLowerCase())
) || {
iso2: "IN",
code: "+91",
label: "🇮🇳 +91",
country: countryName,
currency: normalized === "india" ? "INR" : "USD",
minLength: 7,
maxLength: 15,
placeholder: "Phone number",
}
);
};
export const getCountryRuleByDialCode = (dialCode?: string | null, countryHint?: string | null): CountryCode => {
if (!dialCode) return DEFAULT_COUNTRY;
if (countryHint) {
const byCountry = getCountryRuleByName(countryHint);
if (byCountry && byCountry.code === dialCode) {
return byCountry;
}
}
return (
COUNTRY_CODES.find((c) => c.code === dialCode) || {
iso2: "IN",
code: dialCode,
label: dialCode,
country: countryHint || "Other",
currency: "USD",
minLength: 7,
maxLength: 15,
placeholder: "Phone number",
}
);
};
/**
* Validates mobile phone number according to country telecom numbering plans.
* Uses libphonenumber-js to enforce mobile prefixes (e.g., France 06/07, India 6-9, UK 07).
*/
export const validatePhoneNumber = (
val?: string | null,
dialCode?: string,
country?: string
): string | null => {
if (!val || !val.trim()) return null;
const trimmed = val.trim();
// Explicitly disallow alphabetic characters
if (/[a-zA-Z]/.test(trimmed)) {
return "Phone number cannot contain alphabetic characters.";
}
// Strictly disallow hyphens, dashes, and invalid symbols
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.";
}
const allDigits = trimmed.replace(/\D/g, "");
if (allDigits.length === 0) {
return "Please enter a valid phone number with numeric digits.";
}
let rule = country ? getCountryRuleByName(country) : undefined;
if (!rule && dialCode) {
rule = getCountryRuleByDialCode(dialCode, country);
}
if (!rule) {
rule = DEFAULT_COUNTRY;
}
const iso2 = rule.iso2 || "IN";
// Extract national digits without dial code prefix
let nationalDigits = allDigits;
const dialDigits = rule.code.replace(/\D/g, "");
if (trimmed.startsWith("+")) {
if (allDigits.startsWith(dialDigits)) {
nationalDigits = allDigits.slice(dialDigits.length);
}
} else if (allDigits.startsWith(dialDigits) && allDigits.length > rule.maxLength) {
nationalDigits = allDigits.slice(dialDigits.length);
}
const digitsWithoutTrunk0 = nationalDigits.startsWith("0") && iso2 !== "IT"
? nationalDigits.replace(/^0+/, "")
: nationalDigits;
// 1. Enforce length validation FIRST so digit count errors take precedence over prefix errors
if (iso2 === "IN") {
if (nationalDigits.length !== 10) {
return "India mobile number must be exactly 10 digits.";
}
if (!/^[6-9]/.test(nationalDigits)) {
return "India mobile number must begin with 6, 7, 8, or 9.";
}
} else if (iso2 === "FR") {
if (nationalDigits.length < 9) {
return "France mobile number is too short (must be 9 digits, or 10 digits with 0).";
}
if (nationalDigits.length > 10 || (nationalDigits.length === 10 && !nationalDigits.startsWith("0"))) {
return "France mobile number cannot exceed 9 digits (or 10 digits with leading 0).";
}
if (!/^[67]/.test(digitsWithoutTrunk0)) {
return "France mobile number must begin with 06 or 07 (or 6 or 7).";
}
} else if (iso2 === "GB") {
if (digitsWithoutTrunk0.length < 10) {
return "United Kingdom mobile number is too short (must be 10 digits, or 11 digits with 0).";
}
if (digitsWithoutTrunk0.length > 10) {
return "United Kingdom mobile number cannot exceed 10 digits (or 11 digits with leading 0).";
}
if (!/^7/.test(digitsWithoutTrunk0)) {
return "United Kingdom mobile number must begin with 07 (or 7).";
}
} else {
// General length check for other countries
if (rule.minLength === rule.maxLength) {
if (digitsWithoutTrunk0.length !== rule.minLength && nationalDigits.length !== rule.minLength) {
return `${rule.country} mobile number must be exactly ${rule.minLength} digits.`;
}
} else {
if (digitsWithoutTrunk0.length < rule.minLength && nationalDigits.length < rule.minLength) {
return `${rule.country} mobile number is too short (min ${rule.minLength} digits).`;
}
if (digitsWithoutTrunk0.length > rule.maxLength) {
return `${rule.country} mobile number cannot exceed ${rule.maxLength} digits.`;
}
}
}
// 2. Validate telecom numbering rules with libphonenumber-js
const candidate = trimmed.startsWith("+") ? trimmed : `${rule.code}${nationalDigits}`;
const parsed = parsePhoneNumberFromString(candidate, iso2);
if (parsed && parsed.isValid()) {
const numberType = parsed.getType();
if (numberType === "FIXED_LINE") {
return `Please enter a valid mobile number for ${rule.country}.`;
}
return null;
}
return `Please enter a valid mobile number for ${rule.country} (e.g. ${rule.placeholder}).`;
};
export const isValidPhoneNumber = (
val?: string | null,
dialCode?: string,
country?: string
): boolean => {
return validatePhoneNumber(val, dialCode, country) === null;
};
/**
* Splits a full phone number into dialCode, country, and localDigits
*/
export const parsePhoneNumber = (
fullPhone?: string | null,
fallbackCountry = "India"
): { country: string; dialCode: string; localDigits: string; iso2: LibCountryCode } => {
const defaultRule = getCountryRuleByName(fallbackCountry) || DEFAULT_COUNTRY;
if (!fullPhone || !fullPhone.trim()) {
return { country: defaultRule.country, dialCode: defaultRule.code, localDigits: "", iso2: defaultRule.iso2 };
}
const trimmed = fullPhone.trim();
const parsed = parsePhoneNumberFromString(trimmed, defaultRule.iso2);
if (parsed) {
const matchedRule = parsed.country
? getCountryRuleByIso(parsed.country)
: getCountryRuleByDialCode(`+${parsed.countryCallingCode}`, fallbackCountry);
return {
country: matchedRule.country,
dialCode: `+${parsed.countryCallingCode}`,
localDigits: parsed.nationalNumber,
iso2: matchedRule.iso2,
};
}
const sorted = [...COUNTRY_CODES].sort((a, b) => b.code.length - a.code.length);
const matched = sorted.find((c) => trimmed.startsWith(c.code));
if (matched) {
const rawLocal = trimmed.slice(matched.code.length).replace(/\D/g, "");
return {
country: matched.country,
dialCode: matched.code,
localDigits: rawLocal.slice(0, matched.maxLength),
iso2: matched.iso2,
};
}
const rawDigits = trimmed.replace(/\D/g, "");
return {
country: defaultRule.country,
dialCode: defaultRule.code,
localDigits: rawDigits.slice(0, defaultRule.maxLength),
iso2: defaultRule.iso2,
};
};
/**
* Formats full phone number cleanly as E.164 without spaces (+<dialCode><digits>),
* automatically stripping any national trunk '0' where appropriate.
*/
export const formatE164Phone = (dialCode: string, localDigits: string, country?: string): string => {
if (!localDigits || !localDigits.trim()) return "";
const rule = country ? getCountryRuleByName(country) : getCountryRuleByDialCode(dialCode, country);
const rawDigits = localDigits.replace(/\D/g, "");
if (!rawDigits) return "";
const code = dialCode.startsWith("+") ? dialCode : `+${dialCode}`;
const candidate = localDigits.startsWith("+") ? localDigits : `${code}${rawDigits}`;
const parsed = parsePhoneNumberFromString(candidate, rule.iso2);
if (parsed && parsed.isValid()) {
return parsed.format("E.164");
}
let cleanLocal = rawDigits;
if (rule.iso2 !== "IT" && cleanLocal.startsWith("0")) {
cleanLocal = cleanLocal.replace(/^0+/, "");
}
return `${code}${cleanLocal}`;
};
/**
* Strips non-numeric / non-phone characters from text in real-time
* If maxLength is provided, strictly restricts digit length
* If allowPlus is false, strips any '+' symbols as well (for local number inputs)
*/
export const cleanPhoneInput = (text: string, maxLength = 16, allowPlus = true): string => {
const trimmedStart = text.trimStart();
const hasPlus = allowPlus && trimmedStart.startsWith("+");
const rest = hasPlus ? trimmedStart.slice(1) : text;
const digitsOnly = rest.replace(/\D/g, "");
const boundedDigits = maxLength ? digitsOnly.slice(0, maxLength) : digitsOnly;
return hasPlus ? `+${boundedDigits}` : boundedDigits;
};
/**
* 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);
const parsed = parsePhoneNumber(trimmed, oldRule.country);
const bounded = parsed.localDigits.slice(0, newRule.maxLength);
return bounded ? `${newRule.code} ${bounded}` : `${newRule.code} `;
};
/**
* RFC 5322 & RFC 1035 compliant email validation regex.
*/
export const EMAIL_REGEX = /^[a-zA-Z0-9_%+-]+(?:\.[a-zA-Z0-9_%+-]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.[a-zA-Z]{2,}$/;
export const validateEmail = (email?: string | null): string | null => {
if (!email || !email.trim()) {
return "Email is required";
}
if (!EMAIL_REGEX.test(email.trim())) {
return "Please enter a valid email address";
}
return null;
};
export const isValidEmail = (email?: string | null): boolean => {
return validateEmail(email) === null;
};

View File

@ -17,7 +17,6 @@ import PasswordInput from "@/components/forms/PasswordInput";
import PrimaryButton from "@/components/buttons/PrimaryButton"; import PrimaryButton from "@/components/buttons/PrimaryButton";
import { AuthColors } from "../constants/colors"; import { AuthColors } from "../constants/colors";
import { validateEmail } from "@/constants/countries";
import { useAuthStore } from "@/store/auth.store"; import { useAuthStore } from "@/store/auth.store";
import { LoginMethod } from "./LoginTabs"; import { LoginMethod } from "./LoginTabs";
import { login } from "@/features/auth/api/auth.api"; import { login } from "@/features/auth/api/auth.api";
@ -42,8 +41,7 @@ export default function LoginForm({
const handlePhoneChange = (text: string) => { const handlePhoneChange = (text: string) => {
const digits = text.replace(/\D/g, ""); const digits = text.replace(/\D/g, "");
setPhone(digits.slice(0, 15)); setPhone(digits.slice(0, 10));
if (phoneError) setPhoneError("");
}; };
const handleLogin = async () => { const handleLogin = async () => {
@ -53,17 +51,19 @@ export default function LoginForm({
setPasswordError(""); setPasswordError("");
if (activeTab === "email") { if (activeTab === "email") {
const emailErr = validateEmail(email); if (!email.trim()) {
if (emailErr) { setEmailError("Email is required");
setEmailError(emailErr); hasError = true;
} else if (!/\S+@\S+\.\S+/.test(email)) {
setEmailError("Please enter a valid email address");
hasError = true; hasError = true;
} }
} else { } else {
if (!phone.trim()) { if (!phone.trim()) {
setPhoneError("Phone number is required"); setPhoneError("Phone number is required");
hasError = true; hasError = true;
} else if (phone.length < 7 || phone.length > 15) { } else if (phone.length < 10) {
setPhoneError("Phone number must be between 7 and 15 digits"); setPhoneError("Phone number must be 10 digits");
hasError = true; hasError = true;
} }
} }
@ -130,7 +130,7 @@ export default function LoginForm({
autoCapitalize="none" autoCapitalize="none"
autoCorrect={false} autoCorrect={false}
textContentType="telephoneNumber" textContentType="telephoneNumber"
maxLength={15} maxLength={10}
leftIcon="call-outline" leftIcon="call-outline"
error={phoneError} error={phoneError}
/> />

View File

@ -1,74 +1,39 @@
import React, { useState } from "react"; import React from "react";
import { Pressable, StyleSheet, Text, TouchableOpacity, View } from "react-native"; import { Pressable, StyleSheet, Text, View } from "react-native";
import { Ionicons } from "@expo/vector-icons"; import { Ionicons } from "@expo/vector-icons";
import { useRouter } from "expo-router"; import { useRouter } from "expo-router";
import { AuthColors } from "../constants/colors";
import { import {
moderateScale, moderateScale,
scale, scale,
verticalScale, verticalScale,
} from "react-native-size-matters"; } 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() { export default function LoginHeader() {
const router = useRouter(); 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 ( return (
<View style={styles.container}> <View style={styles.container}>
<View style={styles.topRow}> <Pressable
<Pressable accessibilityRole="button"
accessibilityRole="button" accessibilityLabel="Go Back"
accessibilityLabel="Go Back" hitSlop={10}
hitSlop={10} onPress={() => router.back()}
onPress={() => router.back()} style={styles.backButton}
style={styles.backButton} >
> <Ionicons
<Ionicons name="arrow-back"
name="arrow-back" size={moderateScale(24)}
size={moderateScale(24)} />
/> </Pressable>
</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}> <View style={styles.textContainer}>
<Text style={styles.title}>Welcome Back!</Text> <Text style={styles.title}>Welcome Back!</Text>
<Text style={styles.subtitle}>Login to continue</Text>
</View>
{ENABLE_ENV_SWITCHER && ( <Text style={styles.subtitle}>
<EnvironmentSelectorModal Login to continue
visible={modalVisible} </Text>
onClose={() => setModalVisible(false)} </View>
/>
)}
</View> </View>
); );
} }
@ -79,41 +44,11 @@ const styles = StyleSheet.create({
marginBottom: verticalScale(32), marginBottom: verticalScale(32),
}, },
topRow: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
marginBottom: verticalScale(28),
},
backButton: { backButton: {
width: scale(40), width: scale(40),
height: scale(40), height: scale(40),
justifyContent: "center", 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: { textContainer: {
@ -131,4 +66,4 @@ const styles = StyleSheet.create({
color: AuthColors.textSecondary, color: AuthColors.textSecondary,
fontWeight: "500", fontWeight: "500",
}, },
}); });

View File

@ -1,37 +1,12 @@
import React, { useState, useMemo } from "react"; import React, { useState } from "react";
import { import { Alert, StyleSheet, View } from "react-native";
KeyboardAvoidingView,
Modal,
Platform,
Pressable,
ScrollView,
StyleSheet,
Text,
TextInput,
View,
} from "react-native";
import { useRouter } from "expo-router"; import { useRouter } from "expo-router";
import { Ionicons } from "@expo/vector-icons"; import { verticalScale } from "react-native-size-matters";
import {
moderateScale,
scale,
verticalScale,
} from "react-native-size-matters";
import BaseTextInput from "@/components/forms/BaseTextInput"; import BaseTextInput from "@/components/forms/BaseTextInput";
import PasswordInput from "@/components/forms/PasswordInput"; import PasswordInput from "@/components/forms/PasswordInput";
import PrimaryButton from "@/components/buttons/PrimaryButton"; import PrimaryButton from "@/components/buttons/PrimaryButton";
import { AuthColors } from "../constants/colors";
import { Colors } from "@/theme";
import {
CountryCode,
COUNTRY_CODES,
DEFAULT_COUNTRY,
SORTED_COUNTRY_CODES,
validatePhoneNumber,
formatE164Phone,
validateEmail,
} from "@/constants/countries";
import { useAuthStore } from "@/store/auth.store"; import { useAuthStore } from "@/store/auth.store";
import { register } from "@/features/auth/api/auth.api"; import { register } from "@/features/auth/api/auth.api";
@ -41,13 +16,9 @@ export default function SignUpForm() {
const [fullName, setFullName] = useState(""); const [fullName, setFullName] = useState("");
const [email, setEmail] = useState(""); const [email, setEmail] = useState("");
const [selectedCountry, setSelectedCountry] = useState<CountryCode>(DEFAULT_COUNTRY);
const [phone, setPhone] = useState(""); const [phone, setPhone] = useState("");
const [password, setPassword] = useState(""); const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState(""); const [confirmPassword, setConfirmPassword] = useState("");
const [showCountryModal, setShowCountryModal] = useState(false);
const [countrySearch, setCountrySearch] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [fullNameError, setFullNameError] = useState(""); const [fullNameError, setFullNameError] = useState("");
const [emailError, setEmailError] = useState(""); const [emailError, setEmailError] = useState("");
@ -55,62 +26,9 @@ export default function SignUpForm() {
const [passwordError, setPasswordError] = useState(""); const [passwordError, setPasswordError] = useState("");
const [confirmPasswordError, setConfirmPasswordError] = useState(""); const [confirmPasswordError, setConfirmPasswordError] = useState("");
const filteredCountries = useMemo(() => {
const q = countrySearch.trim().toLowerCase();
if (!q) return SORTED_COUNTRY_CODES;
return SORTED_COUNTRY_CODES.filter(
(c) =>
c.country.toLowerCase().includes(q) ||
c.code.includes(q) ||
c.label.toLowerCase().includes(q)
);
}, [countrySearch]);
const handlePhoneChange = (text: string) => { const handlePhoneChange = (text: string) => {
const trimmed = text.trim();
// Check if user pasted an international number with '+' prefix
if (trimmed.startsWith("+")) {
const sorted = [...COUNTRY_CODES].sort((a, b) => b.code.length - a.code.length);
const matched = sorted.find((c) => trimmed.startsWith(c.code));
if (matched) {
if (matched.country !== selectedCountry.country) {
setSelectedCountry(matched);
}
const rest = trimmed.slice(matched.code.length).replace(/\D/g, "");
setPhone(rest.slice(0, matched.maxLength));
if (phoneError) setPhoneError("");
return;
}
}
// Check if user pasted dial digits without '+' (e.g. 919876543210)
const dialDigits = selectedCountry.code.replace(/\D/g, "");
const rawDigits = trimmed.replace(/\D/g, "");
if (
dialDigits &&
rawDigits.startsWith(dialDigits) &&
rawDigits.length > selectedCountry.maxLength
) {
const rest = rawDigits.slice(dialDigits.length);
setPhone(rest.slice(0, selectedCountry.maxLength));
if (phoneError) setPhoneError("");
return;
}
const digits = text.replace(/\D/g, ""); const digits = text.replace(/\D/g, "");
setPhone(digits.slice(0, selectedCountry.maxLength)); setPhone(digits.slice(0, 10));
if (phoneError) setPhoneError("");
};
const handleCountrySelect = (c: CountryCode) => {
if (c.country !== selectedCountry.country) {
setPhone("");
}
setSelectedCountry(c);
setShowCountryModal(false);
setCountrySearch("");
if (phoneError) setPhoneError("");
}; };
const handleSignUp = async () => { const handleSignUp = async () => {
@ -126,22 +44,17 @@ export default function SignUpForm() {
hasError = true; hasError = true;
} }
const emailErr = validateEmail(email); if (!email.trim()) {
if (emailErr) { setEmailError("Email is required");
setEmailError(emailErr); hasError = true;
} else if (!/\S+@\S+\.\S+/.test(email)) {
setEmailError("Please enter a valid email address");
hasError = true; hasError = true;
} }
if (phone.trim()) { if (phone.trim() && phone.length < 10) {
const err = validatePhoneNumber( setPhoneError("Phone number must be 10 digits");
phone.trim(), hasError = true;
selectedCountry.code,
selectedCountry.country
);
if (err) {
setPhoneError(err);
hasError = true;
}
} }
if (!password) { if (!password) {
@ -159,7 +72,7 @@ export default function SignUpForm() {
} else if (!/[0-9]/.test(password)) { } else if (!/[0-9]/.test(password)) {
setPasswordError("Password must contain at least one number (0-9)"); setPasswordError("Password must contain at least one number (0-9)");
hasError = true; hasError = true;
} else if (!/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?~`]/.test(password)) { } else if (!/[^A-Za-z0-9\s]/.test(password)) {
setPasswordError("Password must contain at least one special character (!@#$)"); setPasswordError("Password must contain at least one special character (!@#$)");
hasError = true; hasError = true;
} }
@ -174,28 +87,20 @@ export default function SignUpForm() {
if (hasError) return; if (hasError) return;
setIsLoading(true);
try { try {
const formattedPhone = phone.trim()
? formatE164Phone(selectedCountry.code, phone.trim(), selectedCountry.country)
: undefined;
const response = await register({ const response = await register({
email: email.trim().toLowerCase(), email: email.trim().toLowerCase(),
password, password,
full_name: fullName.trim(), full_name: fullName.trim(),
phone_number: formattedPhone, phone_number: phone.trim() ? phone.trim() : undefined,
country: selectedCountry.country,
}); });
const { user } = response; const { user } = response;
setRegisteredUser({ setRegisteredUser({
id: user.id, id: user.id,
name: user.display_name ?? fullName.trim(), name: user.display_name,
email: user.email, email: user.email,
phone_number: user.phone_number ?? formattedPhone,
country: user.country ?? selectedCountry.country,
}); });
// Redirect directly to login screen without alert block // Redirect directly to login screen without alert block
@ -209,8 +114,6 @@ export default function SignUpForm() {
errMsg = detail[0].msg || JSON.stringify(detail[0]); errMsg = detail[0].msg || JSON.stringify(detail[0]);
} }
alert("Registration Failed: " + errMsg); alert("Registration Failed: " + errMsg);
} finally {
setIsLoading(false);
} }
}; };
@ -238,49 +141,18 @@ export default function SignUpForm() {
error={emailError} error={emailError}
/> />
{/* Phone Number Field with Country Dial Code */} <BaseTextInput
<View style={styles.phoneFieldWrapper}> value={phone}
<View style={[styles.phoneContainer, phoneError ? styles.errorBorder : null]}> onChangeText={handlePhoneChange}
<Pressable placeholder="Phone Number (Optional)"
accessibilityRole="button" keyboardType="number-pad"
accessibilityLabel="Select Country and Dial Code" autoCapitalize="none"
onPress={() => setShowCountryModal(true)} autoCorrect={false}
style={styles.dialCodeButton} textContentType="telephoneNumber"
> maxLength={10}
<Text style={styles.dialCodeText}>{selectedCountry.label}</Text> leftIcon="call-outline"
<Ionicons error={phoneError}
name="chevron-down" />
size={moderateScale(14)}
color={AuthColors.textSecondary}
style={{ marginLeft: scale(5) }}
/>
</Pressable>
<View style={styles.phoneDivider} />
<TextInput
value={phone}
onChangeText={handlePhoneChange}
placeholder={selectedCountry.placeholder || "Phone Number (Optional)"}
placeholderTextColor={AuthColors.textSecondary}
keyboardType="number-pad"
autoCapitalize="none"
autoCorrect={false}
textContentType="telephoneNumber"
maxLength={selectedCountry.maxLength}
style={styles.phoneInput}
/>
</View>
{phoneError ? (
<Text style={styles.errorText}>{phoneError}</Text>
) : (
<Text style={styles.phoneHelperText}>
{selectedCountry.minLength === selectedCountry.maxLength
? `${selectedCountry.country}: Requires exactly ${selectedCountry.maxLength} digits`
: `${selectedCountry.country}: ${selectedCountry.minLength} to ${selectedCountry.maxLength} digits`}
</Text>
)}
</View>
<PasswordInput <PasswordInput
value={password} value={password}
@ -299,128 +171,9 @@ export default function SignUpForm() {
<View style={styles.buttonSpacing}> <View style={styles.buttonSpacing}>
<PrimaryButton <PrimaryButton
title="Sign Up" title="Sign Up"
loading={isLoading}
onPress={handleSignUp} onPress={handleSignUp}
/> />
</View> </View>
{/* Country Selection Modal */}
<Modal
visible={showCountryModal}
transparent
animationType="slide"
onRequestClose={() => {
setShowCountryModal(false);
setCountrySearch("");
}}
>
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : undefined}
style={styles.modalOverlay}
>
<Pressable
style={StyleSheet.absoluteFill}
onPress={() => {
setShowCountryModal(false);
setCountrySearch("");
}}
/>
<View style={styles.modalSheet}>
<View style={styles.modalHeader}>
<Text style={styles.modalTitle}>Select Country</Text>
<Pressable
hitSlop={8}
onPress={() => {
setShowCountryModal(false);
setCountrySearch("");
}}
>
<Ionicons
name="close"
size={moderateScale(22)}
color={AuthColors.textSecondary}
/>
</Pressable>
</View>
{/* Country Search Bar */}
<View style={styles.modalSearchContainer}>
<Ionicons
name="search-outline"
size={moderateScale(17)}
color={AuthColors.textSecondary}
/>
<TextInput
value={countrySearch}
onChangeText={setCountrySearch}
placeholder="Search country or code..."
placeholderTextColor={AuthColors.textSecondary}
style={styles.modalSearchInput}
autoCapitalize="none"
autoCorrect={false}
/>
{countrySearch.length > 0 && (
<Pressable
hitSlop={8}
onPress={() => setCountrySearch("")}
>
<Ionicons
name="close-circle"
size={moderateScale(17)}
color={AuthColors.textSecondary}
/>
</Pressable>
)}
</View>
<ScrollView
showsVerticalScrollIndicator={false}
contentContainerStyle={styles.countryList}
keyboardShouldPersistTaps="handled"
>
{filteredCountries.length === 0 ? (
<View style={styles.emptyContainer}>
<Text style={styles.emptyText}>No countries found</Text>
</View>
) : (
filteredCountries.map((c) => {
const isSelected = selectedCountry.country === c.country;
return (
<Pressable
key={c.code + c.country}
style={({ pressed }) => [
styles.countryItem,
isSelected && styles.countryItemSelected,
pressed && styles.countryItemPressed,
]}
onPress={() => handleCountrySelect(c)}
>
<View style={styles.countryRow}>
<Text style={styles.countryLabel}>{c.label}</Text>
<Text
style={[
styles.countryName,
isSelected && styles.countryNameSelected,
]}
>
{c.country}
</Text>
</View>
{isSelected && (
<Ionicons
name="checkmark"
size={moderateScale(18)}
color={Colors.primary}
/>
)}
</Pressable>
);
})
)}
</ScrollView>
</View>
</KeyboardAvoidingView>
</Modal>
</View> </View>
); );
} }
@ -432,154 +185,4 @@ const styles = StyleSheet.create({
buttonSpacing: { buttonSpacing: {
marginTop: verticalScale(10), marginTop: verticalScale(10),
}, },
phoneFieldWrapper: {
marginBottom: verticalScale(18),
},
phoneContainer: {
flexDirection: "row",
alignItems: "center",
backgroundColor: AuthColors.inputBackground,
borderWidth: 1,
borderColor: AuthColors.border,
borderRadius: moderateScale(16),
paddingHorizontal: scale(12),
height: verticalScale(56),
},
dialCodeButton: {
flexDirection: "row",
alignItems: "center",
paddingVertical: verticalScale(8),
paddingHorizontal: scale(4),
},
dialCodeText: {
fontSize: moderateScale(14),
fontWeight: "700",
color: AuthColors.textPrimary,
},
phoneDivider: {
width: 1,
height: verticalScale(28),
backgroundColor: AuthColors.border,
marginHorizontal: scale(10),
},
phoneInput: {
flex: 1,
fontSize: moderateScale(15),
color: AuthColors.textPrimary,
paddingVertical: 0,
},
errorBorder: {
borderColor: AuthColors.danger,
},
errorText: {
color: AuthColors.danger,
fontSize: moderateScale(12),
marginTop: verticalScale(6),
marginLeft: scale(6),
},
phoneHelperText: {
color: AuthColors.textSecondary,
fontSize: moderateScale(11),
marginTop: verticalScale(4),
marginLeft: scale(6),
},
modalOverlay: {
flex: 1,
backgroundColor: "rgba(0, 0, 0, 0.45)",
justifyContent: "flex-end",
},
modalSheet: {
backgroundColor: "#FFFFFF",
borderTopLeftRadius: moderateScale(20),
borderTopRightRadius: moderateScale(20),
maxHeight: "75%",
paddingTop: verticalScale(16),
paddingBottom: verticalScale(32),
},
modalHeader: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
paddingHorizontal: scale(20),
paddingBottom: verticalScale(12),
borderBottomWidth: 1,
borderBottomColor: "#F1F5F9",
},
modalTitle: {
fontSize: moderateScale(17),
fontWeight: "700",
color: Colors.textPrimary,
},
countryList: {
paddingHorizontal: scale(16),
paddingTop: verticalScale(8),
},
countryItem: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
paddingVertical: verticalScale(12),
paddingHorizontal: scale(12),
borderRadius: moderateScale(10),
},
countryItemSelected: {
backgroundColor: "#DCFCE7",
},
countryItemPressed: {
backgroundColor: "#F1F5F9",
},
countryRow: {
flexDirection: "row",
alignItems: "center",
gap: scale(10),
},
countryLabel: {
fontSize: moderateScale(15),
fontWeight: "600",
color: Colors.textPrimary,
minWidth: scale(65),
},
countryName: {
fontSize: moderateScale(14),
color: Colors.textPrimary,
fontWeight: "500",
},
countryNameSelected: {
fontWeight: "700",
color: "#15803D",
},
modalSearchContainer: {
flexDirection: "row",
alignItems: "center",
backgroundColor: "#F8FAFC",
borderWidth: 1,
borderColor: "#E2E8F0",
borderRadius: moderateScale(12),
marginHorizontal: scale(16),
marginTop: verticalScale(12),
marginBottom: verticalScale(4),
paddingHorizontal: scale(12),
height: verticalScale(42),
gap: scale(8),
},
modalSearchInput: {
flex: 1,
fontSize: moderateScale(14),
color: Colors.textPrimary,
paddingVertical: 0,
},
emptyContainer: {
paddingVertical: verticalScale(32),
alignItems: "center",
justifyContent: "center",
},
emptyText: {
fontSize: moderateScale(14),
color: AuthColors.textSecondary,
fontWeight: "500",
},
}); });

View File

@ -2,14 +2,9 @@ import React, { type ReactNode, useCallback } from "react";
import { BackHandler, Platform, Pressable, StyleSheet, Text, View } from "react-native"; import { BackHandler, Platform, Pressable, StyleSheet, Text, View } from "react-native";
import { Ionicons } from "@expo/vector-icons"; import { Ionicons } from "@expo/vector-icons";
import { router, useFocusEffect } from "expo-router"; import { router, useFocusEffect } from "expo-router";
import { moderateScale, scale } from "react-native-size-matters"; import { moderateScale } from "react-native-size-matters";
import { Colors } from "@/theme"; import { Colors } from "@/theme";
import {
type PageTone,
toneColors,
usePageTone,
} from "../../context/PageToneContext";
export interface ContentPageHeaderProps { export interface ContentPageHeaderProps {
title: string; title: string;
@ -19,8 +14,6 @@ export interface ContentPageHeaderProps {
onTitlePress?: () => void; onTitlePress?: () => void;
titleAccessibilityLabel?: string; titleAccessibilityLabel?: string;
onBack?: () => void; onBack?: () => void;
tone?: PageTone;
titleColor?: string;
} }
export function ContentPageHeader({ export function ContentPageHeader({
@ -31,14 +24,7 @@ export function ContentPageHeader({
onTitlePress, onTitlePress,
titleAccessibilityLabel, titleAccessibilityLabel,
onBack, onBack,
tone,
titleColor,
}: ContentPageHeaderProps) { }: ContentPageHeaderProps) {
const { tone: contextTone } = usePageTone();
const effectiveTone = tone || contextTone;
const resolvedTitleColor =
titleColor ||
Colors.textPrimary;
useFocusEffect( useFocusEffect(
useCallback(() => { useCallback(() => {
if (!onBack) return; if (!onBack) return;
@ -73,7 +59,7 @@ export function ContentPageHeader({
const titleContent = ( const titleContent = (
<View style={styles.titleContent}> <View style={styles.titleContent}>
<Text numberOfLines={1} style={[styles.title, { color: resolvedTitleColor }]}> <Text numberOfLines={1} style={styles.title}>
{title} {title}
</Text> </Text>
{subtitle ? ( {subtitle ? (
@ -90,16 +76,16 @@ export function ContentPageHeader({
<Pressable <Pressable
accessibilityRole="button" accessibilityRole="button"
accessibilityLabel="Go back" accessibilityLabel="Go back"
hitSlop={{ top: 12, bottom: 12, left: 12, right: 12 }} hitSlop={10}
onPress={handleBack} onPress={handleBack}
style={({ pressed }) => [ style={({ pressed }) => [
styles.backButton, styles.iconButton,
pressed && styles.backButtonPressed, pressed && styles.pressed,
]} ]}
> >
<Ionicons <Ionicons
name="chevron-back" name="chevron-back"
size={moderateScale(24)} size={24}
color={Colors.textPrimary} color={Colors.textPrimary}
/> />
</Pressable> </Pressable>
@ -153,16 +139,12 @@ const styles = StyleSheet.create({
alignItems: "center", alignItems: "center",
justifyContent: "flex-end", justifyContent: "flex-end",
}, },
backButton: { iconButton: {
width: scale(38), width: 40,
height: scale(38), height: 40,
borderRadius: scale(19), borderRadius: 20,
justifyContent: "center",
alignItems: "center", alignItems: "center",
backgroundColor: "#F1F5F9", justifyContent: "center",
},
backButtonPressed: {
backgroundColor: "#E2E8F0",
}, },
pressed: { pressed: {
opacity: 0.65, opacity: 0.65,

View File

@ -36,7 +36,7 @@ export const DivergentChannel = ({ data }: { data: Record<string, unknown> }) =>
export const LuoChannel = ({ data }: { data: Record<string, unknown> }) => ( export const LuoChannel = ({ data }: { data: Record<string, unknown> }) => (
<SectionCard title="Luo-Connecting Channel"> <SectionCard title="Luo-Connecting Channel">
<BulletList items={asStringArray(data.luo_connecting_channel)} /> <BulletList items={asStringArray(data.luo_connecting_channel)} />
<ObjectSections value={asRecord(data.luo_connecting_vessel)} withTopDivider /> <ObjectSections value={asRecord(data.luo_connecting_vessel)} />
</SectionCard> </SectionCard>
); );

View File

@ -1,69 +0,0 @@
import React, {
createContext,
useContext,
useState,
useEffect,
type PropsWithChildren,
} from "react";
import { Colors } from "@/theme";
export type PageTone = "purple" | "blue" | "green";
export interface ToneColorScheme {
accent: string;
soft: string;
border: string;
title: string;
}
export const toneColors: Record<PageTone, ToneColorScheme> = {
purple: {
accent: Colors.purple, // "#75649B"
soft: Colors.purpleSoft, // "#F6F3FA"
border: "#E8E2F2",
title: Colors.textPrimary,
},
blue: {
accent: Colors.blue, // "#4E7496"
soft: Colors.blueSoft, // "#F1F6FA"
border: "#DAE6F0",
title: Colors.textPrimary,
},
green: {
accent: Colors.primary, // "#2E7D32"
soft: "#F2F8F4",
border: "#DCEADF",
title: Colors.textPrimary,
},
};
export interface PageToneContextType {
tone: PageTone;
setTone: (tone: PageTone) => void;
}
export const PageToneContext = createContext<PageToneContextType>({
tone: "green",
setTone: () => {},
});
export function PageToneProvider({
tone: initialTone = "green",
children,
}: PropsWithChildren<{ tone?: PageTone }>) {
const [tone, setTone] = useState<PageTone>(initialTone);
useEffect(() => {
setTone(initialTone);
}, [initialTone]);
return (
<PageToneContext.Provider value={{ tone, setTone }}>
{children}
</PageToneContext.Provider>
);
}
export function usePageTone(): PageToneContextType {
return useContext(PageToneContext);
}

View File

@ -15,7 +15,7 @@ export function useModulesQuery() {
return useQuery({ return useQuery({
queryKey: contentQueryKeys.modules(preview), queryKey: contentQueryKeys.modules(preview),
queryFn: () => contentApi.getModules(preview), queryFn: () => contentApi.getModules(preview),
staleTime: 30 * 1000, staleTime: 10 * 60 * 1000,
}); });
} }

View File

@ -1,23 +1,10 @@
import { useMemo } from "react"; import { useMemo } from "react";
import { import { buildModuleTemplateReference } from "@/features/modules/module-index";
buildModuleTemplateReference,
isPointsModule,
resolveModuleCategory,
} from "@/features/modules/module-index";
import { buildContentReferenceRoute } from "../utils/content-reference"; import { buildContentReferenceRoute } from "../utils/content-reference";
import { useModulesQuery } from "./use-content-queries"; import { useModulesQuery } from "./use-content-queries";
export interface ModuleDisplayInfo { export function useModuleDisplayName(moduleCode: string) {
name: string;
homeRoute: string;
category: string | null;
isPointsModule: boolean;
isLoading: boolean;
isError: boolean;
}
export function useModuleDisplayName(moduleCode: string): ModuleDisplayInfo {
const query = useModulesQuery(); const query = useModulesQuery();
const resolved = useMemo(() => { const resolved = useMemo(() => {
@ -26,8 +13,6 @@ export function useModuleDisplayName(moduleCode: string): ModuleDisplayInfo {
return { return {
name: "Content", name: "Content",
homeRoute: "/modules", homeRoute: "/modules",
category: null,
isPointsModule: false,
}; };
} }
@ -39,20 +24,14 @@ export function useModuleDisplayName(moduleCode: string): ModuleDisplayInfo {
return { return {
name: "Content", name: "Content",
homeRoute: "/modules", homeRoute: "/modules",
category: null,
isPointsModule: isPointsModule(null, moduleCode),
}; };
} }
const category = resolveModuleCategory(module);
return { return {
name: module.name?.trim() || "Content", name: module.name?.trim() || "Content",
homeRoute: buildContentReferenceRoute( homeRoute: buildContentReferenceRoute(
buildModuleTemplateReference(module), buildModuleTemplateReference(module),
), ),
category,
isPointsModule: isPointsModule(module, moduleCode),
}; };
}, [moduleCode, query.data?.modules]); }, [moduleCode, query.data?.modules]);

View File

@ -133,7 +133,7 @@ const GalleryImage = memo(function GalleryImage({
previous.item.caption === next.item.caption previous.item.caption === next.item.caption
); );
export function ContentMediaGallery({ media, title = "Visual Reference" }: ContentMediaGalleryProps) { export function ContentMediaGallery({ media, title = "Visual reference" }: ContentMediaGalleryProps) {
const items = useMemo(() => sortMedia(media ?? []), [media]); const items = useMemo(() => sortMedia(media ?? []), [media]);
const { width: windowWidth } = useWindowDimensions(); const { width: windowWidth } = useWindowDimensions();
const carouselWidth = Math.max(windowWidth - Spacing.md * 2, 280); const carouselWidth = Math.max(windowWidth - Spacing.md * 2, 280);
@ -141,21 +141,6 @@ export function ContentMediaGallery({ media, title = "Visual Reference" }: Conte
const [viewerIndex, setViewerIndex] = useState<number | null>(null); const [viewerIndex, setViewerIndex] = useState<number | null>(null);
const listRef = useRef<FlatList<ContentMediaItem>>(null); const listRef = useRef<FlatList<ContentMediaItem>>(null);
const MAX_VISIBLE_DOTS = 7;
const visibleDots = useMemo(() => {
if (items.length <= MAX_VISIBLE_DOTS) {
return items.map((item, index) => ({ item, index }));
}
const half = Math.floor(MAX_VISIBLE_DOTS / 2);
let start = Math.max(0, activeIndex - half);
let end = start + MAX_VISIBLE_DOTS;
if (end > items.length) {
end = items.length;
start = Math.max(0, end - MAX_VISIBLE_DOTS);
}
return items.slice(start, end).map((item, i) => ({ item, index: start + i }));
}, [items, activeIndex]);
if (!items.length) return null; if (!items.length) return null;
const handleMomentumEnd = (event: NativeSyntheticEvent<NativeScrollEvent>) => { const handleMomentumEnd = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
@ -184,12 +169,6 @@ export function ContentMediaGallery({ media, title = "Visual Reference" }: Conte
offset: carouselWidth * index, offset: carouselWidth * index,
index, index,
})} })}
onScrollToIndexFailed={(info) => {
listRef.current?.scrollToOffset({
offset: info.index * carouselWidth,
animated: true,
});
}}
onMomentumScrollEnd={handleMomentumEnd} onMomentumScrollEnd={handleMomentumEnd}
renderItem={({ item, index }) => ( renderItem={({ item, index }) => (
<Pressable <Pressable
@ -213,16 +192,12 @@ export function ContentMediaGallery({ media, title = "Visual Reference" }: Conte
{items.length > 1 ? ( {items.length > 1 ? (
<View style={styles.dots} accessibilityElementsHidden> <View style={styles.dots} accessibilityElementsHidden>
{visibleDots.map(({ item, index }) => ( {items.map((item, index) => (
<Pressable <Pressable
key={item.id} key={item.id}
onPress={() => { onPress={() => {
setActiveIndex(index); setActiveIndex(index);
try { listRef.current?.scrollToIndex({ index, animated: true });
listRef.current?.scrollToIndex({ index, animated: true });
} catch {
listRef.current?.scrollToOffset({ offset: index * carouselWidth, animated: true });
}
}} }}
hitSlop={6} hitSlop={6}
> >
@ -279,12 +254,7 @@ const styles = StyleSheet.create({
}, },
zoomText: { color: Colors.white, fontSize: 12, fontWeight: "700" }, zoomText: { color: Colors.white, fontSize: 12, fontWeight: "700" },
caption: { color: Colors.textSecondary, fontSize: 13, lineHeight: 19, textAlign: "center" }, caption: { color: Colors.textSecondary, fontSize: 13, lineHeight: 19, textAlign: "center" },
dots: { dots: { flexDirection: "row", flexWrap: "wrap", justifyContent: "center", gap: 7 },
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: 7,
},
dot: { width: 7, height: 7, borderRadius: 4, backgroundColor: Colors.border }, dot: { width: 7, height: 7, borderRadius: 4, backgroundColor: Colors.border },
dotActive: { width: 18, backgroundColor: Colors.primary }, dotActive: { width: 18, backgroundColor: Colors.primary },
}); });

View File

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

View File

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

View File

@ -33,9 +33,6 @@ export function EarAcupunctureCatalogCardRenderer({
const contentCount = asNumber(attributes.content_count); const contentCount = asNumber(attributes.content_count);
const contentLabel = asString(attributes.content_label).trim(); const contentLabel = asString(attributes.content_label).trim();
const isCatalog =
contentCount !== null ||
(attributes.link as Record<string, unknown> | undefined)?.type === "template_ref";
return ( return (
<StandardIndexCard <StandardIndexCard
@ -43,8 +40,6 @@ export function EarAcupunctureCatalogCardRenderer({
subtitle={item.summary || null} subtitle={item.summary || null}
count={contentCount} count={contentCount}
countLabel={contentLabel || null} countLabel={contentLabel || null}
icon={isCatalog ? "book" : "dot"}
tone={isCatalog ? "green" : undefined}
onPress={onPress} onPress={onPress}
/> />
); );

View File

@ -6,7 +6,6 @@ import { moderateScale, verticalScale } from "react-native-size-matters";
import { Colors } from "@/theme"; import { Colors } from "@/theme";
import { asNumber, asString } from "../helpers/value"; import { asNumber, asString } from "../helpers/value";
import { CollectionScaffold } from "../shared/CollectionScaffold"; import { CollectionScaffold } from "../shared/CollectionScaffold";
import { OverviewCard } from "../shared/OverviewCard";
import type { import type {
CollectionItemRendererProps, CollectionItemRendererProps,
CollectionRendererProps, CollectionRendererProps,
@ -25,15 +24,24 @@ export function EightPrinciplesCollectionRenderer(
const header = ( const header = (
<View style={styles.overviewContainer}> <View style={styles.overviewContainer}>
<OverviewCard <View style={styles.overviewCard}>
style={styles.overviewCard} <View style={styles.overviewHeader}>
paragraphs={[ <Ionicons name="information-circle" size={20} color={Colors.primary} />
"The eight principles include exterior, interior, cold, heat, deficiency, excess, yin and yang. Syndrome differentiation (pattern identification) of the eight principles is an essential paradigm in the Chinese medicine system.", <Text style={styles.overviewTitle}>Overview</Text>
"Pattern identification of the eight principles aims to tell about the disease location, the pathogenic nature and the strength between antipathogenic qi and pathogenic factors, thus generalizing the condition into eight categories.", </View>
"The eight principles can be divided into four pairs: interior/exterior for the depth of pathogens; cold/heat for the disease nature; deficiency/excess for the strength between antipathogenic qi and pathogenic factors; and yin/yang for the preponderance of yin and yang. However, yin and yang can also generalize the other six principles: exterior, heat and excess are ascribed to yang, and interior, cold and deficiency to yin.", <Text style={styles.overviewText}>
"Two or more principles may occur concurrently, such as an exterior cold syndrome and an interior deficiency cold syndrome. A combined deficiency and excess may also be present. The principles may transform into each other as well, such as cold transforming into heat, or the exterior entering the interior. Additionally, a true cold may sometimes manifest as a false heat or vice versa.", The eight principles include exterior, interior, cold, heat, deficiency, excess, yin and yang. Syndrome differentiation (pattern identification) of the eight principles is an essential paradigm in the Chinese medicine system.
]} </Text>
/> <Text style={styles.overviewParagraph}>
Pattern identification of the eight principles aims to tell about the disease location, the pathogenic nature and the strength between antipathogenic qi and pathogenic factors, thus generalizing the condition into eight categories.
</Text>
<Text style={styles.overviewParagraph}>
The eight principles can be divided into four pairs: interior/exterior for the depth of pathogens; cold/heat for the disease nature; deficiency/excess for the strength between antipathogenic qi and pathogenic factors; and yin/yang for the preponderance of yin and yang. However, yin and yang can also generalize the other six principles: exterior, heat and excess are ascribed to yang, and interior, cold and deficiency to yin.
</Text>
<Text style={styles.overviewParagraph}>
Two or more principles may occur concurrently, such as an exterior cold syndrome and an interior deficiency cold syndrome. A combined deficiency and excess may also be present. The principles may transform into each other as well, such as cold transforming into heat, or the exterior entering the interior. Additionally, a true cold may sometimes manifest as a false heat or vice versa.
</Text>
</View>
<Text style={styles.sectionHeading}>Eight Principles</Text> <Text style={styles.sectionHeading}>Eight Principles</Text>
</View> </View>
); );
@ -103,8 +111,35 @@ const styles = StyleSheet.create({
marginBottom: verticalScale(14), marginBottom: verticalScale(14),
}, },
overviewCard: { overviewCard: {
backgroundColor: "#FFFFFF",
borderRadius: moderateScale(16),
borderWidth: 1,
borderColor: "#E2EAE5",
padding: moderateScale(16),
marginBottom: verticalScale(14), marginBottom: verticalScale(14),
}, },
overviewHeader: {
flexDirection: "row",
alignItems: "center",
marginBottom: verticalScale(8),
gap: moderateScale(8),
},
overviewTitle: {
fontSize: moderateScale(16),
fontWeight: "700",
color: Colors.textPrimary,
},
overviewText: {
fontSize: moderateScale(13),
lineHeight: verticalScale(19),
color: Colors.textSecondary,
},
overviewParagraph: {
fontSize: moderateScale(13),
lineHeight: verticalScale(19),
color: Colors.textSecondary,
marginTop: verticalScale(10),
},
sectionHeading: { sectionHeading: {
fontSize: moderateScale(15), fontSize: moderateScale(15),
fontWeight: "700", fontWeight: "700",

View File

@ -14,16 +14,9 @@ export function EovCollectionRenderer(props: CollectionRendererProps) {
} }
export function EovIndexCardRenderer({ item, onPress }: CollectionItemRendererProps) { export function EovIndexCardRenderer({ item, onPress }: CollectionItemRendererProps) {
const a = item.attributes; const a = item.attributes;
const subtitle =
asString(a.sub_title) ||
asString(a.subtitle) ||
(asStringArray(a.alt_name).length > 0 ? asStringArray(a.alt_name).join(", ") : asString(a.alt_name)) ||
null;
return ( return (
<StandardIndexCard <StandardIndexCard
title={asString(a.name) || item.title} title={asString(a.name) || item.title}
subtitle={subtitle}
count={asNumber(a.content_count)} count={asNumber(a.content_count)}
countLabel={asString(a.content_label) || null} countLabel={asString(a.content_label) || null}
onPress={onPress} onPress={onPress}

View File

@ -7,7 +7,6 @@ import { Colors } from "@/theme";
import { asNumber, asString } from "../helpers/value"; import { asNumber, asString } from "../helpers/value";
import { CollectionScaffold } from "../shared/CollectionScaffold"; import { CollectionScaffold } from "../shared/CollectionScaffold";
import { ContentCountBadge } from "../shared/ContentCountBadge"; import { ContentCountBadge } from "../shared/ContentCountBadge";
import { OverviewCard } from "../shared/OverviewCard";
import type { import type {
CollectionItemRendererProps, CollectionItemRendererProps,
CollectionRendererProps, CollectionRendererProps,
@ -16,14 +15,21 @@ import type {
export function FiveElementsCollectionRenderer(props: CollectionRendererProps) { export function FiveElementsCollectionRenderer(props: CollectionRendererProps) {
const header = ( const header = (
<View style={styles.overviewContainer}> <View style={styles.overviewContainer}>
<OverviewCard <View style={styles.overviewCard}>
style={styles.overviewCard} <View style={styles.overviewHeader}>
paragraphs={[ <Ionicons name="information-circle" size={20} color={Colors.primary} />
"The identification of patterns according to the Five Elements is based on the pathological changes occurring in dysfunctions of the Generating, Overacting and Insulting sequences of the Five Elements.", <Text style={styles.overviewTitle}>Overview</Text>
"These patterns describe clinical conditions which are often expressed by the Internal Organ patterns, but in certain cases, Five-Element patterns describe conditions falling outside their scope (such as Deficient Qi of Wood manifesting with timidity and indecision).", </View>
"The sequences below detail the Generating, Overacting, and Insulting relationships and their specific clinical presentations.", <Text style={styles.overviewText}>
]} The identification of patterns according to the Five Elements is based on the pathological changes occurring in dysfunctions of the Generating, Overacting and Insulting sequences of the Five Elements.
/> </Text>
<Text style={styles.overviewParagraph}>
These patterns describe clinical conditions which are often expressed by the Internal Organ patterns, but in certain cases, Five-Element patterns describe conditions falling outside their scope (such as Deficient Qi of Wood manifesting with timidity and indecision).
</Text>
<Text style={styles.overviewParagraph}>
The sequences below detail the Generating, Overacting, and Insulting relationships and their specific clinical presentations.
</Text>
</View>
<Text style={styles.sectionHeading}>Sequences</Text> <Text style={styles.sectionHeading}>Sequences</Text>
</View> </View>
); );
@ -45,10 +51,11 @@ export function FiveElementsCardRenderer({
}: CollectionItemRendererProps) { }: CollectionItemRendererProps) {
const attributes = item.attributes; const attributes = item.attributes;
const title = asString(attributes.title) || asString(attributes.name) || item.title; const title = asString(attributes.title) || asString(attributes.name) || item.title;
const subtitle = const label =
asString(attributes.sub_title) || asString(attributes.content_label) ||
asString(attributes.description) || asString(attributes.description) ||
(item.summary && item.summary !== "Open sequence" ? item.summary : null); item.summary ||
"Open sequence";
const sortOrder = asNumber(attributes.sort_order); const sortOrder = asNumber(attributes.sort_order);
const sequenceNumber = typeof sortOrder === "number" ? sortOrder + 1 : undefined; const sequenceNumber = typeof sortOrder === "number" ? sortOrder + 1 : undefined;
@ -65,11 +72,9 @@ export function FiveElementsCardRenderer({
<View style={styles.textContainer}> <View style={styles.textContainer}>
<Text style={styles.title}>{title}</Text> <Text style={styles.title}>{title}</Text>
{subtitle ? ( <Text style={styles.description} numberOfLines={1}>
<Text style={styles.description} numberOfLines={1}> {label}
{subtitle} </Text>
</Text>
) : null}
</View> </View>
<ContentCountBadge <ContentCountBadge
@ -86,8 +91,35 @@ const styles = StyleSheet.create({
marginBottom: verticalScale(14), marginBottom: verticalScale(14),
}, },
overviewCard: { overviewCard: {
backgroundColor: "#FFFFFF",
borderRadius: moderateScale(16),
borderWidth: 1,
borderColor: "#E2EAE5",
padding: moderateScale(16),
marginBottom: verticalScale(14), marginBottom: verticalScale(14),
}, },
overviewHeader: {
flexDirection: "row",
alignItems: "center",
marginBottom: verticalScale(8),
gap: moderateScale(8),
},
overviewTitle: {
fontSize: moderateScale(16),
fontWeight: "700",
color: Colors.textPrimary,
},
overviewText: {
fontSize: moderateScale(13),
lineHeight: verticalScale(19),
color: Colors.textSecondary,
},
overviewParagraph: {
fontSize: moderateScale(13),
lineHeight: verticalScale(19),
color: Colors.textSecondary,
marginTop: verticalScale(10),
},
sectionHeading: { sectionHeading: {
fontSize: moderateScale(15), fontSize: moderateScale(15),
fontWeight: "700", fontWeight: "700",

View File

@ -7,7 +7,6 @@ import { Colors } from "@/theme";
import { asNumber, asString } from "../helpers/value"; import { asNumber, asString } from "../helpers/value";
import { CollectionScaffold } from "../shared/CollectionScaffold"; import { CollectionScaffold } from "../shared/CollectionScaffold";
import { ContentCountBadge } from "../shared/ContentCountBadge"; import { ContentCountBadge } from "../shared/ContentCountBadge";
import { OverviewCard } from "../shared/OverviewCard";
import type { import type {
CollectionItemRendererProps, CollectionItemRendererProps,
CollectionRendererProps, CollectionRendererProps,
@ -16,17 +15,30 @@ import type {
export function FourLevelsCollectionRenderer(props: CollectionRendererProps) { export function FourLevelsCollectionRenderer(props: CollectionRendererProps) {
const header = ( const header = (
<View style={styles.overviewContainer}> <View style={styles.overviewContainer}>
<OverviewCard <View style={styles.overviewCard}>
style={styles.overviewCard} <View style={styles.overviewHeader}>
paragraphs={[ <Ionicons name="information-circle" size={20} color={Colors.primary} />
"The Four Levels of Diagnosis in Traditional Chinese Medicine (TCM) is a framework mainly used in Warm Disease Theory (Wen Bing), which deals with febrile (heat) diseases caused by external pathogens, especially warm pathogens like viruses or bacteria. It helps practitioners understand the progression of the disease and guide treatment.", <Text style={styles.overviewTitle}>Overview</Text>
"The interpretation of clinical manifestations of Warm Diseases according to the Four Levels was formulated by Ye Tian Shi. This is a brilliant theory that provides the most clinically useful tool to diagnose, interpret and treat diseases caused by external Wind-Heat and their consequences, whether they are Warm Diseases or not.", </View>
"The theory of the Four Levels is clinically more relevant than that of the Six Stages. For example, one of the most common consequences of an invasion of Wind-Heat is the transformation of external Wind-Heat into interior Phlegm-Heat in the Lungs, causing a chest infection: this situation is contemplated in the Four Levels (corresponding to Lung-Heat, Qi level), while it is not contemplated in the Six Stages.", <Text style={styles.overviewText}>
"The Qi level contemplates the pattern of Damp-Heat in Stomach and Spleen as a consequence of an invasion of Wind-Heat: this is a very common clinical situation and yet it is one that is not contemplated in the Six Stages.", The Four Levels of Diagnosis in Traditional Chinese Medicine (TCM) is a framework mainly used in Warm Disease Theory (Wen Bing), which deals with febrile (heat) diseases caused by external pathogens, especially warm pathogens like viruses or bacteria. It helps practitioners understand the progression of the disease and guide treatment.
"The Blood level includes patterns which are characterized by convulsions from the development of internal Wind: these are typical complications of children’s diseases such as meningitis but they are not contemplated in the Six Stages.", </Text>
"The Four Levels are the Defensive Qi, Qi, Nutritive Qi and Blood levels (Wei, Qi, Ying, Xue): the first level is the only exterior one characterized by the presence of the external Wind-Heat on the energetic surface of the body. The other three levels are all interior and all characterized by interior Heat; however, the brilliance of this theory lies in its identification of three different depths of penetration of interior pathogenic Heat. Each level has its own distinctive pathology and treatment.", <Text style={styles.overviewParagraph}>
]} The interpretation of clinical manifestations of Warm Diseases according to the Four Levels was formulated by Ye Tian Shi. This is a brilliant theory that provides the most clinically useful tool to diagnose, interpret and treat diseases caused by external Wind-Heat and their consequences, whether they are Warm Diseases or not.
/> </Text>
<Text style={styles.overviewParagraph}>
The theory of the Four Levels is clinically more relevant than that of the Six Stages. For example, one of the most common consequences of an invasion of Wind-Heat is the transformation of external Wind-Heat into interior Phlegm-Heat in the Lungs, causing a chest infection: this situation is contemplated in the Four Levels (corresponding to Lung-Heat, Qi level), while it is not contemplated in the Six Stages.
</Text>
<Text style={styles.overviewParagraph}>
The Qi level contemplates the pattern of Damp-Heat in Stomach and Spleen as a consequence of an invasion of Wind-Heat: this is a very common clinical situation and yet it is one that is not contemplated in the Six Stages.
</Text>
<Text style={styles.overviewParagraph}>
The Blood level includes patterns which are characterized by convulsions from the development of internal Wind: these are typical complications of children’s diseases such as meningitis but they are not contemplated in the Six Stages.
</Text>
<Text style={styles.overviewParagraph}>
The Four Levels are the Defensive Qi, Qi, Nutritive Qi and Blood levels (Wei, Qi, Ying, Xue): the first level is the only exterior one characterized by the presence of the external Wind-Heat on the energetic surface of the body. The other three levels are all interior and all characterized by interior Heat; however, the brilliance of this theory lies in its identification of three different depths of penetration of interior pathogenic Heat. Each level has its own distinctive pathology and treatment.
</Text>
</View>
<Text style={styles.sectionHeading}>Levels</Text> <Text style={styles.sectionHeading}>Levels</Text>
</View> </View>
); );
@ -48,10 +60,11 @@ export function FourLevelsCardRenderer({
}: CollectionItemRendererProps) { }: CollectionItemRendererProps) {
const attributes = item.attributes; const attributes = item.attributes;
const title = asString(attributes.title) || asString(attributes.name) || item.title; const title = asString(attributes.title) || asString(attributes.name) || item.title;
const subtitle = const label =
asString(attributes.sub_title) || asString(attributes.content_label) ||
asString(attributes.description) || asString(attributes.description) ||
(item.summary && item.summary !== "Open content" ? item.summary : null); item.summary ||
"Open content";
const sortOrder = asNumber(attributes.sort_order); const sortOrder = asNumber(attributes.sort_order);
const levelNumber = typeof sortOrder === "number" ? sortOrder + 1 : undefined; const levelNumber = typeof sortOrder === "number" ? sortOrder + 1 : undefined;
@ -68,11 +81,9 @@ export function FourLevelsCardRenderer({
<View style={styles.textContainer}> <View style={styles.textContainer}>
<Text style={styles.title}>{title}</Text> <Text style={styles.title}>{title}</Text>
{subtitle ? ( <Text style={styles.description} numberOfLines={1}>
<Text style={styles.description} numberOfLines={1}> {label}
{subtitle} </Text>
</Text>
) : null}
</View> </View>
<ContentCountBadge <ContentCountBadge
@ -89,8 +100,35 @@ const styles = StyleSheet.create({
marginBottom: verticalScale(14), marginBottom: verticalScale(14),
}, },
overviewCard: { overviewCard: {
backgroundColor: "#FFFFFF",
borderRadius: moderateScale(16),
borderWidth: 1,
borderColor: "#E2EAE5",
padding: moderateScale(16),
marginBottom: verticalScale(14), marginBottom: verticalScale(14),
}, },
overviewHeader: {
flexDirection: "row",
alignItems: "center",
marginBottom: verticalScale(8),
gap: moderateScale(8),
},
overviewTitle: {
fontSize: moderateScale(16),
fontWeight: "700",
color: Colors.textPrimary,
},
overviewText: {
fontSize: moderateScale(13),
lineHeight: verticalScale(19),
color: Colors.textSecondary,
},
overviewParagraph: {
fontSize: moderateScale(13),
lineHeight: verticalScale(19),
color: Colors.textSecondary,
marginTop: verticalScale(10),
},
sectionHeading: { sectionHeading: {
fontSize: moderateScale(15), fontSize: moderateScale(15),
fontWeight: "700", fontWeight: "700",

View File

@ -1,578 +0,0 @@
import React, { useMemo } from "react";
import { StyleSheet, Text, View } from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { moderateScale, verticalScale } from "react-native-size-matters";
import { Colors } from "@/theme";
import { asString, humanizeKey } from "../helpers/value";
import { Hero } from "../shared/Hero";
import { CollectionScaffold } from "../shared/CollectionScaffold";
import { OverviewCard } from "../shared/OverviewCard";
import type { CollectionRendererProps } from "../../types/renderer.types";
export interface GynecologyDiseaseInfo {
title: string;
code?: string;
overview: string;
}
export const GYNECOLOGY_DISEASE_DATA: Record<string, GynecologyDiseaseInfo> = {
"m0042_ct0011": {
title: "Early Periods",
code: "early_periods",
overview: "Early Periods are defined as periods that come consistently up to 9 days early so that the cycle is less than 28 days long; the definition applies if this happens more than twice in succession. The amount of bleeding may be normal, scanty or excessive.",
},
"m0042_ct0012": {
title: "Late Periods",
code: "late_periods",
overview: "The periods are defined as Late Periods when they arrive late so that the menstrual cycle is longer than 28–30 days consistently (or at least for 3 consecutive months). It can be up to 40–50 days long. If the periods are only occasionally late, this may be due to external circumstances such as emotional upsets or travelling. Obviously, if after always being regular the period is suddenly late one month, then this might indicate pregnancy.",
},
"m0042_ct0013": {
title: "Irregular Periods",
code: "irregular_periods",
overview: "The term ‘Irregular Periods’ refers to periods that come with an irregular cycle, sometimes early, sometimes late. It is important to note that if the periods come consistently early or consistently late, they fall under the categories of Early Periods or Late Periods respectively: thus, it is only when they are sometimes late and sometimes early in an unpredictable manner that they constitute Irregular Periods. An irregularity of the cycle in the time preceding the menopause is normal; similarly for some months after the menarche.",
},
"m0042_ct0014": {
title: "Heavy Periods",
code: "heavy_periods",
overview: "‘Heavy Periods’ means periods that occur regularly and last the customary 5 days or thereabouts but are heavier than normal. As mentioned in physiology, the average blood loss during a menstrual cycle is 30-80 ml. Since the range of blood loss is quite broad, the definition of a ‘heavy’ period can be rather subjective and difficult to gauge. Generally speaking, a period may be called ‘heavy’ if it starts with a gush of blood, catching the woman unaware and necessitating an urgent resort to a tampon or sanitary towel (pad), or if the woman has to make very frequent changes of these protective devices.\n\nAs a category of disease-symptom in Chinese medicine, Heavy Periods should be differentiated from Flooding and Trickling. The former consists of heavy bleeding which occurs at the proper time and within the proper span of the periods (approximately 5 days); the latter consists of very heavy bleeding that may both start before the proper time and continue after it, and may also trickle on for a long time after the period should have ended. The distinction between these two conditions is not too important in terms of pathology and treatment, which are essentially the same, but it matters from a prognostic perspective: in fact, Flooding and Trickling is more difficult to treat than Heavy Periods.",
},
"m0042_ct0015": {
title: "Scanty Periods",
code: "scanty_periods",
overview: "The periods are defined as ‘Scanty Periods’ when the bleeding is very light (so as to necessitate few changes of sanitary towels/pads or tampons), or when the bleeding lasts only 2–3 days or is extremely scanty, like a small drip. It is important to ask women about the amount of bleeding in detail as most of them do not see scanty bleeding as a ‘problem’. Thus, if we ask only a general question, such as ‘Is the amount of bleeding normal?’, a woman might reply ‘Yes’ although her periods in fact last only 2 days. Because few women see scanty periods as a matter of concern, it is seldom the main presenting problem and is usually treated only when it accompanies other conditions. For example, a woman might complain of tiredness as her main problem; were this due to Blood deficiency, her periods might be scanty and therefore need treatment.",
},
"m0042_ct0016": {
title: "Long Periods",
code: "long_periods",
overview: "Long Periods are characterized by prolonged bleeding which may last 7–10 days; the cycle is regular and the amount of bleeding itself is not excessive. Thus, they differ from Heavy Periods, in which the amount of bleeding is excessive, and from Flooding and Trickling, in which the cycle is somewhat irregular because bleeding can occur before the right time.",
},
"m0042_ct0017": {
title: "Painful Periods",
code: "painful_periods",
overview: "Painful Periods indicates menstrual pain that occurs before, during or after menstruation. The pain may occur in the lower abdomen or sacral region and sometimes extend to the legs. In severe cases, there may be nausea and vomiting or even fainting.\n\nThe Liver, Penetrating Vessel and Directing Vessel are responsible for the physiology of menstruation. For a normal period to occur, Blood must be abundant and move adequately. Proper movement of Blood relies on the free flow of Liver-Qi and of the Qi of the Penetrating Vessel.\n\nAs we have seen in physiology, four different phases may be identified in each menstrual cycle. During the pre-menstrual phase, Yang rises and Liver-Qi moves in preparation for moving Blood during the period. Thus, a proper movement of Liver-Qi and Liver-Blood is essential for a pain-free period. If Liver-Qi stagnates, it may cause pain, especially before the period, while if Liver-Blood stagnates, it causes pain during the period. Stagnation is therefore the most important pathological condition causing painful periods: even in deficiency conditions when the pain is mild, it is some element of stagnation that causes it.",
},
"m0042_ct0018": {
title: "Bleeding between Periods",
code: "bleeding_between_periods",
overview: "An irregularity of the cycle is menstrual bleeding that occurs consistently at about the mid-point of the cycle. The bleeding may last 1-2 days or even longer; if it lasts much longer and is relatively heavy, this condition may be mistakenly interpreted as being Early Periods. The main factors are usually a disharmony of Yin-Yang, imbalance of Qi and Blood, stasis of Blood or Damp-Heat.\n\nBleeding between Periods should be differentiated from Early Periods, Flooding and Trickling (Beng Lou) and Red or White-Red Leucorrhea. Early Periods are characterized by bleeding some time before the normal; the amount of bleeding is normal or profuse. Flooding and Trickling is characterized by either very heavy bleeding at or before the right time or long trickling of blood after the period. Red or Red–White Leucorrhea is characterized by a persistent discharge, unrelated to the cycle, but which, especially in the case of Red Leucorrhea, may be mistaken for menstrual blood.",
},
"m0042_ct0019": {
title: "No Periods (Amenorrhea)",
code: "no_periods_amenorrhea",
overview: "The absence of periods (amenorrhea) is called Bi Jing in Chinese: Jing means menstruation and bi means 'shut' or 'closed'. Western medicine distinguishes between primary amenorrhea, which occurs when a woman has not had a period by the time she is 18, and secondary amenorrhea, which occurs when a woman has had periods but they have stopped for at least 3 months.\n\nObviously, the temporary interruption of the menses that occurs after childbirth and during breastfeeding is not considered amenorrhea, nor, similarly, is the stopping of the menses for 1 or 2 months as a consequence of sudden environmental or living condition changes. If a woman presents with secondary amenorrhea, it is of course very important to exclude pregnancy first of all because, were the patient treated for amenorrhea, the medicines are contraindicated in pregnancy. We shall call this condition 'No Periods' rather than 'amenorrhea'.",
},
"m0042_ct0020": {
title: "Flooding and Trickling (Metrorrhagia)",
code: "flooding_and_trickling_metrorrhagia",
overview: "The condition of Flooding and Trickling is called Beng Lou in Chinese: beng means 'flood' or 'flooding, bursting through' and lou means 'trickle, drip, dribble' or 'trickling, dripping, dribbling, leaking'. It corresponds to metrorrhagia in Western medicine.\n\nFlooding and Trickling encompasses two distinct symptoms, the former (Beng) indicating a period that starts suddenly with a flood, often before the proper time, and the latter (Lou) a period that continues with a trickle after the proper time. Flooding and Trickling should be distinguished from Heavy Periods: the latter indicates heavy blood loss during the proper period time (about 5 days), with the periods coming at regular intervals, rather than the sudden, profuse and often early bleeding of Flooding. In terms of quantity, Flooding involves a heavier bleeding than Heavy Periods. In general, the pathology of Heavy Periods and of Flooding and Trickling is the same although the latter is a more serious condition and therefore more difficult to treat.\n\n“When Yin is deficient and Yang throbs, Flooding occurs”. This statement refers to pulse diagnosis, i.e. when the Yin pulses are deficient and the Yang pulses forceful, a woman may suffer from Flooding. However, the statement may also be interpreted in a general sense, i.e. when Yin is deficient and Yang in excess, there may be Flooding because excess Yang heats the Blood and makes it spill from the blood vessels.",
},
"m0042_ct0021": {
title: "Pre-Menstrual Syndrome (PMS)",
code: "pre_menstrual_syndrome_pms",
overview: "The term Pre-Menstrual Syndrome (PMS) broadly describes emotional and physical symptoms occurring before a period. These may include depression, sadness, irritability, anxiety, lethargy, loss of concentration, aggressiveness, changes in libido, changes in bowel habit, skin eruptions, food cravings, crying, propensity to outbursts of anger, clumsiness, distension of abdomen and breasts, and insomnia. These symptoms can vary in intensity from very mild to extremely serious; a woman suffering severe Pre-Menstrual Syndrome may actually injure a member of her family or some other person. The symptoms vary in duration as well as in intensity, ranging from 1 day to 2 weeks before the period. Rarely, these symptoms may be experienced after the period. Pre-Menstrual Syndrome is more common in the 30–40 age groups.",
},
"m0042_ct0031": {
title: "Pre-Menstrual Breast Distension",
code: "pre_menstrual_breast_distension",
overview: "Pre-menstrual breast distension is a very common problem occurring mostly before the onset of a period, although occasionally it may occur after a period. It can vary from mild to a very severe distension, with swelling, enlargement, hardness and pain. In many cases, pre-menstrual breast distension is also accompanied by small lumps in the breast which may become larger before and during the period and smaller afterwards. This corresponds to benign fibrocystic breast disease and will be discussed separately under the chapter on benign breast lumps.",
},
"m0042_ct0032": {
title: "Headaches During Periods",
code: "headaches_during_periods",
overview: "Headache occurring at period time is an extremely common problem. When chronic headache is linked to the menstrual cycle it must be treated by regulating the menses and the Uterus, plus any other treatment that may be called for. Headaches at period time may occur before, during or after the period; the incidence is more or less equal. As a rough guide, headaches occurring before the period are due to Qi or Blood stagnation; headaches during the period, to Liver-Yang rising; headaches after the period, to Blood deficiency. However, this is only a rough diagnostic guide and, in practice, there may be deviations from the above rule.",
},
"m0042_ct0033": {
title: "Edema During Periods",
code: "edema_during_periods",
overview: "Edema at period time can affect the face, hands, lower legs and abdomen. It usually occurs before the period.",
},
"m0042_ct0034": {
title: "Diarrhea During Period",
code: "diarrhea_during_period",
overview: "This includes diarrhea or loose stools occurring before, during or after each period.",
},
"m0042_ct0035": {
title: "Dizziness during Period",
code: "dizziness_during_period",
overview: "Dizziness during or in connection with the period is frequently encountered in clinical practice. It is most commonly associated with Blood deficiency or Liver-Yang rising.",
},
"m0042_ct0036": {
title: "Body Aches during Period",
code: "body_aches_during_period",
overview: "The aches and pains occur in connection with the menstrual cycle, they are often related to a Blood pathology rather than to actual Painful Obstruction Syndrome with invasion of external Wind, Dampness or Cold. Of course, the two conditions may be, and often are, combined so that there is a deficiency of Blood in the channel, which facilitates the invasion of external pathogenic factors. The treatment in such cases must definitely stress nourishing the Blood as, if this is not done, external pathogenic factors will not be expelled.",
},
"m0042_ct0037": {
title: "Fever during Period",
code: "fever_during_period",
overview: "‘Fever’ here includes both an actual fever and a pronounced feeling of heat, which is more frequent before or during the period but may also occur after it. It should be stressed that if there is only a feeling of heat, this should be both subjective and objective, i.e. the patient has a feeling of heat and her skin (particularly of the dorsum of the hands) also feels hot to the touch.",
},
"m0042_ct0038": {
title: "Mouth Ulcers during Period",
code: "mouth_ulcers_during_period",
overview: "This condition consists in the appearance of mouth and/or tongue ulcers at period time.",
},
"m0042_ct0039": {
title: "Skin Eruptions during Period",
code: "skin_eruptions_during_period",
overview: "Papular, itchy skin eruptions may appear suddenly before the period and subside after the period. Generalized skin eruptions such as these are not common but the localized around the chin and face are very common.",
},
"m0042_ct0040": {
title: "Epistaxis or Hemoptysis during Period",
code: "epistaxis_or_hemoptysis_during_period",
overview: "Epistaxis or hemoptysis may occur before, during or after the period. From a Western perspective, these symptoms may indicate endometriosis, but they may also occur in the absence of such a disease. From a Chinese perspective, they are usually associated with a situation of Qi rebelling upwards and are therefore strongly related to a Penetrating Vessel pathology: for these reasons, this condition was sometimes called ‘rebellious period’, or ‘reverse period’.",
},
"m0042_ct0051": {
title: "Morning Sickness",
code: "morning_sickness",
overview: "Morning sickness is one of the earliest signs of pregnancy although not all pregnant women have it. It may range from a mild nausea to very severe and frequent vomiting. It usually lasts only for about 3 months but in severe cases it may go on for a long time or even for the whole pregnancy. The intensity of morning sickness is obviously related to the pre-existing state of the woman’s digestive system. In spite of its name, ‘morning sickness’ can occur at any time of day although it is usually more pronounced in the morning.\n\nThe symptoms associated with nausea and vomiting should be carefully considered to distinguish Heat from Cold and deficiency from excess:\n• Vomiting soon after eating: Heat and Fullness.\n• Vomiting of dilute fluids: Cold and deficiency.\n• Vomiting with retching and belching: Liver-Qi stagnation.\n• Only slight nausea: Stomach-Qi deficiency.\n• Vomiting of sour fluids: Liver-Qi stagnation.\n• Vomiting of bitter fluids: Stomach and Liver-Heat.",
},
"m0042_ct0052": {
title: "Abdominal Pain during Pregnancy",
code: "abdominal_pain_during_pregnancy",
overview: "Mild abdominal pain is relatively frequent during pregnancy and in most cases it poses no danger to the mother or fetus. However, when faced by a pregnant woman with abdominal pain, we should first exclude the possibility of ectopic pregnancy or threatened miscarriage.",
},
"m0042_ct0053": {
title: "Fetus not Growing",
code: "fetus_not_growing",
overview: "There is essentially only one pattern in this condition and that is a deficiency of Blood and Kidneys in varying degrees. The Kidney deficiency may be of Yang or Yin.",
},
"m0042_ct0054": {
title: "Threatened Miscarriage",
code: "threatened_miscarriage",
overview: "Three conditions may be identified in Chinese medicine: ‘Vaginal Bleeding during Pregnancy’, ‘Restless Fetus’ and ‘Miscarriage’. These three conditions represent different stages of the same process: in the first two stages, the fetus has not yet been damaged and miscarriage can be prevented, while in the third stage the fetus has been injured or has already left the uterus and miscarriage cannot be prevented.\n\nFrom a Western perspective, ‘Vaginal Bleeding during Pregnancy’ corresponds to ‘threatened abortion’ and ‘Restless Fetus’ may correspond to either ‘threatened abortion’ or to ‘inevitable abortion’.\n\nWith regard to vaginal bleeding, however, it should be remembered that a slight bleeding a few weeks after becoming pregnant sometimes occurs without consequence and does not necessarily indicate a threatened miscarriage.",
},
"m0042_ct0055": {
title: "Habitual Miscarriage",
code: "habitual_miscarriage",
overview: "‘Habitual miscarriage’ is usually defined as such after three occurrences. In Chinese medicine, miscarriage takes different names according to the time of pregnancy it occurs. If it occurs within 1 month of pregnancy, it is called an chan, which means ‘hidden labor’. Between 1 and 3 months, it is called duo tai, which means ‘falling fetus’. After 3 months it is called xiao chan or ban chan, which mean ‘small labor’ or ‘half labor’ respectively. Habitual miscarriage is called hua tai, which means ‘slippery fetus’.\n\nIt is important to remember that, according to the experience of Chinese medicine, a miscarriage is as draining to a woman’s energy as labor.",
},
"m0042_ct0056": {
title: "Feeling of Suffocation during Pregnancy",
code: "feeling_of_suffocation_during_pregnancy",
overview: "This condition is called zi xuan in Chinese, xuan meaning ‘suspended’ or ‘anxious’, and also tai qi shang ni, which means ‘fetus’s Qi rebelling upwards’. It includes a feeling of tightness of the chest, anxiety, breathlessness and mental restlessness.",
},
"m0042_ct0057": {
title: "Edema during Pregnancy",
code: "edema_during_pregnancy",
overview: "In Chinese medicine, edema in pregnancy was given different names according to its location:\n• Zi zhong: ‘edema of pregnancy’, indicated edema of the face and whole body together with scanty urination.\n• Zi man: ‘fullness of pregnancy’, indicated swelling of the body with abdominal distension and breathlessness.\n• Zi Qi: ‘Qi of pregnancy’, referred to edema below the knees, with scanty urination, and was caused by Dampness.\n• Zhou jiao: ‘wrinkled foot’, indicated edema of the feet from Dampness.\n• Cui jiao: ‘brittle foot’, referred to edema of the feet from overflowing of Water.",
},
"m0042_ct0058": {
title: "Urinary Syndrome during Pregnancy",
code: "urinary_syndrome_during_pregnancy",
overview: "This condition includes frequency, pain and urgency of urination. It was called zi lin, i.e. ‘lin’ disease in pregnancy, ‘lin’ being Urinary Syndrome.",
},
"m0042_ct0059": {
title: "Retention of Urine during Pregnancy",
code: "retention_of_urine_during_pregnancy",
overview: "This condition is characterized by difficult urination, slight retention of urine, an uncomfortable feeling in the lower abdomen and a feeling of irritability.",
},
"m0042_ct0060": {
title: "Anxiety during Pregnancy",
code: "anxiety_during_pregnancy",
overview: "Anxiety in pregnancy is called zi fan, which literally means ‘child mental restlessness’, intending by that ‘mental restlessness of pregnancy’.",
},
"m0042_ct0061": {
title: "Dizziness during Pregnancy",
code: "dizziness_during_pregnancy",
overview: "Dizziness and vertigo, called zi yun, usually occur in the second and third trimesters of pregnancy. They occur with different degrees of severity: very severe vertigo can be a prodromal symptom of pre-eclampsia or eclampsia, which in Chinese medicine corresponds to ‘convulsions in pregnancy’ (zi xian).",
},
"m0042_ct0062": {
title: "Convulsions during Pregnancy",
code: "convulsions_during_pregnancy",
overview: "This condition is called zi xian, which means ‘convulsions in pregnancy’: it clearly corresponds to eclampsia in Western medicine. It is a condition that occurs not only in pregnancy but also soon after childbirth. The main manifestations are severe dizziness, headache, vomiting, hypertension and, in its late stages, tremors of limbs, convulsions and coma.",
},
"m0042_ct0063": {
title: "Cough during Pregnancy",
code: "cough_during_pregnancy",
overview: "Cough in pregnancy is a condition that is characterized not only by a persistent cough but also by mental restlessness and a feeling of heat.",
},
"m0042_ct0064": {
title: "Aphonia during Pregnancy",
code: "aphonia_during_pregnancy",
overview: "Loss of voice or hoarseness occurring towards the end of pregnancy is called zi yin, which means ‘loss of voice in pregnancy’.",
},
"m0042_ct0071": {
title: "Abdominal Pain after childbirth",
code: "abdominal_pain_after_childbirth",
overview: "The pathology of Abdominal Pain after Childbirth is, as always, characterized by either a deficiency or an excess condition. The Golden Mirror of Medicine says: \u201cPost-partum abdominal pain is caused by deficiency of Blood if there is heavy loss of blood; by stasis of Blood if lochia are retained; by retention of Food if there is poor appetite, distension and fullness; and by invasion of Cold if pain is accompanied by a cold feeling.\u201d Deficient Blood and Qi may cause abdominal pain of a deficient nature, i.e. quite mild, better with pressure and better after eating. Causes which are excess in nature include stagnation of Qi, stasis of Blood and retention of food: these cause a Full type of pain which is more intense, with a feeling of distension in the case of Qi stagnation and fixed, stabbing in the case of Blood stasis. Full-type pain is worse with pressure and worse after eating. It is also possible to have a mixed deficiency/excess condition since when Qi and Blood are deficient, they fail to move Blood properly and hence some stasis of Blood ensues. The Complete Works of Jing Yue says: \u201cDeficiency and Excess should be differentiated in the treatment of post-partum abdominal pain. Pain from stasis of Blood is of the Excess type, while that due to deficiency of Blood is of the Deficient type. Pain accompanied by a feeling of distension or a sensation as if a stream of air was rushing upwards to the chest and hypochondrium, aggravated by pressure, is of the Excess type. To treat it, one must move Qi and disperse. Pain without distension or fullness and alleviated by pressure, warmth or eating, is of the Deficient type. One should not use herbs that expel pathogenic factors.\u201d When a woman has abdominal pain after childbirth, any question of infection must first be excluded. From a Chinese perspective, abdominal pain from infection would be accompanied by shivering, fever that rises continuously and discharge of lochia with a smell like rancid soya sauce.",
},
"m0042_ct0072": {
title: "Breast Milk not Flowing",
code: "breast_milk_not_flowing",
overview: "This condition consists of scanty or absent breast milk after childbirth. The term \u2018Breast Milk not Flowing\u2019 is used in place of \u2018Insufficient Lactation\u2019 or \u2018Agalactia\u2019 because these two terms imply a deficiency, a lack of a vital substance; lack of breast milk, however, may be due not only to a deficiency of milk but also to an obstruction or stagnation that prevents the flow of milk.",
},
"m0042_ct0073": {
title: "Collapse after Childbirth",
code: "collapse_after_childbirth",
overview: "Collapse after Childbirth indicates a condition characterized by severe dizziness with a sudden onset. The woman cannot stand or sit, she has blurred vision and a feeling of tightness of the chest, she suffers nausea and vomiting and, in extreme cases, may faint.",
},
"m0042_ct0074": {
title: "Constipation after Childbirth",
code: "4.07",
overview: "Constipation after Childbirth refers to difficult, dry or very infrequent defecation. Constipation occurring after childbirth in a woman who previously had regular bowel movements is usually due to Blood deficiency and dryness following excessive blood loss during labor. When Blood and fluids are exhausted, the Large Intestine is affected and deficiency of fluids in this organ makes the passage of stools difficult. A state of dryness may also occur as a result of profuse spontaneous sweating after childbirth, but this is rare. Apart from the Large Intestine, the pathology of constipation after childbirth is also related to the Liver when deficient Liver-Blood fails to moisten the faces, and to the Lungs when deficient Lung-Qi fails to descend to the Large Intestine to provide Qi for the effort of defecation.",
},
"m0042_ct0075": {
title: "Convulsions after Childbirth",
code: "convulsions_after_childbirth",
overview: "Convulsions after Childbirth is characterized by rigidity of the spine, tremor of limbs, lockjaw and opisthotonos (a spasm in which the head and heels are bent backwards and the body bowed forward). If only the first two signs are present, the condition is considered not too severe; if there is also lockjaw and opisthotonos, the condition is serious; if, in addition, the woman sweats on the forehead, with the sweat being like beads, the limbs are cold and the breathing is inaudible, then the condition is dangerous.",
},
"m0042_ct0076": {
title: "Fever after Childbirth",
code: "fever_after_childbirth",
overview: "Fever after childbirth may be continuous but relatively low or sudden and high. Persistent fever of at least 38\u00b0C (100\u00b0F), which does not abate on its own and is accompanied by other symptoms and signs, may result from weakened Upright Qi, imbalance of Nutritive and Defensive Qi, Exterior pathogenic factors, or deficiency of Blood or Yin.",
},
"m0042_ct0077": {
title: "Hemorrhoids after Childbirth",
code: "4.08",
overview: "Hemorrhoids are varicose veins in the rectum wall. They are usually classified as first, second or third degree. First-degree hemorrhoids do not prolapse; second-degree ones prolapse on defecation but return into position spontaneously; third-degree ones remain prolapsed outside the anus. Hemorrhoids are due to congestion in the pelvic veins; this occurs frequently during pregnancy and after labor due to the pressure of the fetus on the pelvic veins and to the bearing-down efforts during labor. The development of constipation during pregnancy is also a contributory factor. The main symptoms of hemorrhoids are rectal discomfort or pain, anal itching and bleeding. In Chinese medicine, the pathology of hemorrhoids consists of Qi deficiency, Damp-Heat and Toxic-Heat. Deficient Qi fails to lift the organs and this may cause the sagging of veins in the rectum. Damp-Heat in the Large Intestine causes the pain and itching of the anus; Toxic-Heat causes more intense anal pain. When Heat invades the Blood, anal bleeding from the hemorrhoids occurs. Thus, the main treatment principles for hemorrhoids are to tonify and raise Qi, resolve Dampness, clear Heat, resolve Toxic-Heat and cool the Blood. The formulae used are distinguished according to internal or external hemorrhoids.",
},
"m0042_ct0078": {
title: "Joint Pain after Childbirth",
code: "joint_pain_after_childbirth",
overview: "Joint Pain after Childbirth includes pain, ache, soreness, numbness or feeling of heaviness in the joints, back or knees after childbirth. It pertains to the broad disease category of Painful Obstruction Syndrome but has specific characteristics and pathology when it occurs after childbirth. Its pathology may be of external origin, such as invasion of Wind, or internal origin, including Blood deficiency, Liver and Kidney deficiency, and Blood stasis.",
},
"m0042_ct0079": {
title: "Persistent Lochial discharge",
code: "persistent_lochial_discharge",
overview: "Persistent Lochial Discharge consists in a lochial discharge that goes on for longer than normal and continues to be red in colour rather than changing to a yellowish, serous discharge. Lochia refers to the bloody discharge coming from the placental site. The normal time of lochial discharge is about 3 weeks. The pathology of Persistent Lochial Discharge consists in three possible conditions: Qi deficiency, Blood stasis or Blood-Heat. When Qi is deficient, it fails to hold Blood and bleeding results: in this case, the blood discharged will be pale. When Blood stagnates, the blood vessels and the uterus are obstructed by stagnant Blood; as newly generated Blood has nowhere to go, it leaks out. In this case, the lochial discharge is dark and with clots. When Heat invades the Blood portion, it makes Blood reckless so that it pushes out of the blood vessels, causing bleeding: in this case, the lochial discharge will be bright red or dark red.",
},
"m0042_ct0080": {
title: "Post-Natal Depression",
code: "post_natal_depression",
overview: "The pathology of post-natal depression in Chinese medicine revolves around Blood: the exertion and loss of blood occurring at childbirth induce a state of Blood deficiency; since the Heart houses the Mind and governs Blood, Heart-Blood becomes deficient, the Mind has no residence and it becomes depressed and anxious. This causes a state of depression, mild anxiety, insomnia and fatigue: on a mental level the mother feels unable to cope, she is tearful, she loses any libido and she may feel angry or guilty. From Blood deficiency, other conditions may develop: after some time, and in women who have a predisposition to Yin deficiency, Blood deficiency may give rise to Yin deficiency and Empty-Heat. This would cause a more severe condition of depression with more intense anxiety, insomnia, mental restlessness and agitation. Conditions of neurotic, obsessive, phobic or psychotic behavior after childbirth are usually due to stagnant Blood harassing the Mind (rather than the more common Phlegm-Heat). In such cases, the woman is not only depressed but also confused, she may display obsessive behavior or phobias and, in extreme cases, she may manifest psychotic behavior. She may be aggressive and offensive, she may have hallucinations and delusions and she may display suicidal tendencies and even harbor destructive thoughts against her baby. Of course, every woman suffering from post-natal depression will present with pre-existing disharmonies which will play a role in the pathology of this condition. For example, Phlegm is an important contributory factor as it obstructs the Mind.",
},
"m0042_ct0081": {
title: "Retention of Lochia",
code: "retention_of_lochia",
overview: "Retention of lochia is characterized by the complete absence of lochial discharge or by a very scanty discharge, usually accompanied by abdominal pain. The pathology of the condition is always stasis of Blood. This may derive either from stagnation of Qi or from invasion of Cold in the Uterus. Thus, the etiology of the condition is either emotional problems leading to stagnation of Qi and stasis of Blood, or invasion of external cold during or after labor.",
},
"m0042_ct0082": {
title: "Spontaneous Flow of Milk",
code: "spontaneous_flow_of_milk",
overview: "This condition consists of a spontaneous flow of milk not elicited by the suckling of the baby; it is called in Chinese lou ru, which means \u2018trickling breast\u2019.",
},
"m0042_ct0083": {
title: "Sweating after Childbirth",
code: "sweating_after_childbirth",
overview: "The condition Sweating after Childbirth refers to either day-time or night-time sweating. After childbirth, Qi and Blood are deficient and skin pores are open. Sweating is likely to occur when eating or during sleep. It usually stops spontaneously in a few days. Profuse sweating that continues for a long time is pathological. Sweating after childbirth is one of the three acute conditions, called san ji, during the post-partum stage. Thus, it should be arrested as soon as possible in order to prevent collapse of Yin or collapse of Yang. The pathology of Sweating after Childbirth is always one of deficiency. Qi deficiency causes sweating in day-time and deficiency of Yin sweating at night. The type of fluids lost in day-time is different from that lost at night. In day-time sweating, it is the superficial fluids that circulate with the Defensive Qi in the space between the skin and muscles that leak out; in night-time sweating, the Yin essence from the Yin portion. Because these fluids come from the deep, Yin, energetic layers, this type of sweating is also called \u2018steaming from the bones.\u2019 Sweating is always taken seriously in Chinese medicine because it is a self-perpetuating pathological process. In fact, in day-time sweating the loss of fluids from the space between skin and muscles induces a deficiency of Qi because that is where Defensive Qi circulates. In night-time sweating, the fluids leaking from the Yin energetic layers represent a loss of precious Yin essences. Because of this, night-time sweat is supposed to taste sweet being composed of Yin essences, whereas day-time sweat tastes salty. The organs affected are mostly the Lungs and Kidneys: The Lungs are affected in day-time sweating as they govern Qi, control the Defensive Qi and the space between skin and muscles. In night-time sweating, the Lungs and/or the Kidneys are affected.",
},
"m0042_ct0084": {
title: "Urinary Difficulty after Childbirth",
code: "urinary_difficulty_after_childbirth",
overview: "Urinary Difficulty after Childbirth includes a range of urinary problems, from difficulty in urination and retention of urine, to their opposites, frequency of urination and incontinence of urine. They can be dealt with together because the cause is always a deficiency occurring after childbirth, and addressing the underlying deficiency cures the urinary problems. The mother\u2019s conditions included under this heading are urinary problems without fever or pain; thus, from a Western point of view, they are urinary problems without a urinary infection. The pathology of Urinary Difficulty after Childbirth, according to the traditional theory, is always one of deficiency and primarily of the Spleen or Kidneys. Deficient Spleen-Qi may cause sinking of the Qi of the Bladder and thus frequent urination or incontinence; or it may fail to transform and transport fluids so that urine is retained. Deficient Kidney-Qi fails to provide Qi to the Bladder for its function of Qi transformation, there is not enough Qi to hold the urine, and frequency and incontinence result. Alternatively, Kidney-Qi may be so deficient that there is no strength to push the urine out and retention of urine ensues. This type of Kidney-Qi deficiency always occurs against a background of Kidney-Yang deficiency.",
},
"m0042_ct0091": {
title: "Abdominal Masses",
code: "abdominal_masses",
overview: "In Traditional Chinese Medicine, abdominal masses are categorized as Zheng Jia. Zheng refers to fixed, hard masses with tangible form, primarily associated with Blood stasis and localized in the Yin organs. Jia refers to movable, intangible masses without fixed shape, characterized by pain that comes and goes, primarily associated with Qi stagnation and localized in the Yang organs. As for pathology, abdominal masses are always characterized by either stagnation of Qi or stasis of Blood, the former being non-substantial and the latter substantial masses. In addition to stagnation, there may also be Phlegm. However, in all cases of abdominal masses there is always an underlying deficiency of Qi. Deficient Qi fails to transport and transform and, leading to stagnation of Qi and Blood, it allows masses to form. Masses from stagnation of Qi come and go, are movable on palpation and change location. If there is pain, the pain has no fixed location and is accompanied by a pronounced feeling of distension. Masses from stasis of Blood are fixed in location, they are not movable on palpation and feel quite hard. If there is pain, it is fixed and stabbing in character. Masses from Phlegm feel soft on palpation and have a fixed location. There is usually no pain.",
},
"m0042_ct0092": {
title: "Breast Lumps",
code: "breast_lumps",
overview: "In Traditional Chinese Medicine, breast lumps are classified under the category of Ru Pi (Breast Mass/Nodule). The pathology primarily revolves around the Liver, Spleen, and Stomach meridians, alongside the Chong (Penetrating) and Ren (Conception) vessels. Anatomically in TCM, the breast tissue is governed by the Stomach meridian, while the nipple is governed by the Liver meridian. The core mechanism is the stagnation of Qi, which fails to move body fluids, leading to the coagulation of Phlegm. When Qi and Phlegm stagnate in the collateral channels of the breast over time, Blood stasis develops, forming palpable masses.",
},
"m0042_ct0093": {
title: "Endometriosis",
code: "endometriosis",
overview: "Endometriosis is a condition resulting from the presence of actively growing and functioning endometrial tissue in locations outside the uterus. The areas where endometriosis may occur are widespread and usually multiple. They include ovaries, uterine wall, fallopian tubes, abdominal scars, umbilicus, sigmoid colon, rectum, ureters, bladder, and vagina.",
},
"m0042_ct0094": {
title: "Excessive Vaginal Discharge",
code: "excessive_vaginal_discharge",
overview: "In Traditional Chinese Medicine, excessive vaginal discharge is classified as Dai Xia Bing (Disease of the Girdle Vessel). The pathology is centrally rooted in the dysfunction of the Dai (Girdle) and Ren (Conception) vessels. The Dai Mai binds all longitudinal meridians; when its restraining capacity is impaired, coupled with accumulated Dampness in the lower Jiao, pathological fluid leaks downward. The core pathogenic factor is always Dampness, whether generated internally through Zang-Fu organ dysfunction or invading from exogenous sources.",
},
"m0042_ct0095": {
title: "Genital Eczema",
code: "genital_eczema",
overview: "Genital eczema in women manifests with a red rash, vesicles or papules around the external genitalia. The vesicles or papules exude a fluid. This problem is due to the downward infusion of Damp-Heat in the genital area or to deficiency and dryness of the Blood.",
},
"m0042_ct0096": {
title: "Infertility",
code: "infertility",
overview: "Infertility Infertility is defined as the inability to produce offspring in a woman who has been trying for 2 years with a normal sexual life and, of course, the reproductive function of whose partner is normal. Infertility is frequently treated in China according to the four phases of the menstrual cycle, i.e. the period, the postmenstrual, the inter-menstrual and the pre-menstrual phases. The treatment principles in each phase are as follows: Period phase: regulate menstruation (i.e. stop bleeding if period is heavy or invigorate Blood if it is scanty). Post-menstrual phase: nourish Blood and tonify the Kidneys. Inter-menstrual phase: tonify the Kidneys and consolidate the Directing and Penetrating Vessels. If necessary, resolve Dampness or Phlegm. Pre-menstrual phase: tonify Yang and move Liver-Qi. If necessary, resolve Phlegm, invigorate Blood, expel Cold. Identification of Patterns and Treatment Empty Condition",
},
"m0042_ct0097": {
title: "Menopausal Syndrome",
code: "menopausal_syndrome",
overview: "Menopausal Syndrome \u2018Menopause\u2019 indicates the complete or permanent cessation of menstruation: an interval of 6-12 months is usually necessary to establish the diagnosis. \u2018Climacteric\u2019 indicates the phase in a woman\u2019s life during which she makes the transition from a reproductive to a non-reproductive stage: this transition is a period of declining ovarian function which usually spans 2-5 years around the menopause. Thus, when we refer to the discomfort and symptoms appearing during these years, it would be more appropriate to call them Climacteric Syndrome rather than Menopausal Syndrome. Menopause usually occurs between the ages of 48 and 55 and the median age in industrialized countries is about 51. Identification of Patterns and Treatment",
},
"m0042_ct0098": {
title: "Myoma",
code: "myoma",
overview: "Myomas (or \u2018fibroids\u2019) are very common benign uterine tumors in women. Uterine myomas are benign tumors that grow within the muscle tissue of the uterus. They are commonly called \u2018fibroids.\u2019 Between 20% and 50% of women of childbearing age have uterine myomas. While many women do not experience any problems, symptoms can be severe enough to require treatment. Myomas range in size from very small to larger than a melon. A very large uterine myoma can cause the uterus to expand to the size of a six- or seven-month pregnancy. There can either be one dominant myoma or a cluster of many small myomas. There are several types of myomas differentiated according to their location: Sub-serous myomas develop in the outer wall of the uterus and continue to grow outward. Intramural (or interstitial) myomas develop within the uterine wall and expand, making the uterus feel larger than normal. This is the most common type of myoma. Sub-mucous myomas develop just under the lining of the uterine cavity. These are the myomas that, more than others, tend to cause heavy menstrual bleeding and the ones that can cause problems with infertility and miscarriage.",
},
"m0042_ct0099": {
title: "Pcos",
code: "pcos",
overview: "Polycystic ovary syndrome (PCOS) is a common hormonal disorder that affects women during their reproductive years and beyond, into later stages of life. PCOS occurs when inappropriate hormonal signaling leads to higher-than-normal androgen levels and other hormonal imbalances. As a result, women with PCOS may experience irregular or infrequent menstrual periods, pain - including pain with heavy menstrual bleeding, abnormal ovulation, changes in hair (either excessive facial or body hair or female-pattern baldness), oilier skin, acne and/or cysts in the ovaries. PCOS is a leading cause of irregular menstrual periods and one of the most common causes of infertility. Irregular or infrequent menstrual periods among women with PCOS may also raise their risk for endometrial hyperplasia and/or endometrial cancer. PCOS can start as early as during adolescence but is most commonly detected or diagnosed when women struggle to become pregnant. Further, PCOS is a chronic metabolic condition associated with heightened long-term risk for insulin resistance, type 2 diabetes mellitus and obesity. There is currently no cure for PCOS, but lifestyle changes, medications and fertility treatments can reduce symptoms, increase fertility rates and protect longer-term health. Identification of Patterns and Treatment",
},
"m0042_ct0100": {
title: "Prolapse of the Uterus",
code: "prolapse_of_the_uterus",
overview: "In Traditional Chinese Medicine, uterine prolapse is classified under the category of Yin Ting (Prolapse of the Uterus / Vaginal Prolapse). The pathology is fundamentally viewed as a failure of the body's lifting and holding mechanisms, governed primarily by the Spleen and the Kidneys. When the supportive structural integrity of the Chong (Penetrating), Ren (Conception), and Dai (Girdle) vessels weakens, the uterus loses its suspension and descends.",
},
"m0042_ct0101": {
title: "Vaginal Itching",
code: "vaginal_itching",
overview: "In Traditional Chinese Medicine, vaginal and vulvar itching is classified as Yin Yang (Itching of the Genitals). The pathology is intimately connected to the Liver meridian, which anatomically curves around the external genitalia. Consequently, systemic imbalances affecting the Liver network readily manifest as localized symptoms in the vulvovaginal region. The core mechanisms involve either the downward pouring of pathogenic excess (Damp-Heat) or a lack of nourishment causing internal Wind (Yin and Blood deficiency).",
},
"m0042_ct0102": {
title: "Vulvar Sores",
code: "vulvar_sores",
overview: "Vulvar Sores\u2019, called Yin Chuang in Chinese medicine, may manifest with vulvar swelling, pain, itching, erosion, lumps, discharge of pus and excessive vaginal discharge. These local manifestations may be accompanied by systemic symptoms and signs such as shivers, fever, lassitude, abdominal distension, dark urine, thirst, constipation, a Slippery or Wiry and Rapid pulse and a Red tongue with a thick, sticky yellow coating. This Chinese disease category may correspond to various diseases of the genitalia such as vulvitis, vaginitis, boils or ulcers of the external genitalia, inflammation of the Bartholin\u2019s glands, cancer of the external genitalia or genital herpes.",
},
"abdominal_pain_after_childbirth": {
title: "Abdominal Pain after childbirth",
code: "abdominal_pain_after_childbirth",
overview: "The pathology of Abdominal Pain after Childbirth is, as always, characterized by either a deficiency or an excess condition. The Golden Mirror of Medicine says: \u201cPost-partum abdominal pain is caused by deficiency of Blood if there is heavy loss of blood; by stasis of Blood if lochia are retained; by retention of Food if there is poor appetite, distension and fullness; and by invasion of Cold if pain is accompanied by a cold feeling.\u201d Deficient Blood and Qi may cause abdominal pain of a deficient nature, i.e. quite mild, better with pressure and better after eating. Causes which are excess in nature include stagnation of Qi, stasis of Blood and retention of food: these cause a Full type of pain which is more intense, with a feeling of distension in the case of Qi stagnation and fixed, stabbing in the case of Blood stasis. Full-type pain is worse with pressure and worse after eating. It is also possible to have a mixed deficiency/excess condition since when Qi and Blood are deficient, they fail to move Blood properly and hence some stasis of Blood ensues. The Complete Works of Jing Yue says: \u201cDeficiency and Excess should be differentiated in the treatment of post-partum abdominal pain. Pain from stasis of Blood is of the Excess type, while that due to deficiency of Blood is of the Deficient type. Pain accompanied by a feeling of distension or a sensation as if a stream of air was rushing upwards to the chest and hypochondrium, aggravated by pressure, is of the Excess type. To treat it, one must move Qi and disperse. Pain without distension or fullness and alleviated by pressure, warmth or eating, is of the Deficient type. One should not use herbs that expel pathogenic factors.\u201d When a woman has abdominal pain after childbirth, any question of infection must first be excluded. From a Chinese perspective, abdominal pain from infection would be accompanied by shivering, fever that rises continuously and discharge of lochia with a smell like rancid soya sauce.",
},
"breast_milk_not_flowing": {
title: "Breast Milk not Flowing",
code: "breast_milk_not_flowing",
overview: "This condition consists of scanty or absent breast milk after childbirth. The term \u2018Breast Milk not Flowing\u2019 is used in place of \u2018Insufficient Lactation\u2019 or \u2018Agalactia\u2019 because these two terms imply a deficiency, a lack of a vital substance; lack of breast milk, however, may be due not only to a deficiency of milk but also to an obstruction or stagnation that prevents the flow of milk.",
},
"collapse_after_childbirth": {
title: "Collapse after Childbirth",
code: "collapse_after_childbirth",
overview: "Collapse after Childbirth indicates a condition characterized by severe dizziness with a sudden onset. The woman cannot stand or sit, she has blurred vision and a feeling of tightness of the chest, she suffers nausea and vomiting and, in extreme cases, may faint.",
},
"constipation_after_childbirth": {
title: "Constipation after Childbirth",
code: "constipation_after_childbirth",
overview: "Constipation after Childbirth refers to difficult, dry or very infrequent defecation. Constipation occurring after childbirth in a woman who previously had regular bowel movements is usually due to Blood deficiency and dryness following excessive blood loss during labor. When Blood and fluids are exhausted, the Large Intestine is affected and deficiency of fluids in this organ makes the passage of stools difficult. A state of dryness may also occur as a result of profuse spontaneous sweating after childbirth, but this is rare. Apart from the Large Intestine, the pathology of constipation after childbirth is also related to the Liver when deficient Liver-Blood fails to moisten the faces, and to the Lungs when deficient Lung-Qi fails to descend to the Large Intestine to provide Qi for the effort of defecation.",
},
"convulsions_after_childbirth": {
title: "Convulsions after Childbirth",
code: "convulsions_after_childbirth",
overview: "Convulsions after Childbirth is characterized by rigidity of the spine, tremor of limbs, lockjaw and opisthotonos (a spasm in which the head and heels are bent backwards and the body bowed forward). If only the first two signs are present, the condition is considered not too severe; if there is also lockjaw and opisthotonos, the condition is serious; if, in addition, the woman sweats on the forehead, with the sweat being like beads, the limbs are cold and the breathing is inaudible, then the condition is dangerous.",
},
"fever_after_childbirth": {
title: "Fever after Childbirth",
code: "fever_after_childbirth",
overview: "Fever after childbirth may be continuous but relatively low or sudden and high. Persistent fever of at least 38\u00b0C (100\u00b0F), which does not abate on its own and is accompanied by other symptoms and signs, may result from weakened Upright Qi, imbalance of Nutritive and Defensive Qi, Exterior pathogenic factors, or deficiency of Blood or Yin.",
},
"hemorrhoids_after_childbirth": {
title: "Hemorrhoids after Childbirth",
code: "hemorrhoids_after_childbirth",
overview: "Hemorrhoids are varicose veins in the rectum wall. They are usually classified as first, second or third degree. First-degree hemorrhoids do not prolapse; second-degree ones prolapse on defecation but return into position spontaneously; third-degree ones remain prolapsed outside the anus. Hemorrhoids are due to congestion in the pelvic veins; this occurs frequently during pregnancy and after labor due to the pressure of the fetus on the pelvic veins and to the bearing-down efforts during labor. The development of constipation during pregnancy is also a contributory factor.\n\nThe main symptoms of hemorrhoids are rectal discomfort or pain, anal itching and bleeding. In Chinese medicine, the pathology of hemorrhoids consists of Qi deficiency, Damp-Heat and Toxic-Heat. Deficient Qi fails to lift the organs and this may cause the sagging of veins in the rectum. Damp-Heat in the Large Intestine causes the pain and itching of the anus; Toxic-Heat causes more intense anal pain. When Heat invades the Blood, anal bleeding from the hemorrhoids occurs.\n\nThus, the main treatment principles for hemorrhoids are to tonify and raise Qi, resolve Dampness, clear Heat, resolve Toxic-Heat and cool the Blood. The formulae used are distinguished according to internal or external hemorrhoids.",
},
"joint_pain_after_childbirth": {
title: "Joint Pain after Childbirth",
code: "joint_pain_after_childbirth",
overview: "Joint Pain after Childbirth includes pain, ache, soreness, numbness or feeling of heaviness in the joints, back or knees after childbirth. It pertains to the broad disease category of Painful Obstruction Syndrome but has specific characteristics and pathology when it occurs after childbirth. Its pathology may be of external origin, such as invasion of Wind, or internal origin, including Blood deficiency, Liver and Kidney deficiency, and Blood stasis.",
},
"persistent_lochial_discharge": {
title: "Persistent Lochial discharge",
code: "persistent_lochial_discharge",
overview: "Persistent Lochial Discharge consists in a lochial discharge that goes on for longer than normal and continues to be red in colour rather than changing to a yellowish, serous discharge. Lochia refers to the bloody discharge coming from the placental site. The normal time of lochial discharge is about 3 weeks. The pathology of Persistent Lochial Discharge consists in three possible conditions: Qi deficiency, Blood stasis or Blood-Heat. When Qi is deficient, it fails to hold Blood and bleeding results: in this case, the blood discharged will be pale. When Blood stagnates, the blood vessels and the uterus are obstructed by stagnant Blood; as newly generated Blood has nowhere to go, it leaks out. In this case, the lochial discharge is dark and with clots. When Heat invades the Blood portion, it makes Blood reckless so that it pushes out of the blood vessels, causing bleeding: in this case, the lochial discharge will be bright red or dark red.",
},
"post_natal_depression": {
title: "Post-Natal Depression",
code: "post_natal_depression",
overview: "The pathology of post-natal depression in Chinese medicine revolves around Blood: the exertion and loss of blood occurring at childbirth induce a state of Blood deficiency; since the Heart houses the Mind and governs Blood, Heart-Blood becomes deficient, the Mind has no residence and it becomes depressed and anxious. This causes a state of depression, mild anxiety, insomnia and fatigue: on a mental level the mother feels unable to cope, she is tearful, she loses any libido and she may feel angry or guilty. From Blood deficiency, other conditions may develop: after some time, and in women who have a predisposition to Yin deficiency, Blood deficiency may give rise to Yin deficiency and Empty-Heat. This would cause a more severe condition of depression with more intense anxiety, insomnia, mental restlessness and agitation. Conditions of neurotic, obsessive, phobic or psychotic behavior after childbirth are usually due to stagnant Blood harassing the Mind (rather than the more common Phlegm-Heat). In such cases, the woman is not only depressed but also confused, she may display obsessive behavior or phobias and, in extreme cases, she may manifest psychotic behavior. She may be aggressive and offensive, she may have hallucinations and delusions and she may display suicidal tendencies and even harbor destructive thoughts against her baby. Of course, every woman suffering from post-natal depression will present with pre-existing disharmonies which will play a role in the pathology of this condition. For example, Phlegm is an important contributory factor as it obstructs the Mind.",
},
"retention_of_lochia": {
title: "Retention of Lochia",
code: "retention_of_lochia",
overview: "Retention of lochia is characterized by the complete absence of lochial discharge or by a very scanty discharge, usually accompanied by abdominal pain. The pathology of the condition is always stasis of Blood. This may derive either from stagnation of Qi or from invasion of Cold in the Uterus. Thus, the etiology of the condition is either emotional problems leading to stagnation of Qi and stasis of Blood, or invasion of external cold during or after labor.",
},
"spontaneous_flow_of_milk": {
title: "Spontaneous Flow of Milk",
code: "spontaneous_flow_of_milk",
overview: "This condition consists of a spontaneous flow of milk not elicited by the suckling of the baby; it is called in Chinese lou ru, which means \u2018trickling breast\u2019.",
},
"sweating_after_childbirth": {
title: "Sweating after Childbirth",
code: "sweating_after_childbirth",
overview: "The condition Sweating after Childbirth refers to either day-time or night-time sweating. After childbirth, Qi and Blood are deficient and skin pores are open. Sweating is likely to occur when eating or during sleep. It usually stops spontaneously in a few days. Profuse sweating that continues for a long time is pathological. Sweating after childbirth is one of the three acute conditions, called san ji, during the post-partum stage. Thus, it should be arrested as soon as possible in order to prevent collapse of Yin or collapse of Yang. The pathology of Sweating after Childbirth is always one of deficiency. Qi deficiency causes sweating in day-time and deficiency of Yin sweating at night. The type of fluids lost in day-time is different from that lost at night. In day-time sweating, it is the superficial fluids that circulate with the Defensive Qi in the space between the skin and muscles that leak out; in night-time sweating, the Yin essence from the Yin portion. Because these fluids come from the deep, Yin, energetic layers, this type of sweating is also called \u2018steaming from the bones.\u2019 Sweating is always taken seriously in Chinese medicine because it is a self-perpetuating pathological process. In fact, in day-time sweating the loss of fluids from the space between skin and muscles induces a deficiency of Qi because that is where Defensive Qi circulates. In night-time sweating, the fluids leaking from the Yin energetic layers represent a loss of precious Yin essences. Because of this, night-time sweat is supposed to taste sweet being composed of Yin essences, whereas day-time sweat tastes salty. The organs affected are mostly the Lungs and Kidneys: The Lungs are affected in day-time sweating as they govern Qi, control the Defensive Qi and the space between skin and muscles. In night-time sweating, the Lungs and/or the Kidneys are affected.",
},
"urinary_difficulty_after_childbirth": {
title: "Urinary Difficulty after Childbirth",
code: "urinary_difficulty_after_childbirth",
overview: "Urinary Difficulty after Childbirth includes a range of urinary problems, from difficulty in urination and retention of urine, to their opposites, frequency of urination and incontinence of urine. They can be dealt with together because the cause is always a deficiency occurring after childbirth, and addressing the underlying deficiency cures the urinary problems. The mother\u2019s conditions included under this heading are urinary problems without fever or pain; thus, from a Western point of view, they are urinary problems without a urinary infection. The pathology of Urinary Difficulty after Childbirth, according to the traditional theory, is always one of deficiency and primarily of the Spleen or Kidneys. Deficient Spleen-Qi may cause sinking of the Qi of the Bladder and thus frequent urination or incontinence; or it may fail to transform and transport fluids so that urine is retained. Deficient Kidney-Qi fails to provide Qi to the Bladder for its function of Qi transformation, there is not enough Qi to hold the urine, and frequency and incontinence result. Alternatively, Kidney-Qi may be so deficient that there is no strength to push the urine out and retention of urine ensues. This type of Kidney-Qi deficiency always occurs against a background of Kidney-Yang deficiency.",
},
"abdominal_masses": {
title: "Abdominal Masses",
code: "abdominal_masses",
overview: "In Traditional Chinese Medicine, abdominal masses are categorized as Zheng Jia. Zheng refers to fixed, hard masses with tangible form, primarily associated with Blood stasis and localized in the Yin organs. Jia refers to movable, intangible masses without fixed shape, characterized by pain that comes and goes, primarily associated with Qi stagnation and localized in the Yang organs. As for pathology, abdominal masses are always characterized by either stagnation of Qi or stasis of Blood, the former being non-substantial and the latter substantial masses. In addition to stagnation, there may also be Phlegm. However, in all cases of abdominal masses there is always an underlying deficiency of Qi. Deficient Qi fails to transport and transform and, leading to stagnation of Qi and Blood, it allows masses to form. Masses from stagnation of Qi come and go, are movable on palpation and change location. If there is pain, the pain has no fixed location and is accompanied by a pronounced feeling of distension. Masses from stasis of Blood are fixed in location, they are not movable on palpation and feel quite hard. If there is pain, it is fixed and stabbing in character. Masses from Phlegm feel soft on palpation and have a fixed location. There is usually no pain.",
},
"breast_lumps": {
title: "Breast Lumps",
code: "breast_lumps",
overview: "In Traditional Chinese Medicine, breast lumps are classified under the category of Ru Pi (Breast Mass/Nodule). The pathology primarily revolves around the Liver, Spleen, and Stomach meridians, alongside the Chong (Penetrating) and Ren (Conception) vessels. Anatomically in TCM, the breast tissue is governed by the Stomach meridian, while the nipple is governed by the Liver meridian. The core mechanism is the stagnation of Qi, which fails to move body fluids, leading to the coagulation of Phlegm. When Qi and Phlegm stagnate in the collateral channels of the breast over time, Blood stasis develops, forming palpable masses.",
},
"endometriosis": {
title: "Endometriosis",
code: "endometriosis",
overview: "Endometriosis is a condition resulting from the presence of actively growing and functioning endometrial tissue in locations outside the uterus. The areas where endometriosis may occur are widespread and usually multiple. They include ovaries, uterine wall, fallopian tubes, abdominal scars, umbilicus, sigmoid colon, rectum, ureters, bladder, and vagina.",
},
"excessive_vaginal_discharge": {
title: "Excessive Vaginal Discharge",
code: "excessive_vaginal_discharge",
overview: "In Traditional Chinese Medicine, excessive vaginal discharge is classified as Dai Xia Bing (Disease of the Girdle Vessel). The pathology is centrally rooted in the dysfunction of the Dai (Girdle) and Ren (Conception) vessels. The Dai Mai binds all longitudinal meridians; when its restraining capacity is impaired, coupled with accumulated Dampness in the lower Jiao, pathological fluid leaks downward. The core pathogenic factor is always Dampness, whether generated internally through Zang-Fu organ dysfunction or invading from exogenous sources.",
},
"genital_eczema": {
title: "Genital Eczema",
code: "genital_eczema",
overview: "Genital eczema in women manifests with a red rash, vesicles or papules around the external genitalia. The vesicles or papules exude a fluid. This problem is due to the downward infusion of Damp-Heat in the genital area or to deficiency and dryness of the Blood.",
},
"infertility": {
title: "Infertility",
code: "infertility",
overview: "Infertility is defined as the inability to produce offspring in a woman who has been trying for 2 years with a normal sexual life and, of course, the reproductive function of whose partner is normal. Infertility is frequently treated in China according to the four phases of the menstrual cycle, i.e. the period, the postmenstrual, the inter-menstrual and the pre-menstrual phases. The treatment principles in each phase are as follows: Period phase: regulate menstruation (i.e. stop bleeding if period is heavy or invigorate Blood if it is scanty). Post-menstrual phase: nourish Blood and tonify the Kidneys. Inter-menstrual phase: tonify the Kidneys and consolidate the Directing and Penetrating Vessels. If necessary, resolve Dampness or Phlegm. Pre-menstrual phase: tonify Yang and move Liver-Qi. If necessary, resolve Phlegm, invigorate Blood, expel Cold.",
},
"menopausal_syndrome": {
title: "Menopausal Syndrome",
code: "menopausal_syndrome",
overview: "Menopausal Syndrome indicates the complete or permanent cessation of menstruation: an interval of 6-12 months is usually necessary to establish the diagnosis. The term \u2018climacteric\u2019 is used by gynecologists to indicate the phase in a woman\u2019s life during which she passes from the reproductive to the non-reproductive stage. This phase may last many years: 10, 15, or even 20. The symptoms of menopause may occur before, during, or after the permanent cessation of menstruation. Strictly speaking, since many symptoms occur during the climacteric years and not only when periods stop, it would be more appropriate to call them Climacteric Syndrome rather than Menopausal Syndrome. Menopause usually occurs between the ages of 48 and 55 and the median age in industrialized countries is about 51.",
},
"myoma": {
title: "Myoma",
code: "myoma",
overview: "Myomas (or \u2018fibroids\u2019) are very common benign uterine tumors in women that grow within the muscle tissue of the uterus. Between 20% and 50% of women of childbearing age have uterine myomas. While many women do not experience any problems, symptoms can be severe enough to require treatment. Myomas range in size from very small to larger than a melon. A very large uterine myoma can cause the uterus to expand to the size of a six- or seven-month pregnancy. There can either be one dominant myoma or a cluster of many small myomas. Sub-serous myomas develop in the outer wall of the uterus and continue to grow outward. Intramural (or interstitial) myomas develop within the uterine wall and expand, making the uterus feel larger than normal. Sub-mucous myomas develop just under the lining of the uterine cavity, often causing heavy menstrual bleeding, infertility, and miscarriage.",
},
"pcos": {
title: "PCOS",
code: "pcos",
overview: "Polycystic ovary syndrome (PCOS) is a common hormonal disorder that affects women during their reproductive years and beyond. PCOS occurs when inappropriate hormonal signaling leads to higher-than-normal androgen levels and other hormonal imbalances. As a result, women with PCOS may experience irregular or infrequent menstrual periods, pain - including pain with heavy menstrual bleeding, abnormal ovulation, changes in hair, oilier skin, acne and/or cysts in the ovaries. PCOS is a leading cause of irregular menstrual periods and one of the most common causes of infertility. Further, PCOS is a chronic metabolic condition associated with heightened long-term risk for insulin resistance, type 2 diabetes mellitus and obesity.",
},
"prolapse_of_the_uterus": {
title: "Prolapse of the Uterus",
code: "prolapse_of_the_uterus",
overview: "In Traditional Chinese Medicine, uterine prolapse is classified under the category of Yin Ting (Prolapse of the Uterus / Vaginal Prolapse). The pathology is fundamentally viewed as a failure of the body's lifting and holding mechanisms, governed primarily by the Spleen and the Kidneys. When the supportive structural integrity of the Chong (Penetrating), Ren (Conception), and Dai (Girdle) vessels weakens, the uterus loses its suspension and descends.",
},
"prolapse_of_uterus": {
title: "Prolapse of the Uterus",
code: "prolapse_of_uterus",
overview: "In Traditional Chinese Medicine, uterine prolapse is classified under the category of Yin Ting (Prolapse of the Uterus / Vaginal Prolapse). The pathology is fundamentally viewed as a failure of the body's lifting and holding mechanisms, governed primarily by the Spleen and the Kidneys. When the supportive structural integrity of the Chong (Penetrating), Ren (Conception), and Dai (Girdle) vessels weakens, the uterus loses its suspension and descends.",
},
"vaginal_itching": {
title: "Vaginal Itching",
code: "vaginal_itching",
overview: "In Traditional Chinese Medicine, vaginal and vulvar itching is classified as Yin Yang (Itching of the Genitals). The pathology is intimately connected to the Liver meridian, which anatomically curves around the external genitalia. Systemic imbalances affecting the Liver network readily manifest as localized symptoms in the vulvovaginal region. The core mechanisms involve either the downward pouring of pathogenic excess (Damp-Heat) or a lack of nourishment causing internal Wind (Yin and Blood deficiency).",
},
"vulvar_sores": {
title: "Vulvar Sores",
code: "vulvar_sores",
overview: "Vulvar Sores, called Yin Chuang in Chinese medicine, may manifest with vulvar swelling, pain, itching, erosion, lumps, discharge of pus and excessive vaginal discharge. These local manifestations may be accompanied by systemic symptoms such as shivers, fever, lassitude, abdominal distension, dark urine, thirst, constipation, and a Red tongue with a thick, sticky yellow coating. This Chinese disease category may correspond to various diseases of the genitalia such as vulvitis, vaginitis, boils or ulcers of the external genitalia, inflammation of the Bartholin\u2019s glands, or genital herpes.",
},
};
export function findGynecologyDiseaseInfo(
templateCode?: string | null,
itemCodeOrName?: string | null,
): GynecologyDiseaseInfo | null {
if (templateCode) {
const normalized = templateCode.trim().toLowerCase();
if (GYNECOLOGY_DISEASE_DATA[normalized]) {
return GYNECOLOGY_DISEASE_DATA[normalized];
}
}
if (itemCodeOrName) {
const target = itemCodeOrName.trim().toLowerCase();
for (const info of Object.values(GYNECOLOGY_DISEASE_DATA)) {
if (info.code && target.startsWith(info.code.toLowerCase())) {
return info;
}
if (target.includes(info.title.toLowerCase())) {
return info;
}
}
}
return null;
}
export interface GynecologyDiseaseCollectionRendererProps extends CollectionRendererProps {
templateCode?: string;
}
export function GynecologyDiseaseCollectionRenderer(
props: GynecologyDiseaseCollectionRendererProps,
) {
const firstItem = props.items[0];
const itemCode = firstItem
? asString(firstItem.attributes?.code) || asString(firstItem.slug)
: null;
const diseaseInfo = useMemo(() => {
return findGynecologyDiseaseInfo(props.templateCode, itemCode);
}, [props.templateCode, itemCode]);
const title = diseaseInfo?.title
? humanizeKey(diseaseInfo.title)
: firstItem
? humanizeKey(asString(firstItem.attributes?.name) || firstItem.title)
: "Patterns";
const overviewText = useMemo(() => {
if (diseaseInfo?.overview) return diseaseInfo.overview;
for (const item of props.items) {
const defn =
asString(item.attributes?.definition) ||
asString(item.attributes?.description) ||
asString(item.attributes?.overview);
if (defn) return defn;
}
return "";
}, [diseaseInfo?.overview, props.items]);
const paragraphs = useMemo(() => {
if (!overviewText) return [];
return overviewText
.split(/\n{2,}|\r\n\r\n/)
.map((p) => p.trim())
.filter(Boolean);
}, [overviewText]);
const totalCount = props.total || props.items.length;
const countSubtitle = totalCount
? `${totalCount} ${totalCount === 1 ? "Pattern" : "Patterns"}`
: undefined;
const header = (
<View style={styles.overviewContainer}>
<Hero
title={title}
subtitle={countSubtitle}
tone="green"
/>
{paragraphs.length > 0 ? (
<OverviewCard
paragraphs={paragraphs}
style={{ marginTop: verticalScale(12) }}
/>
) : null}
</View>
);
return (
<CollectionScaffold
{...props}
header={header}
countLabel="Identifications of patterns"
/>
);
}
export function createGynecologyDiseaseCollectionRenderer(templateCode: string) {
return function GynecologySpecificCollectionRenderer(
props: CollectionRendererProps,
) {
return (
<GynecologyDiseaseCollectionRenderer
{...props}
templateCode={templateCode}
/>
);
};
}
const styles = StyleSheet.create({
overviewContainer: {
marginBottom: verticalScale(14),
},
});

View File

@ -1,45 +1,12 @@
import React, { useMemo } from "react"; import React from "react";
import { Pressable, Text, View } from "react-native"; import { Pressable, Text, View } from "react-native";
import { asNumber, asString, asStringArray } from "../helpers/value"; import { asNumber, asString, asStringArray } from "../helpers/value";
import { CollectionScaffold } from "../shared/CollectionScaffold"; import { CollectionScaffold } from "../shared/CollectionScaffold";
import { StandardIndexCard } from "../shared/StandardIndexCard"; import { StandardIndexCard } from "../shared/StandardIndexCard";
import type { import type { CollectionItemRendererProps, CollectionRendererProps } from "../../types/renderer.types";
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) { export function MeridianIndexCollectionRenderer(props: CollectionRendererProps) {
const sortedItems = useMemo( return <CollectionScaffold {...props} />;
() => sortWithExtraPointsAfterDu(props.items),
[props.items],
);
return <CollectionScaffold {...props} items={sortedItems} />;
} }
export function MeridianCollectionRenderer(props: CollectionRendererProps) { export function MeridianCollectionRenderer(props: CollectionRendererProps) {
return <CollectionScaffold {...props} />; return <CollectionScaffold {...props} />;
@ -50,7 +17,6 @@ export function MeridianIndexCardRenderer({ item, onPress }: CollectionItemRende
<StandardIndexCard <StandardIndexCard
title={asString(a.name) || item.title} title={asString(a.name) || item.title}
count={asNumber(a.content_count)} count={asNumber(a.content_count)}
countLabel={asString(a.content_label) || null}
onPress={onPress} onPress={onPress}
/> />
); );

View File

@ -1,393 +1,30 @@
import React, { useMemo, useState } from "react"; import React from "react";
import { import { Pressable, StyleSheet, Text, View } from "react-native";
ActivityIndicator,
LayoutAnimation,
Platform,
Pressable,
StyleSheet,
Text,
UIManager,
View,
} from "react-native";
import { Ionicons } from "@expo/vector-icons"; import { Ionicons } from "@expo/vector-icons";
import { useRouter } from "expo-router";
import { moderateScale, verticalScale } from "react-native-size-matters"; import { moderateScale, verticalScale } from "react-native-size-matters";
import { Colors } from "@/theme"; import { Colors } from "@/theme";
import { import { asNumber, asString } from "../helpers/value";
asNumber,
asString,
asStringArray,
buildDefinitionLabelMap,
humanizeKey,
resolveAttributeLabel,
} from "../helpers/value";
import { CollectionScaffold } from "../shared/CollectionScaffold"; import { CollectionScaffold } from "../shared/CollectionScaffold";
import { ContentCountBadge } from "../shared/ContentCountBadge"; import { ContentCountBadge } from "../shared/ContentCountBadge";
import { greenTone } from "../shared/reading-palette";
import {
useModuleContentDetailQuery,
useModuleTemplateContentDetailsQuery,
useTemplateDefinitionsQuery,
} from "../../hooks/use-content-queries";
import type { import type {
CollectionItemRendererProps, CollectionItemRendererProps,
CollectionRendererProps, CollectionRendererProps,
} from "../../types/renderer.types"; } from "../../types/renderer.types";
if (Platform.OS === "android" && UIManager.setLayoutAnimationEnabledExperimental) {
UIManager.setLayoutAnimationEnabledExperimental(true);
}
export function ModuleCatalogCollectionRenderer(props: CollectionRendererProps) { export function ModuleCatalogCollectionRenderer(props: CollectionRendererProps) {
return <CollectionScaffold {...props} />; return <CollectionScaffold {...props} />;
} }
function stripTrailingPeriod(value: string): string {
return value.replace(/\s*\.+\s*$/, "").trim();
}
function normalizePointCode(raw: string): string {
let code = raw.replace(/\s*\([^)]*\)/g, "").trim().toLowerCase();
code = code.replace(/^ren-/, "cv-");
code = code.replace(/^rn-/, "cv-");
code = code.replace(/^du-/, "gv-");
code = code.replace(/^sj-/, "te-");
code = code.replace(/^tb-/, "te-");
code = code.replace(/^liv-/, "lr-");
code = code.replace(/^ub-/, "bl-");
return code;
}
export function PatternAccordionCardRenderer({
item,
}: CollectionItemRendererProps) {
const router = useRouter();
const [expanded, setExpanded] = useState(false);
const attributes = item.attributes;
const rawTitle =
asString(attributes.food_name) ||
asString(attributes.name) ||
item.title;
const title = humanizeKey(rawTitle);
const link = attributes?.link as Record<string, unknown> | undefined;
const linkTarget = link?.target as Record<string, unknown> | undefined;
const contentId = (linkTarget?.content_id as string) || item.id;
const moduleCode = (linkTarget?.module_code as string) || "m0042";
const detailQuery = useModuleContentDetailQuery(
{ module_code: moduleCode },
contentId,
);
const detailTemplateCode =
asString(linkTarget?.template_code) ||
asString(detailQuery.data?.content?.metadata?.template_code) ||
(moduleCode.toLowerCase() === "m0042" ? "m0042_ct0005" : "");
const templateDefsQuery = useTemplateDefinitionsQuery(detailTemplateCode || undefined);
const labelMap = useMemo(
() => buildDefinitionLabelMap(templateDefsQuery.data?.attributes),
[templateDefsQuery.data?.attributes],
);
// Query all acupuncture points from m0001 to resolve links
const { data: pointsData } = useModuleTemplateContentDetailsQuery({
module_code: "m0001",
template_code: "m0001_ct0003",
});
const pointsMap = useMemo(() => {
const map = new Map<string, string>();
if (!pointsData?.items) return map;
for (const pItem of pointsData.items) {
const id = pItem.content.id;
const code = asString(pItem.data.code) || asString(pItem.data.name);
if (code) {
const lower = code.toLowerCase().trim();
map.set(lower, id);
if (lower.startsWith("cv-")) {
map.set(lower.replace("cv-", "ren-"), id);
map.set(lower.replace("cv-", "rn-"), id);
}
if (lower.startsWith("gv-")) {
map.set(lower.replace("gv-", "du-"), id);
}
if (lower.startsWith("te-")) {
map.set(lower.replace("te-", "sj-"), id);
map.set(lower.replace("te-", "tb-"), id);
}
if (lower.startsWith("lr-")) {
map.set(lower.replace("lr-", "liv-"), id);
}
if (lower.startsWith("bl-")) {
map.set(lower.replace("bl-", "ub-"), id);
}
}
if (pItem.content.title) {
map.set(pItem.content.title.toLowerCase().trim(), id);
}
}
return map;
}, [pointsData?.items]);
const handlePointPress = (rawPt: string) => {
const match = rawPt.match(/([A-Za-z]{1,4}-\d{1,2})/);
const pointCode = match ? match[1] : rawPt.trim();
const normalized = normalizePointCode(pointCode);
const pointContentId = pointsMap.get(normalized);
if (pointContentId) {
router.push(`/modules/m0001/m0001_ct0003/${encodeURIComponent(pointContentId)}` as never);
} else {
router.push(`/modules/m0001/search?q=${encodeURIComponent(pointCode)}` as never);
}
};
const toggle = () => {
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
setExpanded((prev) => !prev);
};
const detailData = (detailQuery.data?.data as Record<string, unknown> | undefined) || attributes;
// Extract fields matching the user's diagram
const rawManifestations = detailData.clinical_manifestations;
const clinicalManifestations: string[] = Array.isArray(rawManifestations)
? (rawManifestations as string[]).map(String)
: typeof rawManifestations === "string" && rawManifestations.trim()
? rawManifestations.split("\n").map((s) => s.trim()).filter(Boolean)
: [];
const tongue = stripTrailingPeriod(asString(detailData.tongue));
const pulse = stripTrailingPeriod(asString(detailData.pulse));
const rawPrinciples = detailData.treatment_principle;
const treatmentPrinciples: string[] = Array.isArray(rawPrinciples)
? (rawPrinciples as string[]).map(String).map((s) => s.trim()).filter(Boolean)
: typeof rawPrinciples === "string" && rawPrinciples.trim()
? rawPrinciples
.split(/[,;\n]/)
.map((s) => s.trim().replace(/^[-*•]\s*/, ""))
.filter(Boolean)
: [];
const rawAcupuncture = detailData.acupuncture;
let acuPoints = "";
let acuMethod = "";
if (rawAcupuncture && typeof rawAcupuncture === "object") {
const acuObj = rawAcupuncture as Record<string, unknown>;
acuPoints = asString(acuObj.points);
acuMethod = asString(acuObj.method);
} else if (typeof rawAcupuncture === "string") {
acuPoints = rawAcupuncture;
}
const rawExplanation = detailData.explanation;
const explanations: string[] = Array.isArray(rawExplanation)
? (rawExplanation as string[]).map(String)
: typeof rawExplanation === "string" && rawExplanation.trim()
? rawExplanation.split("\n").map((s) => s.trim()).filter(Boolean)
: [];
const category = asString(detailData.category);
// Split points by comma into chips
const pointChips = acuPoints
? acuPoints.split(/,\s*/).map((p) => p.trim()).filter(Boolean)
: [];
return (
<View style={accordionStyles.cardContainer}>
<Pressable
accessibilityRole="button"
accessibilityLabel={`${expanded ? "Collapse" : "Expand"} ${title}`}
onPress={toggle}
style={({ pressed }) => [
accordionStyles.headerRow,
expanded && accordionStyles.headerRowExpanded,
pressed && accordionStyles.pressed,
]}
>
<View style={[accordionStyles.accentBar, expanded && accordionStyles.accentBarExpanded]} />
<Text style={[accordionStyles.title, expanded && accordionStyles.titleExpanded]}>
{title}
</Text>
<View style={accordionStyles.chevronWrapper}>
<Ionicons
name={expanded ? "chevron-up" : "chevron-down"}
size={18}
color={greenTone.accent}
/>
</View>
</Pressable>
{expanded ? (
<View style={accordionStyles.expandedBody}>
{detailQuery.isLoading && !detailQuery.data ? (
<View style={accordionStyles.loadingRow}>
<ActivityIndicator size="small" color={greenTone.accent} />
<Text style={accordionStyles.loadingText}>Loading pattern details…</Text>
</View>
) : (
<>
{/* 1. Clinical Manifestations */}
{clinicalManifestations.length > 0 ? (
<View style={accordionStyles.section}>
<Text style={accordionStyles.sectionTitle}>
{resolveAttributeLabel("clinical_manifestations", labelMap, "Clinical Manifestations")}
</Text>
<View style={accordionStyles.bulletList}>
{clinicalManifestations.map((itemText, idx) => (
<View key={idx} style={accordionStyles.bulletRow}>
<View style={accordionStyles.bulletDot} />
<Text style={accordionStyles.bulletText}>{itemText}</Text>
</View>
))}
</View>
</View>
) : null}
{/* 2. Tongue */}
{tongue ? (
<View style={accordionStyles.section}>
<Text style={accordionStyles.sectionTitle}>
{resolveAttributeLabel("tongue", labelMap, "Tongue")}
</Text>
<Text style={accordionStyles.sectionText}>{tongue}</Text>
</View>
) : null}
{/* 3. Pulse */}
{pulse ? (
<View style={accordionStyles.section}>
<Text style={accordionStyles.sectionTitle}>
{resolveAttributeLabel("pulse", labelMap, "Pulse")}
</Text>
<Text style={accordionStyles.sectionText}>{pulse}</Text>
</View>
) : null}
{/* 3. Treatment Principle */}
{treatmentPrinciples.length > 0 ? (
<View style={accordionStyles.section}>
<Text style={accordionStyles.sectionTitle}>
{resolveAttributeLabel("treatment_principle", labelMap, "Treatment Principle")}
</Text>
<View style={accordionStyles.bulletList}>
{treatmentPrinciples.map((itemText, idx) => (
<View key={idx} style={accordionStyles.bulletRow}>
<View style={accordionStyles.bulletDot} />
<Text style={accordionStyles.bulletText}>{itemText}</Text>
</View>
))}
</View>
</View>
) : null}
{/* 4. Acupuncture Points */}
{pointChips.length > 0 ? (
<View style={accordionStyles.section}>
<Text style={accordionStyles.sectionTitle}>
{resolveAttributeLabel("acupuncture", labelMap, "Acupuncture Points")}
</Text>
<View style={accordionStyles.chipsContainer}>
{pointChips.map((pt, idx) => (
<Pressable
key={idx}
accessibilityRole="button"
accessibilityLabel={`View ${pt} acupuncture point`}
onPress={() => handlePointPress(pt)}
style={({ pressed }) => [
accordionStyles.pointChip,
pressed && accordionStyles.pointChipPressed,
]}
>
<Text style={accordionStyles.pointChipText}>{pt}</Text>
<Ionicons
name="chevron-forward"
size={12}
color="#35664E"
style={{ marginLeft: 2 }}
/>
</Pressable>
))}
</View>
</View>
) : null}
{/* 5. Method */}
{acuMethod ? (
<View style={accordionStyles.section}>
<Text style={accordionStyles.sectionTitle}>
{resolveAttributeLabel("acupuncture.method", labelMap, "Method")}
</Text>
<Text style={accordionStyles.sectionText}>{acuMethod}</Text>
</View>
) : null}
{/* 5. Explanation */}
{explanations.length > 0 ? (
<View style={accordionStyles.section}>
<Text style={accordionStyles.sectionTitle}>
{resolveAttributeLabel("explanation", labelMap, "Explanation")}
</Text>
<View style={accordionStyles.explanationList}>
{explanations.map((exp, idx) => (
<View key={idx} style={accordionStyles.explanationRow}>
<View style={accordionStyles.explanationDot} />
<Text style={accordionStyles.explanationText}>{exp}</Text>
</View>
))}
</View>
</View>
) : null}
{/* 6. Category */}
{category ? (
<View style={accordionStyles.categoryRow}>
<Text style={accordionStyles.categoryLabel}>
{`${resolveAttributeLabel("category", labelMap, "Category")}:`}
</Text>
<View style={accordionStyles.categoryBadge}>
<Text style={accordionStyles.categoryBadgeText}>{category}</Text>
</View>
</View>
) : null}
</>
)}
</View>
) : null}
</View>
);
}
export function ModuleCatalogCardRenderer({ export function ModuleCatalogCardRenderer({
item, item,
onPress, onPress,
}: CollectionItemRendererProps) { }: CollectionItemRendererProps) {
const attributes = item.attributes; const attributes = item.attributes;
const rawTitle = const title = asString(attributes.name) || item.title;
asString(attributes.food_name) || const label =
asString(attributes.name) ||
item.title;
const parenMatch = rawTitle.match(/^(.*?)\s*\(([^()]+)\)\s*(.*?)$/);
const title = parenMatch
? [parenMatch[1], parenMatch[3]].filter(Boolean).join(" ").trim()
: rawTitle;
const parenSubtitle = parenMatch ? parenMatch[2].trim() : null;
const rawLabel =
parenSubtitle ||
asString(attributes.sub_title) || asString(attributes.sub_title) ||
asString(attributes.subtitle) || asString(attributes.content_label) ||
(asStringArray(attributes.alt_name).length > 0
? asStringArray(attributes.alt_name).join(", ")
: asString(attributes.alt_name)) ||
asString(attributes.pattern_category) ||
asString(attributes.category) ||
asString(attributes.classification) ||
(asString(attributes.title) && asString(attributes.title) !== title (asString(attributes.title) && asString(attributes.title) !== title
? asString(attributes.title) ? asString(attributes.title)
: null) || : null) ||
@ -395,250 +32,34 @@ export function ModuleCatalogCardRenderer({
item.summary || item.summary ||
null; null;
const cleanTitle = humanizeKey(title);
const label = rawLabel ? humanizeKey(rawLabel) : null;
const count = asNumber(attributes.content_count);
const itemCode = asString(attributes.code).toLowerCase().trim();
const rawTitleLower = rawTitle.toLowerCase().trim();
const rawLink = attributes.link as { type?: unknown; target?: unknown } | undefined;
const hasNavigableLink = Boolean(
rawLink && typeof rawLink === "object" && rawLink.type && rawLink.target,
);
const isSpecialDisabled = false;
const isClickable =
!isSpecialDisabled &&
(hasNavigableLink || (count !== null && count > 0) || count === null);
return ( return (
<Pressable <Pressable
accessibilityRole={isClickable ? "button" : undefined} accessibilityRole="button"
disabled={!isClickable} onPress={onPress}
onPress={isClickable ? onPress : undefined} style={({ pressed }) => [styles.row, pressed && styles.pressed]}
style={({ pressed }) => [
styles.row,
isClickable && pressed && styles.pressed,
]}
> >
<View style={styles.iconWrapper}> <View style={styles.iconWrapper}>
<Ionicons name="book-outline" size={22} color={Colors.primary} /> <Ionicons name="book-outline" size={22} color={Colors.primary} />
</View> </View>
<View style={styles.textContainer}> <View style={styles.textContainer}>
<Text style={styles.title}>{cleanTitle}</Text> <Text style={styles.title}>{title}</Text>
{label ? ( {label ? (
<Text numberOfLines={2} style={styles.subtitle}> <Text style={styles.description} numberOfLines={1}>
{label} {label}
</Text> </Text>
) : null} ) : null}
</View> </View>
<ContentCountBadge <ContentCountBadge
count={count} count={asNumber(attributes.content_count)}
label={asString(attributes.content_label)} label={asString(attributes.content_label)}
/> />
{isClickable ? ( <Ionicons name="chevron-forward" size={20} color="#9CA3AF" />
<Ionicons name="chevron-forward" size={20} color="#9CA3AF" />
) : null}
</Pressable> </Pressable>
); );
} }
const accordionStyles = StyleSheet.create({
cardContainer: {
backgroundColor: "#FFFFFF",
width: "100%",
},
headerRow: {
minHeight: verticalScale(54),
flexDirection: "row",
alignItems: "center",
paddingHorizontal: moderateScale(14),
paddingVertical: verticalScale(12),
backgroundColor: greenTone.soft,
gap: moderateScale(10),
},
headerRowExpanded: {
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: greenTone.border,
},
accentBar: {
width: moderateScale(4),
alignSelf: "stretch",
minHeight: verticalScale(26),
borderRadius: moderateScale(999),
backgroundColor: greenTone.accent,
},
accentBarExpanded: {
backgroundColor: greenTone.accent,
},
pressed: {
opacity: 0.74,
},
title: {
flex: 1,
fontSize: moderateScale(15),
lineHeight: moderateScale(21),
fontWeight: "700",
color: greenTone.title,
letterSpacing: 0.1,
},
titleExpanded: {
color: greenTone.title,
},
chevronWrapper: {
width: moderateScale(30),
height: moderateScale(30),
borderRadius: moderateScale(15),
alignItems: "center",
justifyContent: "center",
backgroundColor: "#FFFFFFB8",
},
expandedBody: {
paddingHorizontal: moderateScale(18),
paddingTop: verticalScale(16),
paddingBottom: verticalScale(18),
backgroundColor: "#FFFFFF",
gap: verticalScale(16),
},
loadingRow: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
paddingVertical: verticalScale(16),
gap: moderateScale(8),
},
loadingText: {
fontSize: moderateScale(13),
color: "#64748B",
},
section: {
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: "#E2EAE5",
paddingBottom: verticalScale(14),
gap: verticalScale(8),
},
sectionTitle: {
fontSize: moderateScale(12),
lineHeight: moderateScale(16),
fontWeight: "700",
color: "#4A6B5B",
letterSpacing: 0.15,
},
bulletList: {
gap: verticalScale(8),
},
bulletRow: {
flexDirection: "row",
alignItems: "flex-start",
gap: moderateScale(10),
},
bulletDot: {
width: moderateScale(6),
height: moderateScale(6),
marginTop: verticalScale(7),
borderRadius: moderateScale(3),
backgroundColor: greenTone.accent,
},
bulletText: {
flex: 1,
fontSize: moderateScale(14),
lineHeight: moderateScale(21),
color: "#334155",
},
sectionText: {
fontSize: moderateScale(14),
lineHeight: moderateScale(21),
color: "#334155",
},
principleBox: {
backgroundColor: greenTone.soft,
paddingHorizontal: moderateScale(12),
paddingVertical: verticalScale(10),
borderRadius: moderateScale(8),
borderLeftWidth: moderateScale(3),
borderLeftColor: greenTone.accent,
},
principleText: {
fontSize: moderateScale(14),
lineHeight: moderateScale(21),
color: greenTone.title,
fontStyle: "italic",
},
chipsContainer: {
flexDirection: "row",
flexWrap: "wrap",
gap: moderateScale(7),
},
pointChip: {
flexDirection: "row",
alignItems: "center",
backgroundColor: "#EEF7F1",
borderWidth: 1,
borderColor: "#D5E8DB",
paddingHorizontal: moderateScale(11),
paddingVertical: verticalScale(5),
borderRadius: moderateScale(999),
},
pointChipPressed: {
opacity: 0.72,
transform: [{ scale: 0.96 }],
},
pointChipText: {
fontSize: moderateScale(13),
lineHeight: moderateScale(18),
fontWeight: "700",
color: "#35664E",
},
explanationList: {
gap: verticalScale(8),
},
explanationRow: {
flexDirection: "row",
alignItems: "flex-start",
gap: moderateScale(10),
},
explanationDot: {
width: moderateScale(5),
height: moderateScale(5),
marginTop: verticalScale(7),
borderRadius: moderateScale(2.5),
backgroundColor: "#829B8E",
},
explanationText: {
flex: 1,
fontSize: moderateScale(13),
lineHeight: moderateScale(19),
color: "#334155",
},
categoryRow: {
flexDirection: "row",
alignItems: "center",
gap: moderateScale(10),
paddingTop: verticalScale(2),
},
categoryLabel: {
fontSize: moderateScale(11),
lineHeight: moderateScale(15),
fontWeight: "700",
color: "#597064",
letterSpacing: 0.15,
},
categoryBadge: {
backgroundColor: "#EEF7F1",
borderWidth: 1,
borderColor: "#D5E8DB",
paddingHorizontal: moderateScale(11),
paddingVertical: verticalScale(4),
borderRadius: moderateScale(999),
},
categoryBadgeText: {
fontSize: moderateScale(12),
lineHeight: moderateScale(16),
fontWeight: "600",
color: "#35664E",
},
});
const styles = StyleSheet.create({ const styles = StyleSheet.create({
row: { row: {
minHeight: moderateScale(68), minHeight: moderateScale(68),
@ -666,12 +87,10 @@ const styles = StyleSheet.create({
fontSize: moderateScale(15), fontSize: moderateScale(15),
fontWeight: "600", fontWeight: "600",
color: Colors.textPrimary, color: Colors.textPrimary,
marginBottom: verticalScale(2),
}, },
subtitle: { description: {
fontSize: moderateScale(12), fontSize: moderateScale(12),
color: Colors.textSecondary, color: Colors.textSecondary,
marginTop: verticalScale(2),
lineHeight: moderateScale(16),
}, },
}); });

View File

@ -6,7 +6,6 @@ import { moderateScale, verticalScale } from "react-native-size-matters";
import { Colors } from "@/theme"; import { Colors } from "@/theme";
import { asNumber, asString } from "../helpers/value"; import { asNumber, asString } from "../helpers/value";
import { CollectionScaffold } from "../shared/CollectionScaffold"; import { CollectionScaffold } from "../shared/CollectionScaffold";
import { OverviewCard } from "../shared/OverviewCard";
import type { import type {
CollectionItemRendererProps, CollectionItemRendererProps,
CollectionRendererProps, CollectionRendererProps,
@ -17,15 +16,24 @@ export function PathogenicFactorsCollectionRenderer(
) { ) {
const header = ( const header = (
<View style={styles.overviewContainer}> <View style={styles.overviewContainer}>
<OverviewCard <View style={styles.overviewCard}>
style={styles.overviewCard} <View style={styles.overviewHeader}>
paragraphs={[ <Ionicons name="information-circle" size={20} color={Colors.primary} />
"This method of pattern identification is based on the pathological changes occurring when the body is invaded by pathogenic factors such as Wind, Cold, Summer-Heat, Dampness, Dryness and Fire. Each of these pathogenic factors may be exterior or interior.", <Text style={styles.overviewTitle}>Overview</Text>
"They always correspond to a Full pattern according to the Eight Principles. Indeed, from the Eight-Principle point of view, a Full condition is defined as one characterized by the presence of a pathogenic factor while the body’s Qi is still relatively intact.", </View>
"The pathogenic factor is frequently associated with a Deficiency, in which case the condition is a combined Full–Empty condition. With regard to pathogenic factors, a combined Full-Empty condition can arise in one of two ways: a pathogenic factor can give rise to a Deficiency (e.g. Fire weakens Yin) or a Deficiency can give rise to a pathogenic factor (e.g. Spleen-Qi deficiency gives rise to Dampness).", <Text style={styles.overviewText}>
"Generally speaking, pathogenic factors are more relevant as patterns of disharmony than as causes of disease. The diagnosis of a pathogenic factor is made not on the basis of the patient’s history, but on the basis of the pattern of symptoms and signs presented.", This method of pattern identification is based on the pathological changes occurring when the body is invaded by pathogenic factors such as Wind, Cold, Summer-Heat, Dampness, Dryness and Fire. Each of these pathogenic factors may be exterior or interior.
]} </Text>
/> <Text style={styles.overviewParagraph}>
They always correspond to a Full pattern according to the Eight Principles. Indeed, from the Eight-Principle point of view, a Full condition is defined as one characterized by the presence of a pathogenic factor while the body’s Qi is still relatively intact.
</Text>
<Text style={styles.overviewParagraph}>
The pathogenic factor is frequently associated with a Deficiency, in which case the condition is a combined Full–Empty condition. With regard to pathogenic factors, a combined Full-Empty condition can arise in one of two ways: a pathogenic factor can give rise to a Deficiency (e.g. Fire weakens Yin) or a Deficiency can give rise to a pathogenic factor (e.g. Spleen-Qi deficiency gives rise to Dampness).
</Text>
<Text style={styles.overviewParagraph}>
Generally speaking, pathogenic factors are more relevant as patterns of disharmony than as causes of disease. The diagnosis of a pathogenic factor is made not on the basis of the patient’s history, but on the basis of the pattern of symptoms and signs presented.
</Text>
</View>
<Text style={styles.sectionHeading}>Pathogenic Factors</Text> <Text style={styles.sectionHeading}>Pathogenic Factors</Text>
</View> </View>
); );
@ -97,8 +105,35 @@ const styles = StyleSheet.create({
marginBottom: verticalScale(14), marginBottom: verticalScale(14),
}, },
overviewCard: { overviewCard: {
backgroundColor: "#FFFFFF",
borderRadius: moderateScale(16),
borderWidth: 1,
borderColor: "#E2EAE5",
padding: moderateScale(16),
marginBottom: verticalScale(14), marginBottom: verticalScale(14),
}, },
overviewHeader: {
flexDirection: "row",
alignItems: "center",
marginBottom: verticalScale(8),
gap: moderateScale(8),
},
overviewTitle: {
fontSize: moderateScale(16),
fontWeight: "700",
color: Colors.textPrimary,
},
overviewText: {
fontSize: moderateScale(13),
lineHeight: verticalScale(19),
color: Colors.textSecondary,
},
overviewParagraph: {
fontSize: moderateScale(13),
lineHeight: verticalScale(19),
color: Colors.textSecondary,
marginTop: verticalScale(10),
},
sectionHeading: { sectionHeading: {
fontSize: moderateScale(15), fontSize: moderateScale(15),
fontWeight: "700", fontWeight: "700",

View File

@ -1,44 +1,11 @@
import React, { useMemo } from "react"; import React from "react";
import { asString } from "../helpers/value"; import { asString } from "../helpers/value";
import { CollectionScaffold } from "../shared/CollectionScaffold"; import { CollectionScaffold } from "../shared/CollectionScaffold";
import { StandardIndexCard } from "../shared/StandardIndexCard"; import { StandardIndexCard } from "../shared/StandardIndexCard";
import type { import type { CollectionItemRendererProps, CollectionRendererProps } from "../../types/renderer.types";
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) { export function AcuPointIndexCollectionRenderer(props: CollectionRendererProps) {
const sortedItems = useMemo( return <CollectionScaffold {...props} />;
() => sortWithExtraPointsAfterDu(props.items),
[props.items],
);
return <CollectionScaffold {...props} items={sortedItems} />;
} }
export function AcuPointCollectionRenderer(props: CollectionRendererProps) { export function AcuPointCollectionRenderer(props: CollectionRendererProps) {
return <CollectionScaffold {...props} />; return <CollectionScaffold {...props} />;

View File

@ -6,7 +6,6 @@ import { moderateScale, verticalScale } from "react-native-size-matters";
import { Colors } from "@/theme"; import { Colors } from "@/theme";
import { asNumber, asString } from "../helpers/value"; import { asNumber, asString } from "../helpers/value";
import { CollectionScaffold } from "../shared/CollectionScaffold"; import { CollectionScaffold } from "../shared/CollectionScaffold";
import { OverviewCard } from "../shared/OverviewCard";
import { useSingleTemplateContentQuery } from "../../hooks/use-single-template-content-query"; import { useSingleTemplateContentQuery } from "../../hooks/use-single-template-content-query";
import type { import type {
CollectionItemRendererProps, CollectionItemRendererProps,
@ -70,7 +69,15 @@ export function QiBloodCollectionRenderer(props: CollectionRendererProps) {
const header = ( const header = (
<View style={styles.headerContainer}> <View style={styles.headerContainer}>
{overviewText ? <OverviewCard text={overviewText} /> : null} {overviewText ? (
<View style={styles.overviewCard}>
<View style={styles.overviewHeader}>
<Ionicons name="information-circle" size={20} color={Colors.primary} />
<Text style={styles.overviewTitle}>Overview</Text>
</View>
<Text style={styles.overviewText}>{overviewText}</Text>
</View>
) : null}
<Text style={styles.sectionHeading}>Categories</Text> <Text style={styles.sectionHeading}>Categories</Text>
</View> </View>
@ -127,6 +134,29 @@ const styles = StyleSheet.create({
paddingBottom: verticalScale(8), paddingBottom: verticalScale(8),
gap: verticalScale(14), gap: verticalScale(14),
}, },
overviewCard: {
backgroundColor: "#FFFFFF",
borderRadius: moderateScale(16),
borderWidth: 1,
borderColor: "#E2EAE5",
padding: moderateScale(18),
},
overviewHeader: {
flexDirection: "row",
alignItems: "center",
marginBottom: verticalScale(10),
gap: moderateScale(8),
},
overviewTitle: {
fontSize: moderateScale(16),
fontWeight: "700",
color: Colors.textPrimary,
},
overviewText: {
fontSize: moderateScale(14),
lineHeight: moderateScale(22),
color: Colors.textSecondary,
},
sectionHeading: { sectionHeading: {
fontSize: moderateScale(16), fontSize: moderateScale(16),
fontWeight: "700", fontWeight: "700",

View File

@ -1,138 +0,0 @@
import React from "react";
import { Pressable, StyleSheet, Text, View } from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { moderateScale, verticalScale } from "react-native-size-matters";
import { Colors } from "@/theme";
import { asNumber, asString, humanizeKey } from "../helpers/value";
import { CollectionScaffold } from "../shared/CollectionScaffold";
import { OverviewCard } from "../shared/OverviewCard";
import type {
CollectionItemRendererProps,
CollectionRendererProps,
} from "../../types/renderer.types";
export function SixStagesCollectionRenderer(props: CollectionRendererProps) {
const overviewText = asString(props.items[0]?.attributes.stage_overview).trim();
const header = overviewText ? (
<View style={styles.overviewContainer}>
<OverviewCard text={overviewText} />
</View>
) : null;
return (
<CollectionScaffold
{...props}
header={header}
/>
);
}
export function SixStagesCardRenderer({
item,
onPress,
}: CollectionItemRendererProps) {
const attributes = item.attributes;
const rawTitle = asString(attributes.name) || item.title;
const parenMatch = rawTitle.match(/^(.*?)\s*\(([^()]+)\)\s*(.*?)$/);
const title = parenMatch
? [parenMatch[1], parenMatch[3]].filter(Boolean).join(" ").trim()
: rawTitle;
const parenSubtitle = parenMatch ? parenMatch[2].trim() : null;
const label =
parenSubtitle ||
asString(attributes.sub_title) ||
null;
const cleanTitle = humanizeKey(title);
const cleanLabel = label ? humanizeKey(label) : null;
const count = asNumber(attributes.content_count);
const rawContentLabel = asString(attributes.content_label);
const contentLabel = rawContentLabel ? humanizeKey(rawContentLabel) : null;
const badgeText =
count !== null && count > 0 && contentLabel
? `${count} ${contentLabel}`
: contentLabel || (count !== null ? `${count}` : null);
return (
<Pressable
accessibilityRole="button"
onPress={onPress}
style={({ pressed }) => [styles.row, pressed && styles.pressed]}
>
<View style={styles.iconWrapper}>
<Ionicons name="book-outline" size={22} color={Colors.primary} />
</View>
<View style={styles.textContainer}>
<Text style={styles.title}>{cleanTitle}</Text>
{cleanLabel ? (
<Text style={styles.description} numberOfLines={1}>
{cleanLabel}
</Text>
) : null}
</View>
{badgeText ? (
<View style={styles.badge}>
<Text style={styles.badgeText}>{badgeText}</Text>
</View>
) : null}
<Ionicons name="chevron-forward" size={20} color="#9CA3AF" />
</Pressable>
);
}
const styles = StyleSheet.create({
overviewContainer: {
marginBottom: verticalScale(14),
},
row: {
minHeight: moderateScale(68),
flexDirection: "row",
alignItems: "center",
padding: moderateScale(14),
},
pressed: {
opacity: 0.72,
},
iconWrapper: {
width: moderateScale(40),
height: moderateScale(40),
borderRadius: moderateScale(20),
justifyContent: "center",
alignItems: "center",
backgroundColor: "#E8F5E9",
},
textContainer: {
flex: 1,
marginLeft: moderateScale(12),
marginRight: moderateScale(10),
},
title: {
fontSize: moderateScale(15),
fontWeight: "600",
color: Colors.textPrimary,
marginBottom: verticalScale(2),
},
description: {
fontSize: moderateScale(12),
color: Colors.textSecondary,
},
badge: {
backgroundColor: "#F3F4F6",
borderRadius: moderateScale(12),
paddingHorizontal: moderateScale(9),
paddingVertical: verticalScale(5),
marginRight: moderateScale(8),
},
badgeText: {
fontSize: moderateScale(11),
fontWeight: "700",
color: Colors.textSecondary,
},
});

View File

@ -4,7 +4,7 @@ import { Ionicons } from "@expo/vector-icons";
import { moderateScale } from "react-native-size-matters"; import { moderateScale } from "react-native-size-matters";
import { Colors } from "@/theme"; import { Colors } from "@/theme";
import { asNumber, asString, formatPatternTitle } from "../helpers/value"; import { asNumber, asString } from "../helpers/value";
import { CollectionScaffold } from "../shared/CollectionScaffold"; import { CollectionScaffold } from "../shared/CollectionScaffold";
import type { import type {
CollectionItemRendererProps, CollectionItemRendererProps,
@ -20,8 +20,7 @@ export function ThreeBurnersCardRenderer({
onPress, onPress,
}: CollectionItemRendererProps) { }: CollectionItemRendererProps) {
const a = item.attributes; const a = item.attributes;
const rawTitle = asString(a.name) || asString(a.title) || item.title; const title = asString(a.name) || asString(a.title) || item.title;
const title = formatPatternTitle(rawTitle);
const sortOrder = asNumber(a.sort_order); const sortOrder = asNumber(a.sort_order);
return ( return (

View File

@ -38,7 +38,7 @@ function RelationshipRow({ label, value, chips = false }: RelationshipRowProps)
return ( return (
<View style={styles.relationshipRow}> <View style={styles.relationshipRow}>
<Text style={styles.relationshipLabel}>{label}</Text> <Text style={styles.relationshipLabel}>{label}</Text>
{chips ? <ReferenceChipList value={value} asBulletList={false} /> : <ContentValue value={value} />} {chips ? <ReferenceChipList value={value} /> : <ContentValue value={value} />}
</View> </View>
); );
} }
@ -148,47 +148,6 @@ export function EovDetailRenderer({
}); });
} }
const clinicalManifestations = data.clinical_manifestation ?? data.clinical_manifestations;
if (!isEmptyValue(clinicalManifestations)) {
items.push({
key: "clinical_manifestation",
order: orderFor("clinical_manifestation", orderFor("clinical_manifestations", 125)),
render: () => (
<SectionCard title="Clinical Manifestations">
<BulletList items={asStringArray(clinicalManifestations)} />
</SectionCard>
),
});
}
if (!isEmptyValue(data.connecting_channel)) {
items.push({
key: "connecting_channel",
order: orderFor("connecting_channel", 130),
render: () => (
<SectionCard title="Connecting Channel">
<Text style={styles.pathway}>{asString(data.connecting_channel)}</Text>
</SectionCard>
),
});
}
if (!isEmptyValue(data.treatment)) {
items.push({
key: "treatment",
order: orderFor("treatment", 140),
render: () => (
<SectionCard title="Treatment">
{typeof data.treatment === "object" ? (
<ContentValue value={data.treatment} />
) : (
<Text style={styles.pathway}>{asString(data.treatment)}</Text>
)}
</SectionCard>
),
});
}
return items.sort((a, b) => a.order - b.order || a.key.localeCompare(b.key)); return items.sort((a, b) => a.order - b.order || a.key.localeCompare(b.key));
}, [data, orderFor, relationshipRows]); }, [data, orderFor, relationshipRows]);
@ -234,7 +193,8 @@ const styles = StyleSheet.create({
lineHeight: 17, lineHeight: 17,
fontWeight: "700", fontWeight: "700",
color: "#597064", color: "#597064",
letterSpacing: 0.15, textTransform: "uppercase",
letterSpacing: 0.4,
}, },
pathway: { pathway: {
fontSize: 16, fontSize: 16,

View File

@ -29,8 +29,6 @@ const RESERVED_KEYS = new Set([
"title", "title",
"sub_title", "sub_title",
"subtitle", "subtitle",
"alt_name",
"alternative_names",
"code", "code",
"sort_order", "sort_order",
"link", "link",
@ -63,9 +61,7 @@ export function ExtraOrdinaryVesselsDetailRenderer({
const subtitle = const subtitle =
asString(data.sub_title) || asString(data.sub_title) ||
asString(data.subtitle) || asString(data.subtitle) ||
(asStringArray(data.alt_name).length > 0 undefined;
? asStringArray(data.alt_name).join(", ")
: undefined);
const mediaValue = data.images ?? data.media ?? data.point_images; const mediaValue = data.images ?? data.media ?? data.point_images;
const media = Array.isArray(mediaValue) const media = Array.isArray(mediaValue)

View File

@ -8,9 +8,6 @@ import { Colors } from "@/theme";
import type { DetailRendererProps } from "../../types/renderer.types"; import type { DetailRendererProps } from "../../types/renderer.types";
import { ContentLinkAttributeSections } from "../shared/ContentLinkAttributeSections"; import { ContentLinkAttributeSections } from "../shared/ContentLinkAttributeSections";
import { Hero } from "../shared/Hero"; import { Hero } from "../shared/Hero";
import { OverviewCard } from "../shared/OverviewCard";
import { Paragraphs } from "../shared/Paragraphs";
import { SectionCard } from "../shared/SectionCard";
import { asRecordArray, asString, asStringArray } from "../helpers/value"; import { asRecordArray, asString, asStringArray } from "../helpers/value";
function resolveSequenceTargetTemplate( function resolveSequenceTargetTemplate(
@ -97,7 +94,20 @@ export function FiveElementsDetailRenderer({
{/* Overview Card (rendered only when overview/content exists in data) */} {/* Overview Card (rendered only when overview/content exists in data) */}
{overviewParagraphs.length > 0 ? ( {overviewParagraphs.length > 0 ? (
<OverviewCard paragraphs={overviewParagraphs} /> <View style={styles.overviewCard}>
<View style={styles.overviewHeader}>
<Ionicons name="information-circle" size={20} color={Colors.primary} />
<Text style={styles.overviewTitle}>Overview</Text>
</View>
{overviewParagraphs.map((para, idx) => (
<Text
key={idx}
style={[styles.overviewText, idx > 0 && styles.paragraphSpacing]}
>
{para}
</Text>
))}
</View>
) : null} ) : null}
{/* Dynamic Sequences List from data.sections */} {/* Dynamic Sequences List from data.sections */}
@ -169,25 +179,53 @@ export function FiveElementsDetailRenderer({
{/* Overview Card (rendered only when overview/content exists in data) */} {/* Overview Card (rendered only when overview/content exists in data) */}
{overviewParagraphs.length > 0 ? ( {overviewParagraphs.length > 0 ? (
<OverviewCard paragraphs={overviewParagraphs} /> <View style={styles.overviewCard}>
<View style={styles.overviewHeader}>
<Ionicons name="information-circle" size={20} color={Colors.primary} />
<Text style={styles.overviewTitle}>Overview</Text>
</View>
{overviewParagraphs.map((para, idx) => (
<Text
key={idx}
style={[styles.overviewText, idx > 0 && styles.paragraphSpacing]}
>
{para}
</Text>
))}
</View>
) : null} ) : null}
{/* Collapsible Pattern Cards from data.sections */} {/* Numbered Pattern Cards from data.sections */}
{rawSections.map((sec, idx) => { {rawSections.length > 0 ? (
const sectionTitle = asString(sec.title) || `Pattern ${idx + 1}`; <View style={styles.sectionsContainer}>
const sectionContent = extractParagraphs(sec.content); <Text style={styles.sectionHeading}>Patterns & Manifestations</Text>
{rawSections.map((sec, idx) => {
const sectionTitle = asString(sec.title) || `Pattern ${idx + 1}`;
const sectionContent = extractParagraphs(sec.content);
return ( return (
<SectionCard <View key={idx} style={styles.patternCard}>
key={idx} <View style={styles.patternHeader}>
title={sectionTitle} <View style={styles.numberBadge}>
> <Text style={styles.numberText}>{idx + 1}</Text>
{sectionContent.length > 0 ? ( </View>
<Paragraphs items={sectionContent} /> <Text style={styles.patternTitle}>{sectionTitle}</Text>
) : null} </View>
</SectionCard>
); {sectionContent.length > 0 ? (
})} <View style={styles.patternBody}>
{sectionContent.map((text, cIdx) => (
<Text key={cIdx} style={styles.contentText}>
{text}
</Text>
))}
</View>
) : null}
</View>
);
})}
</View>
) : null}
<ContentLinkAttributeSections <ContentLinkAttributeSections
data={data} data={data}
@ -205,6 +243,32 @@ const styles = StyleSheet.create({
paddingBottom: verticalScale(40), paddingBottom: verticalScale(40),
gap: verticalScale(14), gap: verticalScale(14),
}, },
overviewCard: {
backgroundColor: "#FFFFFF",
borderRadius: moderateScale(16),
borderWidth: 1,
borderColor: "#E2EAE5",
padding: moderateScale(16),
},
overviewHeader: {
flexDirection: "row",
alignItems: "center",
marginBottom: verticalScale(8),
gap: moderateScale(8),
},
overviewTitle: {
fontSize: moderateScale(16),
fontWeight: "700",
color: Colors.textPrimary,
},
overviewText: {
fontSize: moderateScale(13),
lineHeight: verticalScale(19),
color: Colors.textSecondary,
},
paragraphSpacing: {
marginTop: verticalScale(10),
},
sequencesContainer: { sequencesContainer: {
gap: verticalScale(10), gap: verticalScale(10),
}, },

View File

@ -1,72 +1,13 @@
import React from "react"; import React from "react";
import { Pressable, ScrollView, StyleSheet, Text, View } from "react-native"; import { ScrollView, StyleSheet } from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { useRouter } from "expo-router";
import { moderateScale, verticalScale } from "react-native-size-matters";
import { Colors } from "@/theme";
import type { DetailRendererProps } from "../../types/renderer.types"; import type { DetailRendererProps } from "../../types/renderer.types";
import {
buildContentReferenceRoute,
parseNavigableContentReference,
} from "../../utils/content-reference";
import { asRecord, asString, asStringArray } from "../helpers/value";
import { BulletList } from "../shared/BulletList";
import { ContentLinkAttributeSections } from "../shared/ContentLinkAttributeSections"; import { ContentLinkAttributeSections } from "../shared/ContentLinkAttributeSections";
import { ContentValue } from "../shared/ContentValue";
import { Hero } from "../shared/Hero"; import { Hero } from "../shared/Hero";
import { OverviewCard } from "../shared/OverviewCard";
import { Paragraphs } from "../shared/Paragraphs";
import { SectionCard } from "../shared/SectionCard"; import { SectionCard } from "../shared/SectionCard";
import { Paragraphs } from "../shared/Paragraphs";
function parseExplanationBullets(value: unknown): string[] { import { asString } from "../helpers/value";
if (!value) return [];
if (Array.isArray(value)) {
return value.map(asString).filter(Boolean);
}
const str = asString(value);
if (!str) return [];
if (str.includes("\n")) {
return str
.split(/\n+/)
.map((s) => s.trim().replace(/^\t+/, ""))
.filter(Boolean);
}
const regex =
/(?<=[^\s:,\+])(?<!\band)\s+(?=(?:(?:[A-Z]{2,4}-\d+|RN-\d+|DU-\d+|REN-\d+)(?:[,\s]+(?:[A-Z]{2,4}-\d+|RN-\d+|DU-\d+|REN-\d+))*(?:\s*(?:and|\+)\s*(?:[A-Z]{2,4}-\d+|RN-\d+|DU-\d+|REN-\d+))?(?:\s*\([^)]*\))?:\s*|Cupping\b|Moxa\b))/i;
const parts = str
.split(regex)
.map((s) => s.trim().replace(/^\t+/, ""))
.filter(Boolean);
return parts.length > 0 ? parts : [str];
}
function parseTreatmentBullets(value: unknown): string[] {
if (!value) return [];
if (Array.isArray(value)) {
return value.map(asString).filter(Boolean);
}
const str = asString(value);
if (!str) return [];
if (str.includes("\n")) {
return str
.split(/\n+/)
.map((s) => s.trim().replace(/^\t+/, ""))
.filter(Boolean);
}
const items = str
.split(/,\s*(?![^()]*\))/)
.map((s) => s.trim().replace(/\.$/, ""))
.filter(Boolean);
return items.length > 0 ? items : [str];
}
export function FourLevelsDetailRenderer({ export function FourLevelsDetailRenderer({
content, content,
@ -74,122 +15,26 @@ export function FourLevelsDetailRenderer({
definitions, definitions,
presentationAttributes, presentationAttributes,
}: DetailRendererProps) { }: DetailRendererProps) {
const router = useRouter();
const title = const title =
asString(data.name) || asString(data.name) ||
asString(data.title) || asString(data.title) ||
content.title; content.title;
const overview = asString(data.overview); const overview = asString(data.overview);
const rawPatterns = Array.isArray(data.patterns) ? data.patterns : []; const clinicalManifestations =
const hasPatterns = rawPatterns.length > 0; asString(data.clinical_manifestation) ||
asString(data.clinical_manifestations) ||
const clinicalManifestationsRaw = asString(data.clinical_menifestation);
data.clinical_manifestation ??
data.clinical_manifestations ??
data.clinical_menifestation;
const clinicalManifestationItems = asStringArray(clinicalManifestationsRaw).filter(
(item) => item.trim().length > 0,
);
const tongue = asString(data.tongue); const tongue = asString(data.tongue);
const pulse = asString(data.pulse); const pulse = asString(data.pulse);
const pathology = asString(data.pathology); const pathology = asString(data.pathology);
const treatmentPrincipleRaw = const treatmentPrinciple =
data.treatment_principle ?? data["treatment principle"]; asString(data.treatment_principle) ||
const treatmentPrincipleItems = asStringArray(treatmentPrincipleRaw).filter( asString(data["treatment principle"]);
(item) => item.trim().length > 0,
);
const treatmentPrinciple = asString(treatmentPrincipleRaw);
const treatment = asString(data.treatment); const treatment = asString(data.treatment);
const treatmentBullets = parseTreatmentBullets(treatment);
const explanation = asString(data.explanation); const explanation = asString(data.explanation);
const explanationBullets = parseExplanationBullets(explanation);
const contentText = asString(data.content); const contentText = asString(data.content);
if (hasPatterns) {
return (
<ScrollView
contentContainerStyle={styles.content}
showsVerticalScrollIndicator={false}
>
<Hero title={title} />
{/* Direct Overview Card matching Four Levels 1st page */}
{overview ? <OverviewCard text={overview} /> : null}
{/* Patterns List with numbered cards matching 1st page */}
<View style={styles.patternsSection}>
<View style={styles.sectionHeaderRow}>
<Text style={styles.sectionHeading}>Patterns</Text>
<View style={styles.countBadge}>
<Text style={styles.countBadgeText}>
{rawPatterns.length} {rawPatterns.length === 1 ? "pattern" : "patterns"}
</Text>
</View>
</View>
<View style={styles.patternsList}>
{rawPatterns.map((item, idx) => {
const reference = parseNavigableContentReference(item);
const raw = asRecord(item);
const patternTitle =
reference?.label?.trim() ||
asString(raw?.label) ||
asString(raw?.name) ||
`Pattern ${idx + 1}`;
const handlePress = () => {
if (reference) {
router.push(buildContentReferenceRoute(reference) as never);
} else if (raw && typeof raw.target === "object" && raw.target !== null) {
const target = raw.target as Record<string, unknown>;
const mod = asString(target.module_code);
const tpl = asString(target.template_code);
const cid = asString(target.content_id);
if (mod && tpl && cid) {
router.push(
`/modules/${encodeURIComponent(mod)}/${encodeURIComponent(tpl)}/${encodeURIComponent(cid)}` as never,
);
}
}
};
return (
<View key={idx} style={styles.patternCard}>
<Pressable
accessibilityRole="button"
accessibilityLabel={`Open ${patternTitle}`}
onPress={handlePress}
style={({ pressed }) => [styles.patternRow, pressed && styles.pressed]}
>
<View style={styles.iconWrapper}>
<Text style={styles.levelNumber}>{idx + 1}</Text>
</View>
<View style={styles.textContainer}>
<Text style={styles.title}>{patternTitle}</Text>
<Text style={styles.description}>pattern</Text>
</View>
<Ionicons name="chevron-forward" size={20} color="#9CA3AF" />
</Pressable>
</View>
);
})}
</View>
</View>
<ContentLinkAttributeSections
data={data}
definitions={definitions}
presentationAttributes={presentationAttributes}
excludeAttributeKeys={["patterns", "m0016_ct0003.patterns"]}
/>
</ScrollView>
);
}
return ( return (
<ScrollView <ScrollView
contentContainerStyle={styles.content} contentContainerStyle={styles.content}
@ -203,9 +48,9 @@ export function FourLevelsDetailRenderer({
</SectionCard> </SectionCard>
) : null} ) : null}
{clinicalManifestationItems.length > 0 ? ( {clinicalManifestations ? (
<SectionCard title="Clinical Manifestations"> <SectionCard title="Clinical Manifestations">
<BulletList items={clinicalManifestationItems} /> <Paragraphs items={[clinicalManifestations]} />
</SectionCard> </SectionCard>
) : null} ) : null}
@ -227,35 +72,21 @@ export function FourLevelsDetailRenderer({
</SectionCard> </SectionCard>
) : null} ) : null}
{treatmentPrincipleItems.length > 0 ? ( {treatmentPrinciple ? (
<SectionCard title="Treatment Principle">
<BulletList items={treatmentPrincipleItems} />
</SectionCard>
) : treatmentPrinciple ? (
<SectionCard title="Treatment Principle"> <SectionCard title="Treatment Principle">
<Paragraphs items={[treatmentPrinciple]} /> <Paragraphs items={[treatmentPrinciple]} />
</SectionCard> </SectionCard>
) : null} ) : null}
{data.treatment ? ( {treatment ? (
<SectionCard title="Treatment"> <SectionCard title="Treatment">
{typeof data.treatment === "object" ? ( <Paragraphs items={[treatment]} />
<ContentValue value={data.treatment} />
) : treatmentBullets.length > 0 ? (
<BulletList items={treatmentBullets} />
) : (
<Paragraphs items={[treatment]} />
)}
</SectionCard> </SectionCard>
) : null} ) : null}
{explanation ? ( {explanation ? (
<SectionCard title="Explanation"> <SectionCard title="Explanation">
{explanationBullets.length > 0 ? ( <Paragraphs items={[explanation]} />
<BulletList items={explanationBullets} />
) : (
<Paragraphs items={[explanation]} />
)}
</SectionCard> </SectionCard>
) : null} ) : null}
@ -276,81 +107,9 @@ export function FourLevelsDetailRenderer({
const styles = StyleSheet.create({ const styles = StyleSheet.create({
content: { content: {
paddingHorizontal: moderateScale(16), paddingHorizontal: 18,
paddingTop: verticalScale(14), paddingTop: 16,
paddingBottom: verticalScale(40), paddingBottom: 40,
gap: verticalScale(14), gap: 14,
},
patternsSection: {
gap: verticalScale(10),
},
sectionHeaderRow: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
paddingHorizontal: moderateScale(4),
},
sectionHeading: {
fontSize: moderateScale(15),
fontWeight: "700",
color: Colors.textPrimary,
},
countBadge: {
backgroundColor: "#E8F5E9",
paddingHorizontal: moderateScale(10),
paddingVertical: verticalScale(4),
borderRadius: moderateScale(12),
},
countBadgeText: {
fontSize: moderateScale(12),
fontWeight: "600",
color: Colors.primaryDark,
},
patternsList: {
gap: verticalScale(12),
},
patternCard: {
backgroundColor: "#FFFFFF",
borderRadius: moderateScale(18),
borderWidth: 1,
borderColor: "#E2EAE5",
overflow: "hidden",
},
patternRow: {
minHeight: moderateScale(68),
flexDirection: "row",
alignItems: "center",
padding: moderateScale(14),
},
pressed: {
opacity: 0.72,
},
iconWrapper: {
width: moderateScale(40),
height: moderateScale(40),
borderRadius: moderateScale(20),
justifyContent: "center",
alignItems: "center",
backgroundColor: "#E8F5E9",
},
levelNumber: {
fontSize: moderateScale(16),
fontWeight: "800",
color: Colors.primaryDark,
},
textContainer: {
flex: 1,
marginLeft: moderateScale(12),
marginRight: moderateScale(10),
},
title: {
fontSize: moderateScale(15),
fontWeight: "600",
color: Colors.textPrimary,
marginBottom: verticalScale(2),
},
description: {
fontSize: moderateScale(12),
color: Colors.textSecondary,
}, },
}); });

View File

@ -1,8 +1,21 @@
import React from "react"; import React from "react";
import { ScrollView } from "react-native";
import type { DetailRendererProps } from "../../types/renderer.types"; import type { DetailRendererProps } from "../../types/renderer.types";
import { GenericDetailRenderer } from "../GenericDetailRenderer"; import { ContentLinkAttributeSections } from "../shared/ContentLinkAttributeSections";
import { asString } from "../helpers/value";
export function IndexEntryDetailRenderer(props: DetailRendererProps) { import { Hero } from "../shared/Hero"; import { ImageGallery } from "../shared/ImageGallery";
return <GenericDetailRenderer {...props} />; 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>
);
} }

View File

@ -145,10 +145,7 @@ export function MeridianDetailRenderer({
<> <>
<BulletList items={asStringArray(value)} /> <BulletList items={asStringArray(value)} />
{isPresent(data.luo_connecting_vessel) ? ( {isPresent(data.luo_connecting_vessel) ? (
<ObjectSections <ObjectSections value={asRecord(data.luo_connecting_vessel)} />
value={asRecord(data.luo_connecting_vessel)}
withTopDivider
/>
) : null} ) : null}
</> </>
); );
@ -278,6 +275,7 @@ const styles = StyleSheet.create({
lineHeight: 18, lineHeight: 18,
fontWeight: "700", fontWeight: "700",
color: "#536F61", color: "#536F61",
letterSpacing: 0.15, textTransform: "uppercase",
letterSpacing: 0.35,
}, },
}); });

View File

@ -68,7 +68,6 @@ export function MeridianPointsDetailRenderer({
<Hero <Hero
title={rawTitle} title={rawTitle}
subtitle={totalCount ? `${totalCount} ${countLabel}` : undefined} subtitle={totalCount ? `${totalCount} ${countLabel}` : undefined}
tone="blue"
/> />
<View style={styles.list}> <View style={styles.list}>
@ -88,7 +87,6 @@ export function MeridianPointsDetailRenderer({
<StandardIndexCard <StandardIndexCard
title={title} title={title}
subtitle={subtitle} subtitle={subtitle}
tone="blue"
onPress={() => onPress={() =>
router.push(buildContentReferenceRoute(ref) as never) router.push(buildContentReferenceRoute(ref) as never)
} }

View File

@ -1,278 +0,0 @@
import React, { useMemo } from "react";
import {
ActivityIndicator,
Pressable,
ScrollView,
StyleSheet,
Text,
View,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { useRouter } from "expo-router";
import { moderateScale, verticalScale } from "react-native-size-matters";
import { Colors } from "@/theme";
import { useModuleTemplateContentDetailsQuery } from "../../hooks/use-content-queries";
import {
buildContentReferenceRoute,
getNavigableContentReferences,
} from "../../utils/content-reference";
import type { NavigableContentReference } from "../../types/content-reference.types";
import { asNumber, asString, asStringArray, humanizeKey } from "../helpers/value";
import type { DetailRendererProps } from "../../types/renderer.types";
interface CategoryFoodItem {
id: string;
title: string;
subtitle: string | null;
ref: NavigableContentReference;
}
export function NutritionCategoryDetailRenderer({
moduleCode,
content,
data,
}: DetailRendererProps) {
const router = useRouter();
const rawTitle = asString(data.name) || content.title;
const normalizedCategory = rawTitle.toLowerCase().trim();
// Query all food items from m0031_ct0002
const { data: foodData, isLoading } = useModuleTemplateContentDetailsQuery({
module_code: moduleCode || "m0031",
template_code: "m0031_ct0002",
});
const items = useMemo(() => {
// Map of food item details from template m0031_ct0002
const foodMap = new Map<
string,
{
id: string;
title: string;
subtitle: string | null;
ref: NavigableContentReference;
}
>();
if (foodData?.items) {
for (const item of foodData.items) {
const foodName =
asString(item.data.food_name) ||
asString(item.data.name) ||
item.content.title;
const code = asString(item.data.code) || item.content.slug;
const temp = asString(item.data.temperature);
const taste = asStringArray(item.data.taste).join(", ");
const subtitle = [temp, taste].filter(Boolean).join(" · ") || null;
const ref: NavigableContentReference = {
type: "content_ref",
label: foodName,
target: {
module_code: moduleCode || "m0031",
template_code: "m0031_ct0002",
content_id: item.content.id,
},
};
const entry = {
id: item.content.id,
title: humanizeKey(foodName),
subtitle,
ref,
};
if (code) foodMap.set(code.toLowerCase().trim(), entry);
if (foodName) foodMap.set(foodName.toLowerCase().trim(), entry);
if (item.content.id) foodMap.set(item.content.id, entry);
}
}
// 1. Try references from data.food_items
const foodItemRefs = getNavigableContentReferences(data.food_items);
if (foodItemRefs.length > 0) {
return foodItemRefs.map((ref, idx): CategoryFoodItem => {
const contentId = ref.type === "content_ref" ? ref.target.content_id : undefined;
const sourceKey = ref.type === "content_ref" ? ref.target.source_key ?? undefined : undefined;
const key =
ref.label?.toLowerCase().trim() ||
sourceKey?.toLowerCase().trim() ||
contentId;
const info = key ? foodMap.get(key) : undefined;
return {
id: contentId || info?.id || `${ref.label}-${idx}`,
title: info?.title || humanizeKey(ref.label || `Item ${idx + 1}`),
subtitle: info?.subtitle || null,
ref: info?.ref || ref,
};
});
}
// 2. Fallback: filter foodData items by matching category
if (foodData?.items) {
const filtered = foodData.items.filter((item) => {
const itemCat = asString(item.data.category).toLowerCase().trim();
return itemCat === normalizedCategory;
});
return filtered.map((item): CategoryFoodItem => {
const foodName =
asString(item.data.food_name) ||
asString(item.data.name) ||
item.content.title;
const temp = asString(item.data.temperature);
const taste = asStringArray(item.data.taste).join(", ");
const subtitle = [temp, taste].filter(Boolean).join(" · ") || null;
return {
id: item.content.id,
title: humanizeKey(foodName),
subtitle,
ref: {
type: "content_ref",
label: foodName,
target: {
module_code: moduleCode || "m0031",
template_code: "m0031_ct0002",
content_id: item.content.id,
},
},
};
});
}
return [];
}, [foodData, data.food_items, normalizedCategory, moduleCode]);
const totalCount = asNumber(data.content_count) || items.length;
if (isLoading && items.length === 0) {
return (
<View style={styles.center}>
<ActivityIndicator size="large" color={Colors.primary} />
</View>
);
}
return (
<ScrollView
contentContainerStyle={styles.content}
showsVerticalScrollIndicator={false}
>
<Text style={styles.resultCount} accessibilityLiveRegion="polite">
{totalCount} {totalCount === 1 ? "ITEM" : "ITEMS"}
</Text>
<View style={styles.list}>
{items.map((item) => (
<View key={item.id} style={styles.card}>
<Pressable
accessibilityRole="button"
accessibilityLabel={`Open ${item.title}`}
onPress={() => router.push(buildContentReferenceRoute(item.ref) as never)}
style={({ pressed }) => [styles.row, pressed && styles.pressed]}
>
<View style={styles.iconWrapper}>
<Ionicons name="book-outline" size={22} color={Colors.primary} />
</View>
<View style={styles.textContainer}>
<Text style={styles.title}>{item.title}</Text>
{item.subtitle ? (
<Text numberOfLines={2} style={styles.subtitle}>
{item.subtitle}
</Text>
) : null}
</View>
<Ionicons name="chevron-forward" size={20} color="#9CA3AF" />
</Pressable>
</View>
))}
{items.length === 0 && !isLoading ? (
<View style={styles.emptyCard}>
<Text style={styles.emptyText}>No items found in this category.</Text>
</View>
) : null}
</View>
</ScrollView>
);
}
const styles = StyleSheet.create({
content: {
paddingHorizontal: moderateScale(18),
paddingTop: verticalScale(16),
paddingBottom: verticalScale(32),
},
center: {
paddingVertical: verticalScale(40),
alignItems: "center",
justifyContent: "center",
},
resultCount: {
fontSize: moderateScale(12),
fontWeight: "700",
color: Colors.textSecondary,
letterSpacing: 0.2,
marginBottom: verticalScale(12),
marginLeft: moderateScale(4),
},
list: {
gap: verticalScale(12),
},
card: {
backgroundColor: "#FFFFFF",
borderRadius: moderateScale(18),
borderWidth: 1,
borderColor: "#E2EAE5",
overflow: "hidden",
},
row: {
minHeight: moderateScale(68),
flexDirection: "row",
alignItems: "center",
padding: moderateScale(14),
},
pressed: {
opacity: 0.72,
},
iconWrapper: {
width: moderateScale(40),
height: moderateScale(40),
borderRadius: moderateScale(20),
justifyContent: "center",
alignItems: "center",
backgroundColor: "#E8F5E9",
},
textContainer: {
flex: 1,
marginLeft: moderateScale(12),
marginRight: moderateScale(10),
},
title: {
fontSize: moderateScale(15),
fontWeight: "600",
color: Colors.textPrimary,
},
subtitle: {
fontSize: moderateScale(12),
color: Colors.textSecondary,
marginTop: verticalScale(2),
lineHeight: moderateScale(16),
},
emptyCard: {
backgroundColor: "#FFFFFF",
borderRadius: moderateScale(18),
borderWidth: 1,
borderColor: "#E2EAE5",
padding: moderateScale(24),
alignItems: "center",
},
emptyText: {
fontSize: moderateScale(14),
color: Colors.textSecondary,
},
});

View File

@ -5,11 +5,10 @@ import type { DetailRendererProps } from "../../types/renderer.types";
import { ContentLinkAttributeSections } from "../shared/ContentLinkAttributeSections"; import { ContentLinkAttributeSections } from "../shared/ContentLinkAttributeSections";
import { Hero } from "../shared/Hero"; import { Hero } from "../shared/Hero";
import { BulletList } from "../shared/BulletList";
import { SectionCard } from "../shared/SectionCard"; import { SectionCard } from "../shared/SectionCard";
import { Paragraphs } from "../shared/Paragraphs"; import { Paragraphs } from "../shared/Paragraphs";
import { ImageGallery } from "../shared/ImageGallery"; import { ImageGallery } from "../shared/ImageGallery";
import { asString, asStringArray } from "../helpers/value"; import { asString } from "../helpers/value";
export function PathogenicFactorsDetailRenderer({ export function PathogenicFactorsDetailRenderer({
content, content,
@ -23,12 +22,7 @@ export function PathogenicFactorsDetailRenderer({
content.title; content.title;
const overview = asString(data.overview); const overview = asString(data.overview);
const clinicalManifestationsRaw = const clinicalManifestations = asString(data.clinical_manifestations);
data.clinical_manifestations ??
data.clinical_manifestation;
const clinicalManifestationItems = asStringArray(clinicalManifestationsRaw).filter(
(item) => item.trim().length > 0,
);
const analysis = asString(data.analysis); const analysis = asString(data.analysis);
const contentText = asString(data.content); const contentText = asString(data.content);
const defaultImage = asString(data["default image"]); const defaultImage = asString(data["default image"]);
@ -62,9 +56,9 @@ export function PathogenicFactorsDetailRenderer({
</SectionCard> </SectionCard>
) : null} ) : null}
{clinicalManifestationItems.length > 0 ? ( {clinicalManifestations ? (
<SectionCard title="Clinical Manifestations"> <SectionCard title="Clinical Manifestations">
<BulletList items={clinicalManifestationItems} /> <Paragraphs items={[clinicalManifestations]} />
</SectionCard> </SectionCard>
) : null} ) : null}

View File

@ -8,11 +8,9 @@ import type { DetailRendererProps } from "../../types/renderer.types";
import { BackActionContext } from "../../context/BackActionContext"; import { BackActionContext } from "../../context/BackActionContext";
import { ContentLinkAttributeSections } from "../shared/ContentLinkAttributeSections"; import { ContentLinkAttributeSections } from "../shared/ContentLinkAttributeSections";
import { Hero } from "../shared/Hero"; import { Hero } from "../shared/Hero";
import { OverviewCard } from "../shared/OverviewCard";
import { SectionCard } from "../shared/SectionCard"; import { SectionCard } from "../shared/SectionCard";
import { BulletList } from "../shared/BulletList";
import { Paragraphs } from "../shared/Paragraphs"; import { Paragraphs } from "../shared/Paragraphs";
import { asString, asStringArray, humanizeKey } from "../helpers/value"; import { asString, humanizeKey } from "../helpers/value";
const RESERVED_METADATA_KEYS = new Set([ const RESERVED_METADATA_KEYS = new Set([
"name", "name",
@ -38,51 +36,12 @@ interface PatternItem {
interface ParsedNode { interface ParsedNode {
overview?: string; overview?: string;
clinicalItems: string[]; clinical?: string;
analysis?: string; analysis?: string;
subItems: PatternItem[]; subItems: PatternItem[];
otherTextEntries: Array<{ key: string; text: string }>; otherTextEntries: Array<{ key: string; text: string }>;
} }
function parseClinicalManifestations(raw: unknown): string[] {
if (Array.isArray(raw)) {
return asStringArray(raw);
}
const text = asString(raw).trim();
if (!text) return [];
// Check if string is semicolon or newline separated
if (text.includes("\n")) {
return text
.split("\n")
.map((s) => s.replace(/^[•\-\*\d+\.]\s*/, "").trim())
.filter((s) => s.length > 0);
}
// If semicolon separated
if (text.includes(";")) {
return text
.split(";")
.map((s) => s.trim().replace(/^and\s+/i, ""))
.filter((s) => s.length > 0);
}
// Split by comma outside parentheses
const parts = text.split(/,\s*(?![^()]*\))/);
if (parts.length > 1) {
return parts
.map((s) => s.trim().replace(/\.$/, "").replace(/^and\s+/i, ""))
.filter((s) => s.length > 0);
}
return [text];
}
const DEFAULT_CATEGORY_FALLBACKS: Record<string, string> = {
qi_and_blood:
"Qi and blood are mutually dependent. Qi generates, moves, and holds blood, while blood nourishes and carries qi. Pathological changes often involve both substances concurrently, manifesting as combined patterns of deficiency and stasis.",
};
function extractCategoryOverview(data: Record<string, unknown>, categoryCode: string): string { function extractCategoryOverview(data: Record<string, unknown>, categoryCode: string): string {
const normalizedCode = categoryCode.toLowerCase().replace(/[^a-z0-9_]/g, "_"); const normalizedCode = categoryCode.toLowerCase().replace(/[^a-z0-9_]/g, "_");
@ -112,10 +71,6 @@ function extractCategoryOverview(data: Record<string, unknown>, categoryCode: st
return data.content.trim(); return data.content.trim();
} }
if (DEFAULT_CATEGORY_FALLBACKS[normalizedCode]) {
return DEFAULT_CATEGORY_FALLBACKS[normalizedCode];
}
return ""; return "";
} }
@ -166,13 +121,12 @@ function parseNode(raw: Record<string, unknown>): ParsedNode {
(typeof raw.content === "string" ? raw.content.trim() : undefined) || (typeof raw.content === "string" ? raw.content.trim() : undefined) ||
(typeof raw.overview === "string" ? raw.overview.trim() : undefined); (typeof raw.overview === "string" ? raw.overview.trim() : undefined);
const clinicalRaw = const clinical =
contentTarget["Clinical manifestations"] ?? asString(contentTarget["Clinical manifestations"]) ||
contentTarget.clinical_manifestations ?? asString(contentTarget.clinical_manifestations) ||
contentTarget.clinical_manifestation ?? asString(contentTarget.clinical_manifestation) ||
raw["Clinical manifestations"] ?? asString(raw["Clinical manifestations"]) ||
raw.clinical_manifestations; asString(raw.clinical_manifestations);
const clinicalItems = parseClinicalManifestations(clinicalRaw);
const analysis = const analysis =
asString(contentTarget.Analysis) || asString(contentTarget.Analysis) ||
@ -207,7 +161,7 @@ function parseNode(raw: Record<string, unknown>): ParsedNode {
return { return {
overview: overview || undefined, overview: overview || undefined,
clinicalItems, clinical: clinical || undefined,
analysis: analysis || undefined, analysis: analysis || undefined,
subItems, subItems,
otherTextEntries, otherTextEntries,
@ -273,9 +227,9 @@ export function QiBloodDetailRenderer({
) : null} ) : null}
{/* 2. Clinical Manifestations Card */} {/* 2. Clinical Manifestations Card */}
{parsed.clinicalItems.length > 0 ? ( {parsed.clinical ? (
<SectionCard title="Clinical Manifestations"> <SectionCard title="Clinical Manifestations">
<BulletList items={parsed.clinicalItems} /> <Paragraphs items={[parsed.clinical]} />
</SectionCard> </SectionCard>
) : null} ) : null}
@ -339,7 +293,15 @@ export function QiBloodDetailRenderer({
<Hero title={categoryTitle} /> <Hero title={categoryTitle} />
{/* Category Overview Card */} {/* Category Overview Card */}
{categoryOverview ? <OverviewCard text={categoryOverview} /> : null} {categoryOverview ? (
<View style={styles.overviewCard}>
<View style={styles.overviewHeader}>
<Ionicons name="information-circle" size={20} color={Colors.primary} />
<Text style={styles.overviewTitle}>Overview</Text>
</View>
<Text style={styles.overviewText}>{categoryOverview}</Text>
</View>
) : null}
{/* Numbered Patterns List */} {/* Numbered Patterns List */}
{rootPatterns.length > 0 ? ( {rootPatterns.length > 0 ? (
@ -383,6 +345,29 @@ const styles = StyleSheet.create({
paddingBottom: verticalScale(40), paddingBottom: verticalScale(40),
gap: verticalScale(14), gap: verticalScale(14),
}, },
overviewCard: {
backgroundColor: "#FFFFFF",
borderRadius: moderateScale(16),
borderWidth: 1,
borderColor: "#E2EAE5",
padding: moderateScale(18),
},
overviewHeader: {
flexDirection: "row",
alignItems: "center",
marginBottom: verticalScale(10),
gap: moderateScale(8),
},
overviewTitle: {
fontSize: moderateScale(16),
fontWeight: "700",
color: Colors.textPrimary,
},
overviewText: {
fontSize: moderateScale(14),
lineHeight: moderateScale(22),
color: Colors.textSecondary,
},
patternsContainer: { patternsContainer: {
gap: verticalScale(10), gap: verticalScale(10),
}, },

View File

@ -1,18 +1,8 @@
import React, { useMemo } from "react"; import React from "react";
import { ScrollView, StyleSheet } from "react-native"; import { ScrollView, StyleSheet } from "react-native";
import type { DetailRendererProps } from "../../types/renderer.types"; import type { DetailRendererProps } from "../../types/renderer.types";
import { import { asString, humanizeKey } from "../helpers/value";
asString,
buildDefinitionLabelMap,
humanizeKey,
resolveAttributeLabel,
} from "../helpers/value";
import {
findAttributePresentationRule,
isEmptyValue,
presentationDisplayOrder,
} from "../../utils/attribute-presentation";
import { ContentLinkAttributeSections } from "../shared/ContentLinkAttributeSections"; import { ContentLinkAttributeSections } from "../shared/ContentLinkAttributeSections";
import { ContentValue } from "../shared/ContentValue"; import { ContentValue } from "../shared/ContentValue";
import { Hero } from "../shared/Hero"; import { Hero } from "../shared/Hero";
@ -29,40 +19,18 @@ const CATALOG_METADATA_KEYS = new Set([
"link", "link",
"point_images", "point_images",
"default_image_id", "default_image_id",
"stage_overview",
]); ]);
export function SixStagesDetailRenderer({ export function SixStagesDetailRenderer({
content, content,
data, data,
definitions,
presentationAttributes, presentationAttributes,
}: DetailRendererProps) { }: DetailRendererProps) {
const rawTitle = const title =
asString(data.name) || asString(data.name) ||
asString(data.title) || asString(data.title) ||
content.title || content.title ||
"Six Stages"; "Six Stages";
const title = humanizeKey(rawTitle);
const orderedSections = useMemo(() => {
const definitionByLabel = buildDefinitionLabelMap(definitions);
return Object.entries(data)
.filter(
([key, value]) =>
!RESERVED_KEYS.has(key) &&
!CATALOG_METADATA_KEYS.has(key) &&
!isEmptyValue(value),
)
.map(([key, value]) => {
const rule = findAttributePresentationRule(key, presentationAttributes);
const order = presentationDisplayOrder(rule);
const label = resolveAttributeLabel(key, definitionByLabel);
return { key, value, order, label };
})
.sort((a, b) => a.order - b.order || a.label.localeCompare(b.label));
}, [data, definitions, presentationAttributes]);
return ( return (
<ScrollView <ScrollView
@ -71,11 +39,13 @@ export function SixStagesDetailRenderer({
> >
<Hero title={title} subtitle={content.summary ?? undefined} /> <Hero title={title} subtitle={content.summary ?? undefined} />
{orderedSections.map(({ key, value, label }) => ( {Object.entries(data)
<SectionCard key={key} title={label}> .filter(([key]) => !RESERVED_KEYS.has(key) && !CATALOG_METADATA_KEYS.has(key))
<ContentValue value={value} /> .map(([key, value]) => (
</SectionCard> <SectionCard key={key} title={humanizeKey(key)}>
))} <ContentValue value={value} />
</SectionCard>
))}
<ContentLinkAttributeSections <ContentLinkAttributeSections
data={data} data={data}

View File

@ -1,62 +1,25 @@
import React, { useMemo } from "react"; import React from "react";
import { ScrollView, StyleSheet } from "react-native"; import { ScrollView, StyleSheet } from "react-native";
import type { DetailRendererProps } from "../../types/renderer.types"; import type { DetailRendererProps } from "../../types/renderer.types";
import { import { asString, humanizeKey } from "../helpers/value";
asString,
buildDefinitionLabelMap,
humanizeKey,
resolveAttributeLabel,
} from "../helpers/value";
import {
findAttributePresentationRule,
isEmptyValue,
presentationDisplayOrder,
} from "../../utils/attribute-presentation";
import { ContentLinkAttributeSections } from "../shared/ContentLinkAttributeSections"; import { ContentLinkAttributeSections } from "../shared/ContentLinkAttributeSections";
import { ContentValue } from "../shared/ContentValue"; import { ContentValue } from "../shared/ContentValue";
import { Hero } from "../shared/Hero"; import { Hero } from "../shared/Hero";
import { SectionCard } from "../shared/SectionCard"; import { SectionCard } from "../shared/SectionCard";
const RESERVED_KEYS = new Set([ const EXCLUDED_KEYS = new Set(["code"]);
"id",
"name",
"title",
"code",
"sort_order",
"link",
]);
export function TcmPatternDetailRenderer({ export function TcmPatternDetailRenderer({
content, content,
data, data,
definitions,
presentationAttributes, presentationAttributes,
}: DetailRendererProps) { }: DetailRendererProps) {
const rawTitle = const title =
asString(data.name) || asString(data.name) ||
asString(data.title) || asString(data.title) ||
content.title || content.title ||
"TCM Pattern"; "TCM Pattern";
const title = humanizeKey(rawTitle);
const orderedSections = useMemo(() => {
const definitionByLabel = buildDefinitionLabelMap(definitions);
return Object.entries(data)
.filter(
([key, value]) =>
!RESERVED_KEYS.has(key) &&
!isEmptyValue(value),
)
.map(([key, value]) => {
const rule = findAttributePresentationRule(key, presentationAttributes);
const order = presentationDisplayOrder(rule);
const label = resolveAttributeLabel(key, definitionByLabel);
return { key, value, order, label };
})
.sort((a, b) => a.order - b.order || a.label.localeCompare(b.label));
}, [data, definitions, presentationAttributes]);
return ( return (
<ScrollView <ScrollView
@ -65,11 +28,13 @@ export function TcmPatternDetailRenderer({
> >
<Hero title={title} subtitle={content.summary ?? undefined} /> <Hero title={title} subtitle={content.summary ?? undefined} />
{orderedSections.map(({ key, value, label }) => ( {Object.entries(data)
<SectionCard key={key} title={label}> .filter(([key]) => !EXCLUDED_KEYS.has(key))
<ContentValue value={value} /> .map(([key, value]) => (
</SectionCard> <SectionCard key={key} title={humanizeKey(key)}>
))} <ContentValue value={value} />
</SectionCard>
))}
<ContentLinkAttributeSections <ContentLinkAttributeSections
data={data} data={data}

View File

@ -7,52 +7,17 @@ import { Colors } from "@/theme";
import type { DetailRendererProps } from "../../types/renderer.types"; import type { DetailRendererProps } from "../../types/renderer.types";
import { BackActionContext } from "../../context/BackActionContext"; import { BackActionContext } from "../../context/BackActionContext";
import { Hero } from "../shared/Hero"; import { Hero } from "../shared/Hero";
import { OverviewCard } from "../shared/OverviewCard";
import { SectionCard } from "../shared/SectionCard"; import { SectionCard } from "../shared/SectionCard";
import { Paragraphs } from "../shared/Paragraphs"; import { Paragraphs } from "../shared/Paragraphs";
import { BulletList } from "../shared/BulletList"; import { asString } from "../helpers/value";
import { ContentValue } from "../shared/ContentValue";
import { asString, asStringArray, formatPatternTitle } from "../helpers/value";
import { useContentSearchInfiniteQuery } from "../../hooks/use-content-search-infinite-query"; import { useContentSearchInfiniteQuery } from "../../hooks/use-content-search-infinite-query";
interface PatternData { interface PatternData {
name: string; name: string;
code?: string; code?: string;
clinicalManifestation?: string | string[]; clinicalManifestation?: string;
pathology?: string; pathology?: string;
treatmentPrinciple?: string | string[]; treatment?: string;
treatment?: unknown;
}
function parseBullets(raw: unknown): string[] {
if (Array.isArray(raw)) {
return asStringArray(raw);
}
const text = asString(raw).trim();
if (!text) return [];
if (text.includes("\n")) {
return text
.split("\n")
.map((s) => s.replace(/^[•\-\*\d+\.]\s*/, "").trim())
.filter((s) => s.length > 0);
}
if (text.includes(";")) {
return text
.split(";")
.map((s) => s.trim().replace(/^and\s+/i, ""))
.filter((s) => s.length > 0);
}
const parts = text.split(/,\s*(?![^()]*\))/);
if (parts.length > 1) {
return parts
.map((s) => s.trim().replace(/\.$/, "").replace(/^and\s+/i, ""))
.filter((s) => s.length > 0);
}
return [text];
} }
interface BurnerCategory { interface BurnerCategory {
@ -73,7 +38,7 @@ const BURNER_CONFIGS: Array<{ key: string; title: string }> = [
// Embedded fallback patterns for guaranteed zero-latency / offline rendering // Embedded fallback patterns for guaranteed zero-latency / offline rendering
const FALLBACK_PATTERNS: Record<string, PatternData> = { const FALLBACK_PATTERNS: Record<string, PatternData> = {
"wind_heat_in_the_lungs_defensive_qi_portion": { "wind_heat_in_the_lungs_defensive_qi_portion": {
name: "Wind-Heat in the Lung's Defensive Qi portion", name: "Wind-Heat in the Lungs’ Defensive Qi portion",
clinicalManifestation: clinicalManifestation:
"Fever, aversion to cold, headache, sore throat, slight sweating, runny nose with yellow discharge, swollen tonsils, body aches, slight thirst", "Fever, aversion to cold, headache, sore throat, slight sweating, runny nose with yellow discharge, swollen tonsils, body aches, slight thirst",
pathology: pathology:
@ -155,9 +120,7 @@ function extractBurnerList(data: Record<string, unknown>, burnerKey: string): st
for (const [k, v] of Object.entries(data)) { for (const [k, v] of Object.entries(data)) {
const normK = normalizeKey(k); const normK = normalizeKey(k);
if (normK === normTarget && Array.isArray(v)) { if (normK === normTarget && Array.isArray(v)) {
return v return v.map((item) => asString(item).trim()).filter((item) => item.length > 0);
.map((item) => formatPatternTitle(asString(item).trim()))
.filter((item) => item.length > 0);
} }
} }
return []; return [];
@ -220,42 +183,31 @@ export function ThreeBurnersDetailRenderer({
// 1. Seed fallback patterns // 1. Seed fallback patterns
for (const p of Object.values(FALLBACK_PATTERNS)) { for (const p of Object.values(FALLBACK_PATTERNS)) {
map.set(normalizeKey(p.name), { map.set(normalizeKey(p.name), p);
...p,
clinicalManifestation: parseBullets(p.clinicalManifestation),
});
} }
// 2. Hydrate from live search query // 2. Hydrate from live search query
const items = patternsQuery.data?.pages?.flatMap((p) => p.items) ?? []; const items = patternsQuery.data?.pages?.flatMap((p) => p.items) ?? [];
for (const it of items) { for (const it of items) {
const a = it.attributes as Record<string, unknown>; const a = it.attributes as Record<string, unknown>;
const rawName = asString(a.name) || it.title; const name = asString(a.name) || it.title;
if (!rawName) continue; if (!name) continue;
const name = formatPatternTitle(rawName);
const clinicalRaw = const clinical =
a["clinical menifestation"] ?? asString(a["clinical menifestation"]) ||
a["clinical manifestation"] ?? asString(a["clinical manifestation"]) ||
a.clinical_manifestations ?? asString(a.clinical_manifestations) ||
a.clinical_manifestation; asString(a.clinical_manifestation);
const clinical = parseBullets(clinicalRaw);
const pathology = asString(a.pathology); const pathology = asString(a.pathology);
const treatmentPrincipleRaw = const treatment = asString(a.treatment);
a.treatment_principle ??
a["treatment principle"] ??
a.treatmentPrinciple;
const treatmentPrinciple = parseBullets(treatmentPrincipleRaw);
const treatment = a.treatment ?? a["treatment"];
map.set(normalizeKey(name), { map.set(normalizeKey(name), {
name, name,
code: asString(a.code) || undefined, code: asString(a.code) || undefined,
clinicalManifestation: clinical.length > 0 ? clinical : undefined, clinicalManifestation: clinical || undefined,
pathology: pathology || undefined, pathology: pathology || undefined,
treatmentPrinciple: treatmentPrinciple.length > 0 ? treatmentPrinciple : undefined, treatment: treatment || undefined,
treatment: treatment ?? undefined,
}); });
} }
@ -288,42 +240,25 @@ export function ThreeBurnersDetailRenderer({
const activePatternData: PatternData | null = useMemo(() => { const activePatternData: PatternData | null = useMemo(() => {
if (isDirectLeafPattern) { if (isDirectLeafPattern) {
const rawName = asString(data.name) || content.title || "Three Burners Pattern"; const name = asString(data.name) || content.title || "Three Burners Pattern";
const name = formatPatternTitle(rawName);
const clinicalRaw =
data["clinical menifestation"] ??
data["clinical manifestation"] ??
data.clinical_manifestations ??
data.clinical_manifestation;
const clinical = parseBullets(clinicalRaw);
const treatmentPrincipleRaw =
data.treatment_principle ??
data["treatment principle"] ??
data.treatmentPrinciple;
const treatmentPrinciple = parseBullets(treatmentPrincipleRaw);
return { return {
name, name,
code: asString(data.code) || undefined, code: asString(data.code) || undefined,
clinicalManifestation: clinical.length > 0 ? clinical : undefined, clinicalManifestation:
asString(data["clinical menifestation"]) ||
asString(data["clinical manifestation"]) ||
asString(data.clinical_manifestations),
pathology: asString(data.pathology) || undefined, pathology: asString(data.pathology) || undefined,
treatmentPrinciple: treatmentPrinciple.length > 0 ? treatmentPrinciple : undefined, treatment: asString(data.treatment) || undefined,
treatment: data.treatment ?? undefined,
}; };
} }
if (!selectedPatternName) return null; if (!selectedPatternName) return null;
const found = patternMap.get(normalizeKey(selectedPatternName)); return (
if (found) { patternMap.get(normalizeKey(selectedPatternName)) || {
return { name: selectedPatternName,
...found, }
name: formatPatternTitle(found.name), );
};
}
return {
name: formatPatternTitle(selectedPatternName),
};
}, [isDirectLeafPattern, data, content.title, selectedPatternName, patternMap]); }, [isDirectLeafPattern, data, content.title, selectedPatternName, patternMap]);
// Connect drilldown navigation to the top-header back button // Connect drilldown navigation to the top-header back button
@ -347,20 +282,9 @@ export function ThreeBurnersDetailRenderer({
// SCREEN 3: Pattern Leaf Detail Screen // SCREEN 3: Pattern Leaf Detail Screen
// ---------------------------------------------------- // ----------------------------------------------------
if (activePatternData && (selectedPatternName || isDirectLeafPattern)) { if (activePatternData && (selectedPatternName || isDirectLeafPattern)) {
const treatmentRaw = activePatternData.treatment; const { principles, acupuncture } = parseTreatment(
const { principles, acupuncture } = activePatternData.treatment || "",
typeof treatmentRaw === "string" );
? parseTreatment(treatmentRaw)
: { principles: [], acupuncture: [] };
const rawPrinciples =
activePatternData.treatmentPrinciple &&
(Array.isArray(activePatternData.treatmentPrinciple)
? activePatternData.treatmentPrinciple
: parseBullets(activePatternData.treatmentPrinciple));
const allPrinciples =
rawPrinciples && rawPrinciples.length > 0 ? rawPrinciples : principles;
return ( return (
<ScrollView <ScrollView
@ -369,41 +293,48 @@ export function ThreeBurnersDetailRenderer({
> >
<Hero title={activePatternData.name} /> <Hero title={activePatternData.name} />
{/* 1. Pathology Card */} {/* 1. Clinical Manifestations Card */}
{activePatternData.clinicalManifestation ? (
<SectionCard title="Clinical Manifestations">
<Paragraphs items={[activePatternData.clinicalManifestation]} />
</SectionCard>
) : null}
{/* 2. Pathology Card */}
{activePatternData.pathology ? ( {activePatternData.pathology ? (
<SectionCard title="Pathology"> <SectionCard title="Pathology">
<Paragraphs items={[activePatternData.pathology]} /> <Paragraphs items={[activePatternData.pathology]} />
</SectionCard> </SectionCard>
) : null} ) : null}
{/* 2. Clinical Manifestations Card */} {/* 3. Treatment Card */}
{activePatternData.clinicalManifestation ? ( {activePatternData.treatment ? (
<SectionCard title="Clinical Manifestations">
<BulletList
items={
Array.isArray(activePatternData.clinicalManifestation)
? activePatternData.clinicalManifestation
: parseBullets(activePatternData.clinicalManifestation)
}
/>
</SectionCard>
) : null}
{/* 3. Treatment Principle Card */}
{allPrinciples && allPrinciples.length > 0 ? (
<SectionCard title="Treatment Principle">
<BulletList items={allPrinciples} />
</SectionCard>
) : null}
{/* 4. Treatment Card */}
{treatmentRaw ? (
<SectionCard title="Treatment"> <SectionCard title="Treatment">
{typeof treatmentRaw === "object" ? ( {principles.length > 0 ? (
<ContentValue value={treatmentRaw} /> <View style={styles.subSection}>
) : ( <Text style={styles.subSectionTitle}>Treatment Principle:</Text>
<Paragraphs items={[acupuncture.length > 0 ? acupuncture.join("\n") : String(treatmentRaw)]} /> {principles.map((p, i) => (
)} <Text key={i} style={styles.bulletItem}>
• {p}
</Text>
))}
</View>
) : null}
{acupuncture.length > 0 ? (
<View style={[styles.subSection, principles.length > 0 && styles.subSectionSpacing]}>
<Text style={styles.subSectionTitle}>Acupuncture Points:</Text>
{acupuncture.map((a, i) => (
<Text key={i} style={styles.bodyText}>
{a}
</Text>
))}
</View>
) : null}
{principles.length === 0 && acupuncture.length === 0 ? (
<Paragraphs items={[activePatternData.treatment]} />
) : null}
</SectionCard> </SectionCard>
) : null} ) : null}
@ -424,28 +355,25 @@ export function ThreeBurnersDetailRenderer({
<View style={styles.patternsContainer}> <View style={styles.patternsContainer}>
<Text style={styles.sectionHeading}>Patterns</Text> <Text style={styles.sectionHeading}>Patterns</Text>
{selectedBurner.patterns.map((patternName, idx) => { {selectedBurner.patterns.map((patternName, idx) => (
const formattedTitle = formatPatternTitle(patternName); <Pressable
return ( key={patternName}
<Pressable accessibilityRole="button"
key={patternName} accessibilityLabel={`Open ${patternName}`}
accessibilityRole="button" onPress={() => setSelectedPatternName(patternName)}
accessibilityLabel={`Open ${formattedTitle}`} style={({ pressed }) => [styles.patternRow, pressed && styles.pressed]}
onPress={() => setSelectedPatternName(patternName)} >
style={({ pressed }) => [styles.patternRow, pressed && styles.pressed]} <View style={styles.numberBadge}>
> <Text style={styles.numberText}>{idx + 1}</Text>
<View style={styles.numberBadge}> </View>
<Text style={styles.numberText}>{idx + 1}</Text>
</View>
<View style={styles.patternTitleContainer}> <View style={styles.patternTitleContainer}>
<Text style={styles.patternTitle}>{formattedTitle}</Text> <Text style={styles.patternTitle}>{patternName}</Text>
</View> </View>
<Ionicons name="chevron-forward" size={20} color="#9CA3AF" /> <Ionicons name="chevron-forward" size={20} color="#9CA3AF" />
</Pressable> </Pressable>
); ))}
})}
</View> </View>
</ScrollView> </ScrollView>
@ -470,7 +398,15 @@ export function ThreeBurnersDetailRenderer({
<Hero title="Three Burners" /> <Hero title="Three Burners" />
{/* Overview Card */} {/* Overview Card */}
{overviewText ? <OverviewCard text={overviewText} /> : null} {overviewText ? (
<View style={styles.overviewCard}>
<View style={styles.overviewHeader}>
<Ionicons name="information-circle" size={20} color={Colors.primary} />
<Text style={styles.overviewTitle}>Overview</Text>
</View>
<Text style={styles.overviewText}>{overviewText}</Text>
</View>
) : null}
{/* Burner Categories (1. Upper Burner, 2. Middle Burner, 3. Lower Burner) */} {/* Burner Categories (1. Upper Burner, 2. Middle Burner, 3. Lower Burner) */}
<View style={styles.patternsContainer}> <View style={styles.patternsContainer}>
@ -510,6 +446,29 @@ const styles = StyleSheet.create({
paddingBottom: verticalScale(40), paddingBottom: verticalScale(40),
gap: verticalScale(14), gap: verticalScale(14),
}, },
overviewCard: {
backgroundColor: "#FFFFFF",
borderRadius: moderateScale(16),
borderWidth: 1,
borderColor: "#E2EAE5",
padding: moderateScale(16),
},
overviewHeader: {
flexDirection: "row",
alignItems: "center",
marginBottom: verticalScale(8),
gap: moderateScale(8),
},
overviewTitle: {
fontSize: moderateScale(16),
fontWeight: "700",
color: Colors.textPrimary,
},
overviewText: {
fontSize: moderateScale(13),
lineHeight: verticalScale(20),
color: Colors.textSecondary,
},
patternsContainer: { patternsContainer: {
gap: verticalScale(10), gap: verticalScale(10),
}, },
@ -586,9 +545,6 @@ const styles = StyleSheet.create({
}, },
subSectionSpacing: { subSectionSpacing: {
marginTop: verticalScale(12), marginTop: verticalScale(12),
paddingTop: verticalScale(12),
borderTopWidth: StyleSheet.hairlineWidth,
borderTopColor: "#E8ECEF",
}, },
subSectionTitle: { subSectionTitle: {
fontSize: moderateScale(13), fontSize: moderateScale(13),

View File

@ -7,43 +7,26 @@ import { Colors } from "@/theme";
import type { DetailRendererProps } from "../../types/renderer.types"; import type { DetailRendererProps } from "../../types/renderer.types";
import { BackActionContext } from "../../context/BackActionContext"; import { BackActionContext } from "../../context/BackActionContext";
import { Hero } from "../shared/Hero"; import { Hero } from "../shared/Hero";
import { OverviewCard } from "../shared/OverviewCard";
import { SectionCard } from "../shared/SectionCard"; import { SectionCard } from "../shared/SectionCard";
import { Paragraphs } from "../shared/Paragraphs"; import { Paragraphs } from "../shared/Paragraphs";
import { BulletList } from "../shared/BulletList"; import { asString } from "../helpers/value";
import { asString, asStringArray } from "../helpers/value";
import { useContentSearchInfiniteQuery } from "../../hooks/use-content-search-infinite-query"; import { useContentSearchInfiniteQuery } from "../../hooks/use-content-search-infinite-query";
interface ConnectingChannelDetails { interface ConnectingChannelDetails {
empty?: string[]; empty?: string;
full?: string[]; full?: string;
} }
interface ChannelData { interface ChannelData {
name: string; name: string;
code?: string; code?: string;
mainChannel?: string[]; mainChannel?: string;
connectingChannel?: ConnectingChannelDetails | string[]; connectingChannel?: ConnectingChannelDetails | string;
muscleChannel?: string[]; muscleChannel?: string;
greatConnectingChannelOfSpleen?: string[]; greatConnectingChannelOfSpleen?: string;
} }
interface RawChannelData { const FALLBACK_CHANNELS: ChannelData[] = [
name: string;
code?: string;
mainChannel?: string | string[];
connectingChannel?:
| {
empty?: string | string[];
full?: string | string[];
}
| string
| string[];
muscleChannel?: string | string[];
greatConnectingChannelOfSpleen?: string | string[];
}
const FALLBACK_CHANNELS: RawChannelData[] = [
{ {
name: "Lungs", name: "Lungs",
code: "lungs", code: "lungs",
@ -234,74 +217,23 @@ function normalizeKey(str: string): string {
return str.toLowerCase().replace(/[^a-z0-9]/g, ""); return str.toLowerCase().replace(/[^a-z0-9]/g, "");
} }
function parseBullets(raw: unknown): string[] { function parseConnectingChannel(val: unknown): ConnectingChannelDetails | string | undefined {
if (Array.isArray(raw)) {
return asStringArray(raw);
}
const text = asString(raw).trim();
if (!text) return [];
if (text.includes("\n")) {
return text
.split("\n")
.map((s) => s.replace(/^[•\-\*\d+\.]\s*/, "").trim())
.filter((s) => s.length > 0);
}
if (text.includes(";")) {
return text
.split(";")
.map((s) => s.trim().replace(/^and\s+/i, ""))
.filter((s) => s.length > 0);
}
const parts = text.split(/,\s*(?![^()]*\))/);
if (parts.length > 1) {
return parts
.map((s) => s.trim().replace(/\.$/, "").replace(/^and\s+/i, ""))
.filter((s) => s.length > 0);
}
return [text];
}
function parseConnectingChannel(val: unknown): ConnectingChannelDetails | string[] | undefined {
if (!val) return undefined; if (!val) return undefined;
if (Array.isArray(val)) { if (typeof val === "string") return val;
const arr = parseBullets(val);
return arr.length > 0 ? arr : undefined;
}
if (typeof val === "string") {
const bullets = parseBullets(val);
return bullets.length > 0 ? bullets : undefined;
}
if (typeof val === "object") { if (typeof val === "object") {
const obj = val as Record<string, unknown>; const obj = val as Record<string, unknown>;
const empty = parseBullets(obj.empty); const empty = asString(obj.empty);
const full = parseBullets(obj.full); const full = asString(obj.full);
if (empty.length > 0 || full.length > 0) { if (empty || full) {
return { return {
empty: empty.length > 0 ? empty : undefined, empty: empty || undefined,
full: full.length > 0 ? full : undefined, full: full || undefined,
}; };
} }
} }
return undefined; return undefined;
} }
function toChannelData(raw: RawChannelData): ChannelData {
return {
name: raw.name,
code: raw.code,
mainChannel: raw.mainChannel ? parseBullets(raw.mainChannel) : undefined,
connectingChannel: parseConnectingChannel(raw.connectingChannel),
muscleChannel: raw.muscleChannel ? parseBullets(raw.muscleChannel) : undefined,
greatConnectingChannelOfSpleen: raw.greatConnectingChannelOfSpleen
? parseBullets(raw.greatConnectingChannelOfSpleen)
: undefined,
};
}
export function TwelveChannelsDetailRenderer({ export function TwelveChannelsDetailRenderer({
content, content,
data, data,
@ -327,10 +259,9 @@ export function TwelveChannelsDetailRenderer({
// 1. Seed fallback channels // 1. Seed fallback channels
for (const ch of FALLBACK_CHANNELS) { for (const ch of FALLBACK_CHANNELS) {
const parsed = toChannelData(ch); map.set(normalizeKey(ch.name), ch);
map.set(normalizeKey(parsed.name), parsed); if (ch.code) map.set(normalizeKey(ch.code), ch);
if (parsed.code) map.set(normalizeKey(parsed.code), parsed); list.push(ch);
list.push(parsed);
} }
// 2. Overlay live queried items if available // 2. Overlay live queried items if available
@ -341,29 +272,27 @@ export function TwelveChannelsDetailRenderer({
const name = asString(a.name) || item.title; const name = asString(a.name) || item.title;
if (!name) continue; if (!name) continue;
const mainChannel = parseBullets(a.main_channel); const mainChannel = asString(a.main_channel);
const connectingChannel = parseConnectingChannel(a.connecting_channel); const connectingChannel = parseConnectingChannel(a.connecting_channel);
const muscleChannel = parseBullets(a.muscle_channel); const muscleChannel = asString(a.muscle_channel);
const greatConnecting = a.great_connecting_channel_of_the_spleen; const greatConnecting = a.great_connecting_channel_of_the_spleen;
let greatConnectingBullets: string[] | undefined; let greatConnectingStr: string | undefined;
if (typeof greatConnecting === "object" && greatConnecting !== null) { if (typeof greatConnecting === "object" && greatConnecting !== null) {
const g = parseBullets( greatConnectingStr = asString(
(greatConnecting as Record<string, unknown>).clinical_manifestations, (greatConnecting as Record<string, unknown>).clinical_manifestations,
); );
if (g.length > 0) greatConnectingBullets = g; } else if (typeof greatConnecting === "string") {
} else if (greatConnecting) { greatConnectingStr = greatConnecting;
const g = parseBullets(greatConnecting);
if (g.length > 0) greatConnectingBullets = g;
} }
const channelData: ChannelData = { const channelData: ChannelData = {
name, name,
code: asString(a.code) || item.slug, code: asString(a.code) || item.slug,
mainChannel: mainChannel.length > 0 ? mainChannel : undefined, mainChannel: mainChannel || undefined,
connectingChannel, connectingChannel,
muscleChannel: muscleChannel.length > 0 ? muscleChannel : undefined, muscleChannel: muscleChannel || undefined,
greatConnectingChannelOfSpleen: greatConnectingBullets, greatConnectingChannelOfSpleen: greatConnectingStr || undefined,
}; };
const key = normalizeKey(name); const key = normalizeKey(name);
@ -395,29 +324,23 @@ export function TwelveChannelsDetailRenderer({
const activeChannelData: ChannelData | null = useMemo(() => { const activeChannelData: ChannelData | null = useMemo(() => {
if (isDirectLeafChannel) { if (isDirectLeafChannel) {
const name = asString(data.name) || content.title || "Twelve Channels"; const name = asString(data.name) || content.title || "Twelve Channels";
const mainChannel = parseBullets(data.main_channel);
const connectingChannel = parseConnectingChannel(data.connecting_channel);
const muscleChannel = parseBullets(data.muscle_channel);
const greatConnecting = data.great_connecting_channel_of_the_spleen; const greatConnecting = data.great_connecting_channel_of_the_spleen;
let greatConnectingBullets: string[] | undefined; let greatConnectingStr: string | undefined;
if (typeof greatConnecting === "object" && greatConnecting !== null) { if (typeof greatConnecting === "object" && greatConnecting !== null) {
const g = parseBullets( greatConnectingStr = asString(
(greatConnecting as Record<string, unknown>).clinical_manifestations, (greatConnecting as Record<string, unknown>).clinical_manifestations,
); );
if (g.length > 0) greatConnectingBullets = g; } else if (typeof greatConnecting === "string") {
} else if (greatConnecting) { greatConnectingStr = greatConnecting;
const g = parseBullets(greatConnecting);
if (g.length > 0) greatConnectingBullets = g;
} }
return { return {
name, name,
code: asString(data.code) || undefined, code: asString(data.code) || undefined,
mainChannel: mainChannel.length > 0 ? mainChannel : undefined, mainChannel: asString(data.main_channel) || undefined,
connectingChannel, connectingChannel: parseConnectingChannel(data.connecting_channel),
muscleChannel: muscleChannel.length > 0 ? muscleChannel : undefined, muscleChannel: asString(data.muscle_channel) || undefined,
greatConnectingChannelOfSpleen: greatConnectingBullets, greatConnectingChannelOfSpleen: greatConnectingStr,
}; };
} }
@ -465,9 +388,9 @@ export function TwelveChannelsDetailRenderer({
<Hero title={activeChannelData.name} /> <Hero title={activeChannelData.name} />
{/* 1. Main Channel Card */} {/* 1. Main Channel Card */}
{activeChannelData.mainChannel && activeChannelData.mainChannel.length > 0 ? ( {activeChannelData.mainChannel ? (
<SectionCard title="Main Channel" defaultExpanded> <SectionCard title="Main Channel" defaultExpanded>
<BulletList items={activeChannelData.mainChannel} /> <Paragraphs items={[activeChannelData.mainChannel]} />
</SectionCard> </SectionCard>
) : null} ) : null}
@ -476,46 +399,47 @@ export function TwelveChannelsDetailRenderer({
<SectionCard title="Connecting Channel" defaultExpanded> <SectionCard title="Connecting Channel" defaultExpanded>
{isConnectingObj ? ( {isConnectingObj ? (
<View style={styles.connectingDetailsContainer}> <View style={styles.connectingDetailsContainer}>
{(connecting as ConnectingChannelDetails).full && {(connecting as ConnectingChannelDetails).full ? (
(connecting as ConnectingChannelDetails).full!.length > 0 ? (
<View style={styles.conditionBlock}> <View style={styles.conditionBlock}>
<View style={styles.conditionHeader}> <View style={styles.conditionHeader}>
<View style={[styles.conditionDot, { backgroundColor: Colors.error || "#EF4444" }]} /> <View style={[styles.conditionDot, { backgroundColor: Colors.error || "#EF4444" }]} />
<Text style={styles.conditionTitle}>Full Condition</Text> <Text style={styles.conditionTitle}>Full Condition</Text>
</View> </View>
<BulletList items={(connecting as ConnectingChannelDetails).full!} /> <Text style={styles.conditionText}>
{(connecting as ConnectingChannelDetails).full}
</Text>
</View> </View>
) : null} ) : null}
{(connecting as ConnectingChannelDetails).empty && {(connecting as ConnectingChannelDetails).empty ? (
(connecting as ConnectingChannelDetails).empty!.length > 0 ? ( <View style={[styles.conditionBlock, { marginTop: moderateScale(10) }]}>
<View style={styles.conditionBlock}>
<View style={styles.conditionHeader}> <View style={styles.conditionHeader}>
<View style={[styles.conditionDot, { backgroundColor: "#3B82F6" }]} /> <View style={[styles.conditionDot, { backgroundColor: "#3B82F6" }]} />
<Text style={styles.conditionTitle}>Empty Condition</Text> <Text style={styles.conditionTitle}>Empty Condition</Text>
</View> </View>
<BulletList items={(connecting as ConnectingChannelDetails).empty!} /> <Text style={styles.conditionText}>
{(connecting as ConnectingChannelDetails).empty}
</Text>
</View> </View>
) : null} ) : null}
</View> </View>
) : Array.isArray(connecting) ? ( ) : typeof connecting === "string" ? (
<BulletList items={connecting} /> <Paragraphs items={[connecting]} />
) : null} ) : null}
</SectionCard> </SectionCard>
) : null} ) : null}
{/* 3. Muscle Channel Card */} {/* 3. Muscle Channel Card */}
{activeChannelData.muscleChannel && activeChannelData.muscleChannel.length > 0 ? ( {activeChannelData.muscleChannel ? (
<SectionCard title="Muscle Channel" defaultExpanded> <SectionCard title="Muscle Channel" defaultExpanded>
<BulletList items={activeChannelData.muscleChannel} /> <Paragraphs items={[activeChannelData.muscleChannel]} />
</SectionCard> </SectionCard>
) : null} ) : null}
{/* 4. Great Connecting Channel of the Spleen (if present) */} {/* 4. Great Connecting Channel of the Spleen (if present) */}
{activeChannelData.greatConnectingChannelOfSpleen && {activeChannelData.greatConnectingChannelOfSpleen ? (
activeChannelData.greatConnectingChannelOfSpleen.length > 0 ? (
<SectionCard title="Great Connecting Channel of the Spleen" defaultExpanded> <SectionCard title="Great Connecting Channel of the Spleen" defaultExpanded>
<BulletList items={activeChannelData.greatConnectingChannelOfSpleen} /> <Paragraphs items={[activeChannelData.greatConnectingChannelOfSpleen]} />
</SectionCard> </SectionCard>
) : null} ) : null}
</ScrollView> </ScrollView>
@ -614,7 +538,15 @@ export function TwelveChannelsDetailRenderer({
<Hero title="Twelve Channels" /> <Hero title="Twelve Channels" />
{/* 1. Overview Card */} {/* 1. Overview Card */}
{overviewText ? <OverviewCard text={overviewText} /> : null} {overviewText ? (
<View style={styles.overviewCard}>
<View style={styles.overviewHeader}>
<Ionicons name="information-circle" size={20} color={Colors.primary} />
<Text style={styles.overviewTitle}>Overview</Text>
</View>
<Text style={styles.overviewText}>{overviewText}</Text>
</View>
) : null}
{/* 2. Organ vs Channel Card */} {/* 2. Organ vs Channel Card */}
{organVsChannelText ? ( {organVsChannelText ? (
@ -746,8 +678,31 @@ const styles = StyleSheet.create({
container: { container: {
paddingHorizontal: moderateScale(16), paddingHorizontal: moderateScale(16),
paddingTop: verticalScale(14), paddingTop: verticalScale(14),
paddingBottom: verticalScale(40), paddingBottom: verticalScale(36),
gap: verticalScale(14), },
overviewCard: {
backgroundColor: "#F0FDF4",
borderRadius: moderateScale(14),
borderWidth: 1,
borderColor: "#DCFCE7",
padding: moderateScale(16),
marginBottom: verticalScale(14),
},
overviewHeader: {
flexDirection: "row",
alignItems: "center",
marginBottom: moderateScale(8),
gap: moderateScale(6),
},
overviewTitle: {
fontSize: moderateScale(15),
fontWeight: "700",
color: Colors.primaryDark,
},
overviewText: {
fontSize: moderateScale(14),
color: Colors.textSecondary,
lineHeight: moderateScale(21),
}, },
infoCard: { infoCard: {
backgroundColor: "#FFFFFF", backgroundColor: "#FFFFFF",
@ -755,6 +710,7 @@ const styles = StyleSheet.create({
borderWidth: 1, borderWidth: 1,
borderColor: "#E5E7EB", borderColor: "#E5E7EB",
padding: moderateScale(14), padding: moderateScale(14),
marginBottom: verticalScale(14),
}, },
infoHeader: { infoHeader: {
flexDirection: "row", flexDirection: "row",
@ -860,6 +816,7 @@ const styles = StyleSheet.create({
borderWidth: 1, borderWidth: 1,
borderColor: "#E2E8F0", borderColor: "#E2E8F0",
padding: moderateScale(14), padding: moderateScale(14),
marginBottom: verticalScale(14),
}, },
summaryHeader: { summaryHeader: {
flexDirection: "row", flexDirection: "row",
@ -879,12 +836,13 @@ const styles = StyleSheet.create({
lineHeight: moderateScale(19), lineHeight: moderateScale(19),
}, },
channelsContainer: { channelsContainer: {
gap: verticalScale(10), marginTop: verticalScale(10),
}, },
sectionHeading: { sectionHeading: {
fontSize: moderateScale(16), fontSize: moderateScale(16),
fontWeight: "700", fontWeight: "700",
color: Colors.textPrimary, color: Colors.textPrimary,
marginBottom: verticalScale(12),
marginLeft: moderateScale(2), marginLeft: moderateScale(2),
}, },
channelRow: { channelRow: {
@ -897,6 +855,7 @@ const styles = StyleSheet.create({
borderRadius: moderateScale(14), borderRadius: moderateScale(14),
borderWidth: 1, borderWidth: 1,
borderColor: "#E2EAE5", borderColor: "#E2EAE5",
marginBottom: verticalScale(12),
}, },
pressed: { pressed: {
opacity: 0.72, opacity: 0.72,
@ -926,7 +885,7 @@ const styles = StyleSheet.create({
color: Colors.textPrimary, color: Colors.textPrimary,
}, },
connectingDetailsContainer: { connectingDetailsContainer: {
gap: moderateScale(10), gap: moderateScale(6),
}, },
conditionBlock: { conditionBlock: {
backgroundColor: "#F9FAFB", backgroundColor: "#F9FAFB",

View File

@ -1,482 +1,8 @@
import React, { useMemo, useState } from "react"; import React from "react";
import { import { ScrollView } from "react-native";
LayoutAnimation,
Platform,
Pressable,
ScrollView,
StyleSheet,
Text,
UIManager,
View,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { useRouter } from "expo-router";
import { moderateScale, verticalScale } from "react-native-size-matters";
import { Colors, Radius } from "@/theme";
import { useSettingsStore } from "@/store/settings.store";
import type { DetailRendererProps } from "../../types/renderer.types"; import type { DetailRendererProps } from "../../types/renderer.types";
import { useModuleTemplateContentDetailsQuery } from "../../hooks/use-content-queries";
import {
buildContentReferenceRoute,
parseNavigableContentReference,
} from "../../utils/content-reference";
import {
asRecord,
asRecordArray,
asString,
asStringArray,
} from "../helpers/value";
import { BulletList } from "../shared/BulletList";
import { ContentLinkAttributeSections } from "../shared/ContentLinkAttributeSections"; import { ContentLinkAttributeSections } from "../shared/ContentLinkAttributeSections";
import { asString } from "../helpers/value";
import { Hero } from "../shared/Hero"; import { Hero } from "../shared/Hero";
import { OverviewCard } from "../shared/OverviewCard"; import { DescriptionList, Images, ObjectArrayCards, ObjectArrayTable, ObjectCard, PointCodes, Strings } from "./categoryParts";
import { Images } from "./categoryParts"; export function YuanSourceDetailRenderer({content,data,definitions,presentationAttributes}:DetailRendererProps){ return <ScrollView contentContainerStyle={{paddingHorizontal:18,paddingTop:16,paddingBottom:40,gap:14}}><Hero title={asString(data.title)||asString(data.name)||content.title}/><Images data={data}/><PointCodes data={data}/><ObjectArrayTable title="Source Points" value={data.source_point} columns={["meridian","point"]}/><Strings title="Key Clinical Features" value={data.key_clinical_feature}/><Strings title="Yin vs Yang" value={data.yin_vs_yang}/><Strings title="Functions" value={data.functions}/><Strings title="Diagnostic Utility" value={data.diagnostic_utility}/><ContentLinkAttributeSections data={data} definitions={definitions} presentationAttributes={presentationAttributes}/></ScrollView>; }
if (Platform.OS === "android" && UIManager.setLayoutAnimationEnabledExperimental) {
UIManager.setLayoutAnimationEnabledExperimental(true);
}
interface PointItemProps {
key?: React.Key;
item: Record<string, unknown>;
defaultExpanded: boolean;
moduleCode: string;
pointsCatalogMap?: Map<string, { contentId: string; title: string }>;
}
function sanitizeMeridianHeading(meridian: string, chineseName: string): string {
const cleanChinese = chineseName.replace(/^\((.*)\)$/, "$1").trim();
// Strip meridian abbreviation codes or point codes in parentheses,
// e.g. (ST), (LU-9), (LI), (LV), (LR), (PC), (GB), (HT), etc.
const cleanedMeridian = meridian
.replace(/\s*\(\s*[A-Z]{1,4}(?:[\s\-_]*\d+)?\s*\)\s*/g, " ")
.replace(/\s+/g, " ")
.trim();
if (cleanedMeridian && cleanChinese) {
if (cleanedMeridian.toLowerCase().includes(cleanChinese.toLowerCase())) {
return cleanedMeridian;
}
return `${cleanedMeridian} (${cleanChinese})`;
}
return cleanedMeridian || cleanChinese || "Point";
}
function PointAccordionCard({
item,
defaultExpanded,
moduleCode,
pointsCatalogMap,
}: PointItemProps) {
const router = useRouter();
const [expanded, setExpanded] = useState(defaultExpanded);
const meridian = asString(item.meridian).trim();
const chineseName = asString(item.chinese_name).trim();
const element = asString(item.element).trim();
const caution = asString(item.caution).trim();
const cautionList = asStringArray(item.caution);
const actions = asStringArray(item.actions);
const indications = asStringArray(item.indications);
// Format header title: e.g. "Stomach (Chongyang)", "Lung (Taiyuan)"
const title = useMemo(() => {
return sanitizeMeridianHeading(meridian, chineseName);
}, [meridian, chineseName]);
// Resolve point reference for linkable button
const rawPoint = asRecord(item.point);
const directRef = parseNavigableContentReference(item.point);
// Extract candidate point codes/labels: e.g. "LU 9", "LU-9"
const pointLabel =
directRef?.label?.trim() ||
asString(rawPoint.label).trim() ||
(rawPoint.target && typeof rawPoint.target === "object"
? asString((rawPoint.target as Record<string, unknown>).source_code).trim()
: "") ||
"";
// Construct button display label: e.g. "LU-9 (Taiyuan)" or "LU 9 (Taiyuan)"
const pointButtonLabel = useMemo(() => {
const baseCode = pointLabel || "Point Details";
if (chineseName && !baseCode.toLowerCase().includes(chineseName.toLowerCase())) {
return `${baseCode} (${chineseName})`;
}
return baseCode;
}, [pointLabel, chineseName]);
// Resolve navigation destination
const navigateToPoint = () => {
if (directRef) {
router.push(buildContentReferenceRoute(directRef) as never);
return;
}
if (rawPoint.target && typeof rawPoint.target === "object") {
const target = rawPoint.target as Record<string, unknown>;
const targetModule = asString(target.module_code).trim() || moduleCode || "m0001";
const targetTemplate = asString(target.template_code).trim() || "m0001_ct0003";
const contentId = asString(target.content_id).trim();
const sourceCode = asString(target.source_code).trim();
if (contentId) {
router.push(
`/modules/${encodeURIComponent(targetModule)}/${encodeURIComponent(targetTemplate)}/${encodeURIComponent(contentId)}` as never,
);
return;
}
// Fallback: match by catalog map (from m0001_ct0003) using sourceCode or label
if (pointsCatalogMap && sourceCode) {
const found =
pointsCatalogMap.get(sourceCode.toLowerCase()) ||
pointsCatalogMap.get(sourceCode.replace(/[- ]/g, "").toLowerCase());
if (found) {
router.push(
`/modules/${encodeURIComponent(targetModule)}/${encodeURIComponent(targetTemplate)}/${encodeURIComponent(found.contentId)}` as never,
);
return;
}
}
}
// Secondary fallback matching by pointLabel in catalog
if (pointsCatalogMap && pointLabel) {
const found =
pointsCatalogMap.get(pointLabel.toLowerCase()) ||
pointsCatalogMap.get(pointLabel.replace(/[- ]/g, "").toLowerCase());
if (found) {
router.push(
`/modules/${encodeURIComponent(moduleCode || "m0001")}/m0001_ct0003/${encodeURIComponent(found.contentId)}` as never,
);
}
}
};
const toggle = () => {
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
setExpanded((prev) => !prev);
};
return (
<View style={styles.card}>
{/* Accordion Header */}
<Pressable
accessibilityRole="button"
accessibilityState={{ expanded }}
accessibilityLabel={`${expanded ? "Collapse" : "Expand"} ${title}`}
onPress={toggle}
style={({ pressed }) => [
styles.cardHeader,
expanded && styles.cardHeaderExpanded,
pressed && styles.pressed,
]}
>
<View style={styles.headerLeft}>
<View style={styles.headerAccent} />
<Text style={styles.headerTitle} numberOfLines={2}>
{title}
</Text>
</View>
<View style={styles.headerRight}>
{element ? (
<View style={styles.elementBadge}>
<Text style={styles.elementBadgeText}>{element}</Text>
</View>
) : null}
<View style={styles.chevron}>
<Ionicons
name={expanded ? "chevron-up" : "chevron-down"}
size={moderateScale(16)}
color={Colors.primary}
/>
</View>
</View>
</Pressable>
{/* Accordion Body (Expanded State) */}
{expanded ? (
<View style={styles.cardBody}>
{/* Actions */}
{actions.length > 0 ? (
<View style={styles.sectionRow}>
<Text style={styles.sectionLabel}>ACTIONS</Text>
{actions.length === 1 ? (
<Text style={styles.sectionValue}>{actions[0]}</Text>
) : (
<BulletList items={actions} />
)}
</View>
) : null}
{/* Indications */}
{indications.length > 0 ? (
<View style={styles.sectionRow}>
<Text style={styles.sectionLabel}>INDICATIONS</Text>
<BulletList items={indications} />
</View>
) : null}
{/* Caution (same UI as Actions and Indications) */}
{caution ? (
<View style={styles.sectionRow}>
<Text style={styles.sectionLabel}>CAUTION</Text>
{cautionList.length > 1 ? (
<BulletList items={cautionList} />
) : (
<Text style={styles.sectionValue}>{caution}</Text>
)}
</View>
) : null}
{/* Linkable Point Button (matching standard ReferenceChipList styling) */}
{pointLabel ? (
<Pressable
accessibilityRole="link"
accessibilityLabel={`View point ${pointButtonLabel}`}
onPress={navigateToPoint}
style={({ pressed }) => [
styles.pointLinkButton,
pressed && styles.pressed,
]}
>
<Text style={styles.pointLinkLabel}>{pointButtonLabel}</Text>
<Ionicons
name="chevron-forward"
size={moderateScale(14)}
color={Colors.primaryDark}
/>
</Pressable>
) : null}
</View>
) : null}
</View>
);
}
export function YuanSourceDetailRenderer({
moduleCode = "m0001",
content,
data,
definitions,
presentationAttributes,
}: DetailRendererProps) {
const accordionDefaultExpanded = useSettingsStore(
(state) => state.accordionDefaultExpanded,
);
// Fetch points from m0001_ct0003 for robust ID navigation fallback
const { data: pointsCatalog } = useModuleTemplateContentDetailsQuery({
module_code: moduleCode || "m0001",
template_code: "m0001_ct0003",
});
const pointsCatalogMap = useMemo(() => {
const map = new Map<string, { contentId: string; title: string }>();
if (pointsCatalog?.items) {
for (const item of pointsCatalog.items) {
const id = item.content.id;
const title = item.content.title;
const code = asString(item.data.code).trim().toLowerCase();
const name = asString(item.data.name).trim().toLowerCase();
if (code) {
map.set(code, { contentId: id, title });
map.set(code.replace(/[- ]/g, ""), { contentId: id, title });
}
if (name) {
map.set(name, { contentId: id, title });
}
}
}
return map;
}, [pointsCatalog]);
const rawTitle =
asString(data.title) || asString(data.name) || content.title || "Yuan Source";
const altNames = asStringArray(data.alt_name);
const descriptionParagraphs = asStringArray(data.description);
const points = asRecordArray(data.points);
return (
<ScrollView
contentContainerStyle={styles.container}
showsVerticalScrollIndicator={false}
>
{/* Screen Title & Subtitle */}
<Hero
title={rawTitle}
subtitle={altNames.length > 0 ? altNames.join(" · ") : undefined}
/>
{/* Visual images (if any assigned) */}
<Images data={data} />
{/* Overview Section */}
{descriptionParagraphs.length > 0 ? (
<OverviewCard
title="Overview"
paragraphs={descriptionParagraphs}
/>
) : null}
{/* Points Accordion List */}
{points.length > 0 ? (
<View style={styles.pointsList}>
{points.map((pointItem, index) => (
<PointAccordionCard
key={index}
item={pointItem}
defaultExpanded={accordionDefaultExpanded}
moduleCode={moduleCode}
pointsCatalogMap={pointsCatalogMap}
/>
))}
</View>
) : null}
{/* Generic content link attributes (excluding points already rendered above) */}
<ContentLinkAttributeSections
data={data}
definitions={definitions}
presentationAttributes={presentationAttributes}
excludeAttributeKeys={["points", "m0001_ct0009.points"]}
/>
</ScrollView>
);
}
const styles = StyleSheet.create({
container: {
paddingHorizontal: moderateScale(16),
paddingTop: verticalScale(14),
paddingBottom: verticalScale(40),
gap: verticalScale(14),
},
pointsList: {
gap: verticalScale(12),
},
card: {
backgroundColor: "#FFFFFF",
borderRadius: moderateScale(16),
borderWidth: 1,
borderColor: "#E2E8F0",
overflow: "hidden",
},
cardHeader: {
minHeight: verticalScale(54),
paddingHorizontal: moderateScale(14),
paddingVertical: verticalScale(12),
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
backgroundColor: "#FFFFFF",
gap: moderateScale(10),
},
cardHeaderExpanded: {
backgroundColor: "#F0F7F3",
borderBottomWidth: 1,
borderBottomColor: "#E2E8F0",
},
pressed: {
opacity: 0.75,
},
headerLeft: {
flex: 1,
flexDirection: "row",
alignItems: "center",
gap: moderateScale(10),
},
headerAccent: {
width: moderateScale(4),
height: verticalScale(22),
borderRadius: moderateScale(2),
backgroundColor: Colors.primary,
},
headerTitle: {
flex: 1,
fontSize: moderateScale(15),
lineHeight: moderateScale(21),
fontWeight: "700",
color: "#1E293B",
},
headerRight: {
flexDirection: "row",
alignItems: "center",
gap: moderateScale(8),
},
elementBadge: {
paddingHorizontal: moderateScale(9),
paddingVertical: verticalScale(3),
borderRadius: moderateScale(10),
backgroundColor: "#E8F5E9",
borderWidth: 1,
borderColor: "#C6E4CE",
},
elementBadgeText: {
fontSize: 11,
lineHeight: 16,
fontWeight: "600",
color: "#285A44",
},
chevron: {
width: moderateScale(28),
height: moderateScale(28),
borderRadius: moderateScale(14),
backgroundColor: "#FFFFFFB8",
alignItems: "center",
justifyContent: "center",
borderWidth: 1,
borderColor: "#E2E8F0",
},
cardBody: {
paddingHorizontal: moderateScale(16),
paddingTop: verticalScale(14),
paddingBottom: verticalScale(16),
gap: verticalScale(12),
backgroundColor: "#FFFFFF",
},
sectionRow: {
gap: verticalScale(6),
paddingBottom: verticalScale(10),
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: "#E8ECEF",
},
sectionLabel: {
fontSize: 12,
lineHeight: 17,
fontWeight: "700",
color: "#597064",
letterSpacing: 0.15,
},
sectionValue: {
fontSize: 16,
lineHeight: 25,
color: "#334155",
},
pointLinkButton: {
alignSelf: "flex-start",
minHeight: verticalScale(34),
paddingHorizontal: moderateScale(12),
paddingVertical: verticalScale(6),
borderRadius: Radius.full,
backgroundColor: "#E8F5E9",
borderWidth: 1,
borderColor: "#CDE5D0",
flexDirection: "row",
alignItems: "center",
gap: moderateScale(6),
marginTop: verticalScale(6),
},
pointLinkLabel: {
fontSize: moderateScale(13),
lineHeight: moderateScale(18),
fontWeight: "700",
color: Colors.primaryDark,
},
});

View File

@ -8,8 +8,6 @@ import { ObjectSections } from "../shared/ObjectSections";
import { RecordCards } from "../shared/RecordCards"; import { RecordCards } from "../shared/RecordCards";
import { RecordTable } from "../shared/RecordTable"; import { RecordTable } from "../shared/RecordTable";
import { SectionCard } from "../shared/SectionCard"; import { SectionCard } from "../shared/SectionCard";
import { useRelationalContentMedia } from "../../media/ContentMediaContext";
import { ContentMediaGallery } from "../../media/ContentMediaGallery";
export const PointCodes = ({ data }: { data: Record<string, unknown> }) => ( export const PointCodes = ({ data }: { data: Record<string, unknown> }) => (
<SectionCard title="Points"><ChipList items={asStringArray(data.point_codes)} /></SectionCard> <SectionCard title="Points"><ChipList items={asStringArray(data.point_codes)} /></SectionCard>
@ -25,36 +23,9 @@ export const DescriptionList = ({ data }: { data: Record<string, unknown> }) =>
); );
}; };
const extractCategoryImages = (data: Record<string, unknown>): Record<string, unknown>[] => { export const Images = ({ data }: { data: Record<string, unknown> }) => (
const images = asRecordArray(data.images); <ImageGallery images={asRecordArray(data.images)} />
if (images.length > 0) return images; );
const single = asRecord(data.default_image || data.image);
if (Object.keys(single).length > 0) {
return [single];
}
return [];
};
export const Images = ({ data }: { data: Record<string, unknown> }) => {
const directImages = extractCategoryImages(data);
const relationalMedia = useRelationalContentMedia();
// If direct images are explicitly defined in category data attributes, display them
if (directImages.length > 0) {
return <ImageGallery images={directImages} />;
}
// If direct media was assigned directly to this category (e.g. primary image in CMS)
const directMedia = relationalMedia.filter((m) => m.media_role === "primary");
if (directMedia.length > 0) {
return <ContentMediaGallery media={directMedia} title="Visual Reference" />;
}
// Do not show inherited media from referenced points/meridians for categories without direct images
return null;
};
export const ObjectCard = ({ title, value }: { title: string; value: unknown }) => { export const ObjectCard = ({ title, value }: { title: string; value: unknown }) => {
const obj = asRecord(value); const obj = asRecord(value);

View File

@ -1,11 +1,9 @@
import type { AttributeDefinitionResponse } from "../../types/content.types";
export function asString(value: unknown): string { export function asString(value: unknown): string {
if (typeof value === "string") return value; if (typeof value === "string") return value;
if (typeof value === "number" || typeof value === "boolean") return String(value); if (typeof value === "number" || typeof value === "boolean") return String(value);
if (value !== null && typeof value === "object" && !Array.isArray(value)) { if (value !== null && typeof value === "object" && !Array.isArray(value)) {
const record = value as Record<string, unknown>; const record = value as Record<string, unknown>;
for (const key of ["label", "point_name", "food_name", "name", "title", "code"]) { for (const key of ["label", "point_name", "name", "title", "code"]) {
if (typeof record[key] === "string" && (record[key] as string).trim().length > 0) { if (typeof record[key] === "string" && (record[key] as string).trim().length > 0) {
return (record[key] as string).trim(); return (record[key] as string).trim();
} }
@ -42,67 +40,6 @@ export function asRecordArray(value: unknown): Record<string, unknown>[] {
export function humanizeKey(value: string): string { export function humanizeKey(value: string): string {
return value return value
.replace(/[_-]/g, " ") .replace(/_/g, " ")
.replace(/\b\w/g, (letter) => letter.toUpperCase()) .replace(/\b\w/g, (letter) => letter.toUpperCase());
.replace(/(['’‘ʼ])s\b/gi, (match) => match[0] + "s");
} }
/**
* Normalizes pattern titles, correcting misplaced apostrophes in singular possessive organ names
* (e.g. "Lungs’" / "Lungs'" / "Lunges'" -> "Lung's").
*/
export function formatPatternTitle(value: string): string {
if (!value) return "";
return value.replace(/\bLung(?:es|s)['’]/gi, "Lung's");
}
/**
* Indexes template attribute definitions (and nested children) by code so
* renderers can display exact template labels and casing without hardcoding.
*/
export function buildDefinitionLabelMap(
attributes?: readonly AttributeDefinitionResponse[] | null,
): Map<string, string> {
const map = new Map<string, string>();
if (!attributes) return map;
const visit = (attrs: readonly AttributeDefinitionResponse[], prefix?: string) => {
for (const attr of attrs) {
const code = attr.code?.trim();
const label = attr.label?.trim();
if (code && label) {
map.set(code, label);
map.set(code.toLowerCase(), label);
if (prefix) {
map.set(`${prefix}.${code}`, label);
map.set(`${prefix}.${code}`.toLowerCase(), label);
}
}
if (Array.isArray(attr.children) && attr.children.length > 0) {
visit(attr.children, code || prefix);
}
}
};
visit(attributes);
return map;
}
/**
* Returns the exact template label when defined, falling back to a provided label or humanized key.
*/
export function resolveAttributeLabel(
code: string,
labelMap?: ReadonlyMap<string, string>,
fallback?: string,
): string {
const trimmed = code.trim();
const fromMap =
labelMap?.get(trimmed) || labelMap?.get(trimmed.toLowerCase());
if (fromMap && fromMap.trim().length > 0) {
return fromMap.trim();
}
return fallback ?? humanizeKey(trimmed);
}

View File

@ -2,11 +2,7 @@ import type { CollectionItemRendererComponent, CollectionRendererComponent, Deta
import { GenericCollectionRenderer } from "./GenericCollectionRenderer"; import { GenericCollectionRenderer } from "./GenericCollectionRenderer";
import { GenericCardRenderer } from "./GenericCardRenderer"; import { GenericCardRenderer } from "./GenericCardRenderer";
import { GenericDetailRenderer } from "./GenericDetailRenderer"; import { GenericDetailRenderer } from "./GenericDetailRenderer";
import { import { ModuleCatalogCollectionRenderer, ModuleCatalogCardRenderer } from "./collections/ModuleCatalogRenderers";
ModuleCatalogCollectionRenderer,
ModuleCatalogCardRenderer,
PatternAccordionCardRenderer,
} from "./collections/ModuleCatalogRenderers";
import { AcuPointCollectionRenderer, AcuPointIndexCollectionRenderer, AcuPointCardRenderer, AcuPointIndexCardRenderer } from "./collections/PointRenderers"; import { AcuPointCollectionRenderer, AcuPointIndexCollectionRenderer, AcuPointCardRenderer, AcuPointIndexCardRenderer } from "./collections/PointRenderers";
import { MeridianCollectionRenderer, MeridianIndexCollectionRenderer, MeridianCardRenderer, MeridianIndexCardRenderer } from "./collections/MeridianRenderers"; import { MeridianCollectionRenderer, MeridianIndexCollectionRenderer, MeridianCardRenderer, MeridianIndexCardRenderer } from "./collections/MeridianRenderers";
import { EovCollectionRenderer, EovIndexCollectionRenderer, EovCardRenderer, EovIndexCardRenderer } from "./collections/EovRenderers"; import { EovCollectionRenderer, EovIndexCollectionRenderer, EovCardRenderer, EovIndexCardRenderer } from "./collections/EovRenderers";
@ -49,15 +45,9 @@ import { TwelveChannelsCollectionRenderer, TwelveChannelsCardRenderer } from "./
import { TwelveChannelsDetailRenderer } from "./details/TwelveChannelsDetailRenderer"; import { TwelveChannelsDetailRenderer } from "./details/TwelveChannelsDetailRenderer";
import { ThreeBurnersCollectionRenderer, ThreeBurnersCardRenderer } from "./collections/ThreeBurnersRenderers"; import { ThreeBurnersCollectionRenderer, ThreeBurnersCardRenderer } from "./collections/ThreeBurnersRenderers";
import { ThreeBurnersDetailRenderer } from "./details/ThreeBurnersDetailRenderer"; import { ThreeBurnersDetailRenderer } from "./details/ThreeBurnersDetailRenderer";
import { SixStagesCollectionRenderer, SixStagesCardRenderer } from "./collections/SixStagesRenderers";
import { SixStagesDetailRenderer } from "./details/SixStagesDetailRenderer"; import { SixStagesDetailRenderer } from "./details/SixStagesDetailRenderer";
import { TcmPatternDetailRenderer } from "./details/TcmPatternDetailRenderer"; import { TcmPatternDetailRenderer } from "./details/TcmPatternDetailRenderer";
import { ExtraOrdinaryVesselsDetailRenderer } from "./details/ExtraOrdinaryVesselsDetailRenderer"; import { ExtraOrdinaryVesselsDetailRenderer } from "./details/ExtraOrdinaryVesselsDetailRenderer";
import { NutritionCategoryDetailRenderer } from "./details/NutritionCategoryDetailRenderer";
import {
GynecologyDiseaseCollectionRenderer,
createGynecologyDiseaseCollectionRenderer,
} from "./collections/GynecologyRenderers";
export const collectionRenderers: Readonly<Record<string, CollectionRendererComponent>> = Object.freeze({ export const collectionRenderers: Readonly<Record<string, CollectionRendererComponent>> = Object.freeze({
module_catalog_collection: ModuleCatalogCollectionRenderer, module_catalog_collection: ModuleCatalogCollectionRenderer,
@ -73,25 +63,24 @@ export const collectionRenderers: Readonly<Record<string, CollectionRendererComp
four_levels_collection: FourLevelsCollectionRenderer, four_levels_collection: FourLevelsCollectionRenderer,
eight_principles_collection: EightPrinciplesCollectionRenderer, eight_principles_collection: EightPrinciplesCollectionRenderer,
pathogenic_factors_collection: PathogenicFactorsCollectionRenderer, pathogenic_factors_collection: PathogenicFactorsCollectionRenderer,
five_elements_collection: FiveElementsCollectionRenderer,
qi_blood_collection: QiBloodCollectionRenderer,
twelve_channels_collection: TwelveChannelsCollectionRenderer,
three_burners_collection: ThreeBurnersCollectionRenderer,
six_stages_collection: SixStagesCollectionRenderer,
chinese_scalp_acupuncture_collection: ModuleCatalogCollectionRenderer, chinese_scalp_acupuncture_collection: ModuleCatalogCollectionRenderer,
nutrition_food_collection: ModuleCatalogCollectionRenderer, nutrition_food_collection: ModuleCatalogCollectionRenderer,
nutrition_category_collection: ModuleCatalogCollectionRenderer,
nutrition_effect_collection: ModuleCatalogCollectionRenderer, nutrition_effect_collection: ModuleCatalogCollectionRenderer,
disease_collection: ModuleCatalogCollectionRenderer, m0042_ct0001_collection: ModuleCatalogCollectionRenderer,
auriculotherapy_collection: ModuleCatalogCollectionRenderer, m0016_ct0001_collection: FourLevelsCollectionRenderer,
gynecology_disease_collection: GynecologyDiseaseCollectionRenderer, m0011_ct0005_collection: EightPrinciplesCollectionRenderer,
m0014_ct0001_collection: PathogenicFactorsCollectionRenderer,
// Module-specific renderers removed for generic handling 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,
}); });
export const collectionItemRenderers: Readonly<Record<string, CollectionItemRendererComponent>> = Object.freeze({ export const collectionItemRenderers: Readonly<Record<string, CollectionItemRendererComponent>> = Object.freeze({
module_catalog_card: ModuleCatalogCardRenderer, module_catalog_card: ModuleCatalogCardRenderer,
pattern_accordion_card: PatternAccordionCardRenderer,
gynecology_pattern_card: PatternAccordionCardRenderer,
acu_point_index_card: AcuPointIndexCardRenderer, acu_point_index_card: AcuPointIndexCardRenderer,
acu_point_card: AcuPointCardRenderer, acu_point_card: AcuPointCardRenderer,
meridian_index_card: MeridianIndexCardRenderer, meridian_index_card: MeridianIndexCardRenderer,
@ -105,23 +94,24 @@ export const collectionItemRenderers: Readonly<Record<string, CollectionItemRend
eight_principles_card: EightPrinciplesCardRenderer, eight_principles_card: EightPrinciplesCardRenderer,
pathogenic_factors_card: PathogenicFactorsCardRenderer, pathogenic_factors_card: PathogenicFactorsCardRenderer,
five_elements_card: FiveElementsCardRenderer, five_elements_card: FiveElementsCardRenderer,
qi_blood_card: QiBloodCardRenderer,
twelve_channels_card: TwelveChannelsCardRenderer,
three_burners_card: ThreeBurnersCardRenderer,
six_stages_card: SixStagesCardRenderer,
chinese_scalp_acupuncture_card: ModuleCatalogCardRenderer, chinese_scalp_acupuncture_card: ModuleCatalogCardRenderer,
nutrition_food_card: ModuleCatalogCardRenderer, nutrition_food_card: ModuleCatalogCardRenderer,
nutrition_category_card: ModuleCatalogCardRenderer,
nutrition_effect_card: ModuleCatalogCardRenderer, nutrition_effect_card: ModuleCatalogCardRenderer,
disease_card: ModuleCatalogCardRenderer, m0042_ct0001_card: ModuleCatalogCardRenderer,
auriculotherapy_card: ModuleCatalogCardRenderer, m0016_ct0001_card: FourLevelsCardRenderer,
m0011_ct0005_card: EightPrinciplesCardRenderer,
// Module-specific card renderers removed for generic handling 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,
}); });
export const detailRenderers: Readonly<Record<string, DetailRendererComponent>> = Object.freeze({ export const detailRenderers: Readonly<Record<string, DetailRendererComponent>> = Object.freeze({
extra_ordinary_vessel_detail: ExtraOrdinaryVesselsDetailRenderer, extra_ordinary_vessel_detail: ExtraOrdinaryVesselsDetailRenderer,
module_catalog_detail: IndexEntryDetailRenderer, module_catalog_detail: IndexEntryDetailRenderer,
nutrition_category_detail: NutritionCategoryDetailRenderer,
acu_point_index_detail: IndexEntryDetailRenderer, acu_point_index_detail: IndexEntryDetailRenderer,
meridian_index_detail: MeridianPointsDetailRenderer, meridian_index_detail: MeridianPointsDetailRenderer,
meridian_points_detail: MeridianPointsDetailRenderer, meridian_points_detail: MeridianPointsDetailRenderer,
@ -155,8 +145,10 @@ export const detailRenderers: Readonly<Record<string, DetailRendererComponent>>
chinese_scalp_acupuncture_detail: AcuPointDetailRenderer, chinese_scalp_acupuncture_detail: AcuPointDetailRenderer,
nutrition_food_detail: GenericDetailRenderer, nutrition_food_detail: GenericDetailRenderer,
nutrition_effect_detail: GenericDetailRenderer, nutrition_effect_detail: GenericDetailRenderer,
disease_detail: GenericDetailRenderer, m0042_ct0001_detail: IndexEntryDetailRenderer,
auriculotherapy_detail: GenericDetailRenderer, m0042_ct0002_detail: IndexEntryDetailRenderer,
m0042_ct0003_detail: IndexEntryDetailRenderer,
m0042_ct0004_detail: IndexEntryDetailRenderer,
m0016_ct0002_detail: FourLevelsDetailRenderer, m0016_ct0002_detail: FourLevelsDetailRenderer,
m0011_ct0001_detail: EightPrinciplesDetailRenderer, m0011_ct0001_detail: EightPrinciplesDetailRenderer,
m0011_ct0002_detail: EightPrinciplesDetailRenderer, m0011_ct0002_detail: EightPrinciplesDetailRenderer,
@ -219,25 +211,6 @@ export function resolveCollectionRenderer(
const normalizedModule = moduleCode?.trim().toLowerCase(); const normalizedModule = moduleCode?.trim().toLowerCase();
const normalizedTemplate = templateCode?.trim().toLowerCase(); const normalizedTemplate = templateCode?.trim().toLowerCase();
if (code === "gynecology_disease_collection") {
return normalizedTemplate
? createGynecologyDiseaseCollectionRenderer(normalizedTemplate)
: GynecologyDiseaseCollectionRenderer;
}
if (
normalizedModule === "m0042" &&
normalizedTemplate &&
normalizedTemplate !== "m0042_ct0001" &&
normalizedTemplate !== "m0042_ct0002" &&
normalizedTemplate !== "m0042_ct0003" &&
normalizedTemplate !== "m0042_ct0004" &&
normalizedTemplate !== "m0042_ct0006" &&
normalizedTemplate !== "m0042_ct0007"
) {
return createGynecologyDiseaseCollectionRenderer(normalizedTemplate);
}
if (normalizedTemplate === "m0016_ct0001" || normalizedModule === "m0016") { if (normalizedTemplate === "m0016_ct0001" || normalizedModule === "m0016") {
return FourLevelsCollectionRenderer; return FourLevelsCollectionRenderer;
} }
@ -259,23 +232,6 @@ export function resolveCollectionRenderer(
if (normalizedTemplate === "m0017_ct0002" || (normalizedModule === "m0017" && normalizedTemplate?.includes("ct0002"))) { if (normalizedTemplate === "m0017_ct0002" || (normalizedModule === "m0017" && normalizedTemplate?.includes("ct0002"))) {
return ThreeBurnersCollectionRenderer; return ThreeBurnersCollectionRenderer;
} }
if (
normalizedTemplate?.startsWith("m0015_ct000") &&
normalizedTemplate !== "m0015_ct0007"
) {
return SixStagesCollectionRenderer;
}
if (
normalizedTemplate === "m0012_ct0001" ||
(normalizedModule === "m0012" && (code === "tcm_pattern_list_collection" || !code)) ||
code === "tcm_pattern_list_collection"
) {
return ModuleCatalogCollectionRenderer;
}
// Generic fallback for any mXXXX_ct... template
if (normalizedTemplate?.startsWith("m") && normalizedTemplate?.includes("_ct")) {
return ModuleCatalogCollectionRenderer;
}
if (code && collectionRenderers[code]) return collectionRenderers[code]; if (code && collectionRenderers[code]) return collectionRenderers[code];
reportMissingRenderer("collection", code); reportMissingRenderer("collection", code);
@ -294,20 +250,6 @@ export function resolveCollectionItemRenderer(
const normalizedModule = moduleCode?.trim().toLowerCase(); const normalizedModule = moduleCode?.trim().toLowerCase();
const normalizedTemplate = templateCode?.trim().toLowerCase(); const normalizedTemplate = templateCode?.trim().toLowerCase();
if (
code === "gynecology_pattern_card" ||
(normalizedModule === "m0042" &&
normalizedTemplate &&
normalizedTemplate !== "m0042_ct0001" &&
normalizedTemplate !== "m0042_ct0002" &&
normalizedTemplate !== "m0042_ct0003" &&
normalizedTemplate !== "m0042_ct0004" &&
normalizedTemplate !== "m0042_ct0006" &&
normalizedTemplate !== "m0042_ct0007")
) {
return PatternAccordionCardRenderer;
}
if (normalizedTemplate === "m0016_ct0001" || normalizedModule === "m0016") { if (normalizedTemplate === "m0016_ct0001" || normalizedModule === "m0016") {
return FourLevelsCardRenderer; return FourLevelsCardRenderer;
} }
@ -330,23 +272,6 @@ export function resolveCollectionItemRenderer(
if (normalizedTemplate === "m0017_ct0002" || (normalizedModule === "m0017" && normalizedTemplate?.includes("ct0002"))) { if (normalizedTemplate === "m0017_ct0002" || (normalizedModule === "m0017" && normalizedTemplate?.includes("ct0002"))) {
return ThreeBurnersCardRenderer; return ThreeBurnersCardRenderer;
} }
if (
normalizedTemplate?.startsWith("m0015_ct000") &&
normalizedTemplate !== "m0015_ct0007"
) {
return SixStagesCardRenderer;
}
if (
normalizedTemplate === "m0012_ct0001" ||
(normalizedModule === "m0012" && (code === "tcm_pattern_list_card" || !code)) ||
code === "tcm_pattern_list_card"
) {
return ModuleCatalogCardRenderer;
}
// Generic fallback for any mXXXX_ct... template
if (normalizedTemplate?.startsWith("m") && normalizedTemplate?.includes("_ct")) {
return ModuleCatalogCardRenderer;
}
if (code && collectionItemRenderers[code]) return collectionItemRenderers[code]; if (code && collectionItemRenderers[code]) return collectionItemRenderers[code];
reportMissingRenderer("collection-item", code); reportMissingRenderer("collection-item", code);
@ -378,13 +303,6 @@ export function resolveDetailRenderer(
return MeridianPointsDetailRenderer; return MeridianPointsDetailRenderer;
} }
if (
normalizedTemplate === "m0031_ct0003" ||
code === "nutrition_category_detail"
) {
return NutritionCategoryDetailRenderer;
}
if ( if (
normalizedTemplate === "m0016_ct0002" || normalizedTemplate === "m0016_ct0002" ||
(normalizedModule === "m0016" && (code === "pattern_detail" || code === "module_catalog_detail")) (normalizedModule === "m0016" && (code === "pattern_detail" || code === "module_catalog_detail"))
@ -447,10 +365,6 @@ export function resolveDetailRenderer(
return ExtraOrdinaryVesselsDetailRenderer; 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]; if (code && detailRenderers[code]) return detailRenderers[code];
reportMissingRenderer("detail", code); reportMissingRenderer("detail", code);
return GenericDetailRenderer; return GenericDetailRenderer;

View File

@ -20,15 +20,11 @@ if (Platform.OS === "android" && UIManager.setLayoutAnimationEnabledExperimental
export interface AccordionSectionProps { export interface AccordionSectionProps {
title: string; title: string;
defaultExpanded?: boolean; defaultExpanded?: boolean;
icon?: keyof typeof Ionicons.glyphMap;
iconColor?: string;
} }
export function AccordionSection({ export function AccordionSection({
title, title,
defaultExpanded = true, defaultExpanded = true,
icon,
iconColor,
children, children,
}: PropsWithChildren<AccordionSectionProps>) { }: PropsWithChildren<AccordionSectionProps>) {
const [expanded, setExpanded] = useState(defaultExpanded); const [expanded, setExpanded] = useState(defaultExpanded);
@ -57,13 +53,6 @@ export function AccordionSection({
]} ]}
> >
<View style={[styles.accent, { backgroundColor: tone.accent }]} /> <View style={[styles.accent, { backgroundColor: tone.accent }]} />
{icon ? (
<Ionicons
name={icon}
size={moderateScale(18)}
color={iconColor ?? tone.accent}
/>
) : null}
<Text style={[styles.title, { color: tone.title }]}>{title}</Text> <Text style={[styles.title, { color: tone.title }]}>{title}</Text>
<View style={styles.chevron}> <View style={styles.chevron}>
<Ionicons <Ionicons

View File

@ -1,8 +1,6 @@
import React from "react"; import React from "react";
import { StyleSheet, Text, View } from "react-native"; import { StyleSheet, Text, View } from "react-native";
import { Colors } from "@/theme";
export function BulletList({ items }: { items: string[] }) { export function BulletList({ items }: { items: string[] }) {
if (!items.length) return null; if (!items.length) return null;
return ( return (
@ -25,7 +23,7 @@ const styles = StyleSheet.create({
height: 6, height: 6,
marginTop: 9, marginTop: 9,
borderRadius: 3, borderRadius: 3,
backgroundColor: Colors.primary, backgroundColor: "#5B806D",
}, },
text: { flex: 1, fontSize: 16, lineHeight: 25, color: "#334155" }, text: { flex: 1, fontSize: 16, lineHeight: 25, color: "#334155" },
}); });

View File

@ -1,16 +1,21 @@
import React from "react"; import React from "react";
import { StyleSheet, Text, View } from "react-native"; import { StyleSheet, Text, View } from "react-native";
const greenChipTone = { bg: "#EEF7F1", border: "#D5E8DB", text: "#35664E" }; const chipTones = [
{ bg: "#EEF7F1", border: "#D5E8DB", text: "#35664E" },
{ bg: "#EFF5FA", border: "#D7E5F0", text: "#3C617E" },
{ bg: "#FAF4EB", border: "#EEDFC9", text: "#805C31" },
];
export function ChipList({ items }: { items: string[] }) { export function ChipList({ items }: { items: string[] }) {
if (!items.length) return null; if (!items.length) return null;
return ( return (
<View style={styles.root}> <View style={styles.root}>
{items.map((item) => { {items.map((item, index) => {
const tone = chipTones[index % chipTones.length];
return ( return (
<View key={item} style={[styles.chip, { backgroundColor: greenChipTone.bg, borderColor: greenChipTone.border }]}> <View key={item} style={[styles.chip, { backgroundColor: tone.bg, borderColor: tone.border }]}>
<Text style={[styles.text, { color: greenChipTone.text }]}>{item}</Text> <Text style={[styles.text, { color: tone.text }]}>{item}</Text>
</View> </View>
); );
})} })}

View File

@ -13,7 +13,7 @@ import { Colors } from "@/theme";
import type { CollectionRendererProps } from "../../types/renderer.types"; import type { CollectionRendererProps } from "../../types/renderer.types";
export function CollectionScaffold( export function CollectionScaffold(
props: CollectionRendererProps & { header?: React.ReactNode; countLabel?: string }, props: CollectionRendererProps & { header?: React.ReactNode },
) { ) {
return ( return (
<FlatList <FlatList
@ -30,7 +30,7 @@ export function CollectionScaffold(
<> <>
{props.header} {props.header}
<Text style={styles.resultCount} accessibilityLiveRegion="polite"> <Text style={styles.resultCount} accessibilityLiveRegion="polite">
{props.countLabel ?? `${props.total} ${props.total === 1 ? "result" : "results"}`} {props.total} {props.total === 1 ? "result" : "results"}
</Text> </Text>
</> </>
} }
@ -86,7 +86,8 @@ const styles = StyleSheet.create({
fontSize: moderateScale(12), fontSize: moderateScale(12),
fontWeight: "700", fontWeight: "700",
color: Colors.textSecondary, color: Colors.textSecondary,
letterSpacing: 0.2, textTransform: "uppercase",
letterSpacing: 1,
marginBottom: verticalScale(8), marginBottom: verticalScale(8),
marginLeft: moderateScale(4), marginLeft: moderateScale(4),
}, },
@ -94,7 +95,7 @@ const styles = StyleSheet.create({
backgroundColor: "#FFFFFF", backgroundColor: "#FFFFFF",
borderRadius: moderateScale(18), borderRadius: moderateScale(18),
borderWidth: 1, borderWidth: 1,
borderColor: "#D7E9DE", borderColor: "#E2EAE5",
overflow: "hidden", overflow: "hidden",
}, },
separator: { separator: {

View File

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

View File

@ -29,14 +29,6 @@ function containsNavigableReference(value: unknown): boolean {
return false; return false;
} }
const DEFAULT_EXCLUDED_KEYS = new Set([
"point_codes",
"source_point",
"source_points",
"treatment",
"treatment_principle",
]);
export function ContentLinkAttributeSections({ export function ContentLinkAttributeSections({
data, data,
definitions = [], definitions = [],
@ -48,13 +40,10 @@ export function ContentLinkAttributeSections({
[presentationAttributes], [presentationAttributes],
); );
const excluded = useMemo(() => { const excluded = useMemo(
const set = new Set<string>(DEFAULT_EXCLUDED_KEYS); () => new Set(excludeAttributeKeys.map((key) => bareAttributeKey(key))),
for (const key of excludeAttributeKeys) { [excludeAttributeKeys],
set.add(bareAttributeKey(key)); );
}
return set;
}, [excludeAttributeKeys]);
const items = useMemo(() => { const items = useMemo(() => {
const roots = [...definitions] const roots = [...definitions]

View File

@ -13,8 +13,6 @@ import { Spacing } from "@/theme/spacing";
import { ContentLink } from "../../components/navigation/ContentLink"; import { ContentLink } from "../../components/navigation/ContentLink";
import { parseNavigableContentReference } from "../../utils/content-reference"; import { parseNavigableContentReference } from "../../utils/content-reference";
import { humanizeKey } from "../helpers/value"; import { humanizeKey } from "../helpers/value";
import { BulletList } from "./BulletList";
import { ReferenceChipList } from "./ReferenceChipList";
export interface ContentValueProps { export interface ContentValueProps {
value: unknown; value: unknown;
@ -22,28 +20,6 @@ export interface ContentValueProps {
emptyText?: string | null; emptyText?: string | null;
} }
function parseBullets(text: string): string[] {
if (text.includes("\n")) {
return text
.split("\n")
.map((s) => s.replace(/^[•\-\*\d+\.]\s*/, "").trim())
.filter((s) => s.length > 0);
}
if (text.includes(";")) {
return text
.split(";")
.map((s) => s.trim().replace(/^and\s+/i, ""))
.filter((s) => s.length > 0);
}
const parts = text.split(/,\s*(?![^()]*\))/);
if (parts.length > 1) {
return parts
.map((s) => s.trim().replace(/\.$/, "").replace(/^and\s+/i, ""))
.filter((s) => s.length > 0);
}
return [text];
}
/** /**
* Reference-aware fallback renderer for arbitrary nested attribute values. * Reference-aware fallback renderer for arbitrary nested attribute values.
* *
@ -78,14 +54,6 @@ export function ContentValue({
) : null; ) : null;
} }
if (visible.every((item) => typeof item === "string")) {
return <BulletList items={visible as string[]} />;
}
if (visible.some((item) => parseNavigableContentReference(item) !== null)) {
return <ReferenceChipList value={visible} />;
}
return ( return (
<View style={styles.stack}> <View style={styles.stack}>
{visible.map((item, index) => ( {visible.map((item, index) => (
@ -116,61 +84,16 @@ export function ContentValue({
return ( return (
<View style={styles.object}> <View style={styles.object}>
{entries.map(([key, child], index) => { {entries.map(([key, child]) => (
const isClinical = <View key={key} style={styles.objectRow}>
key.toLowerCase().includes("clinical") || <Text style={styles.objectLabel}>{humanizeKey(key)}</Text>
key.toLowerCase().includes("manifestation"); <ContentValue value={child} textStyle={textStyle} />
</View>
const renderChild = () => { ))}
if (
isClinical &&
typeof child === "string" &&
child.trim().length > 0
) {
const bullets = parseBullets(child);
if (bullets.length > 1) {
return <BulletList items={bullets} />;
}
}
return <ContentValue value={child} textStyle={textStyle} />;
};
return (
<View
key={key}
style={[
styles.objectRow,
index > 0 && styles.divider,
]}
>
<Text style={styles.objectLabel}>{humanizeKey(key)}</Text>
{renderChild()}
</View>
);
})}
</View> </View>
); );
} }
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 ( return (
<Text style={[styles.text, textStyle]}> <Text style={[styles.text, textStyle]}>
{typeof value === "boolean" ? (value ? "Yes" : "No") : String(value)} {typeof value === "boolean" ? (value ? "Yes" : "No") : String(value)}
@ -207,16 +130,12 @@ const styles = StyleSheet.create({
objectRow: { objectRow: {
gap: 4, gap: 4,
}, },
divider: {
paddingTop: 12,
borderTopWidth: StyleSheet.hairlineWidth,
borderTopColor: "#E8ECEF",
},
objectLabel: { objectLabel: {
fontSize: 12, fontSize: 12,
lineHeight: 17, lineHeight: 17,
fontWeight: "700", fontWeight: "700",
color: Colors.textSecondary, color: Colors.textSecondary,
letterSpacing: 0.15, textTransform: "uppercase",
letterSpacing: 0.35,
}, },
}); });

View File

@ -5,40 +5,21 @@ import { Ionicons } from "@expo/vector-icons";
import { router, useLocalSearchParams } from "expo-router"; import { router, useLocalSearchParams } from "expo-router";
import { Colors } from "@/theme"; import { Colors } from "@/theme";
import { type PageTone } from "../../context/PageToneContext";
import { ContentPageHeader } from "../../components/layout/ContentPageHeader"; import { ContentPageHeader } from "../../components/layout/ContentPageHeader";
import { useModuleDisplayName } from "../../hooks/use-module-display-name"; import { useModuleDisplayName } from "../../hooks/use-module-display-name";
export interface DetailPageShellProps extends PropsWithChildren { interface DetailPageShellProps extends PropsWithChildren {
title: string; title: string;
subtitle?: string; subtitle?: string;
onBack?: () => void; onBack?: () => void;
tone?: PageTone;
moduleCode?: string;
hideFavorite?: boolean;
rightAction?: React.ReactNode;
} }
export function DetailPageShell({ export function DetailPageShell({ children, onBack }: DetailPageShellProps) {
children,
onBack,
tone,
moduleCode: propModuleCode,
hideFavorite,
rightAction,
}: DetailPageShellProps) {
const [isFavorite, setIsFavorite] = useState(false); const [isFavorite, setIsFavorite] = useState(false);
const params = useLocalSearchParams<{ moduleCode?: string }>(); const { moduleCode } = useLocalSearchParams<{ moduleCode?: string }>();
const currentModuleCode = const currentModuleCode = typeof moduleCode === "string" ? moduleCode : "";
typeof propModuleCode === "string" && propModuleCode.trim()
? propModuleCode.trim()
: typeof params.moduleCode === "string"
? params.moduleCode.trim()
: "";
const moduleDisplay = useModuleDisplayName(currentModuleCode); const moduleDisplay = useModuleDisplayName(currentModuleCode);
const shouldHideFavorite = hideFavorite ?? moduleDisplay.isPointsModule;
const searchAction = currentModuleCode ? ( const searchAction = currentModuleCode ? (
<Pressable <Pressable
accessibilityRole="button" accessibilityRole="button"
@ -53,7 +34,7 @@ export function DetailPageShell({
</Pressable> </Pressable>
) : null; ) : null;
const favoriteAction = !shouldHideFavorite ? ( const favoriteAction = (
<Pressable <Pressable
accessibilityRole="button" accessibilityRole="button"
accessibilityLabel={isFavorite ? "Remove from favorites" : "Add to favorites"} accessibilityLabel={isFavorite ? "Remove from favorites" : "Add to favorites"}
@ -67,21 +48,12 @@ export function DetailPageShell({
color={isFavorite ? Colors.error : Colors.textPrimary} color={isFavorite ? Colors.error : Colors.textPrimary}
/> />
</Pressable> </Pressable>
) : null; );
const headerActions = searchAction || favoriteAction || rightAction ? (
<View style={styles.actions}>
{searchAction}
{favoriteAction}
{rightAction}
</View>
) : undefined;
return ( return (
<SafeAreaView style={styles.screen} edges={["top", "left", "right"]}> <SafeAreaView style={styles.screen} edges={["top", "left", "right"]}>
<ContentPageHeader <ContentPageHeader
title={moduleDisplay.name} title={moduleDisplay.name}
tone={tone}
onBack={onBack} onBack={onBack}
onTitlePress={ onTitlePress={
currentModuleCode currentModuleCode
@ -92,7 +64,12 @@ export function DetailPageShell({
currentModuleCode ? `Open ${moduleDisplay.name} home` : moduleDisplay.name currentModuleCode ? `Open ${moduleDisplay.name} home` : moduleDisplay.name
} }
fallbackRoute={moduleDisplay.homeRoute} fallbackRoute={moduleDisplay.homeRoute}
right={headerActions} right={
<View style={styles.actions}>
{searchAction}
{favoriteAction}
</View>
}
/> />
<View style={styles.body}>{children}</View> <View style={styles.body}>{children}</View>
</SafeAreaView> </SafeAreaView>

View File

@ -3,44 +3,24 @@ import { StyleSheet, Text, View } from "react-native";
import { moderateScale, verticalScale } from "react-native-size-matters"; import { moderateScale, verticalScale } from "react-native-size-matters";
import { Colors } from "@/theme"; import { Colors } from "@/theme";
import {
type PageTone,
toneColors,
usePageTone,
} from "../../context/PageToneContext";
export function Hero({ export function Hero({
eyebrow, eyebrow,
title, title,
subtitle, subtitle,
meta, meta,
tone,
}: { }: {
eyebrow?: string; eyebrow?: string;
title: string; title: string;
subtitle?: string; subtitle?: string;
meta?: string; meta?: string;
tone?: PageTone;
}) { }) {
const { tone: contextTone } = usePageTone();
const currentTone = tone || contextTone || "green";
const colors = toneColors[currentTone] || toneColors.green;
return ( return (
<View <View style={styles.card}>
style={[ <View style={styles.accent} />
styles.card,
{ backgroundColor: colors.soft, borderColor: colors.border },
]}
>
<View style={[styles.accent, { backgroundColor: colors.accent }]} />
<View style={styles.content}> <View style={styles.content}>
{eyebrow ? ( {eyebrow ? <Text style={styles.eyebrow}>{eyebrow}</Text> : null}
<Text style={[styles.eyebrow, { color: colors.accent }]}> <Text style={styles.title}>{title}</Text>
{eyebrow}
</Text>
) : null}
<Text style={[styles.title, { color: colors.title }]}>{title}</Text>
{subtitle ? <Text style={styles.subtitle}>{subtitle}</Text> : null} {subtitle ? <Text style={styles.subtitle}>{subtitle}</Text> : null}
{meta ? <Text style={styles.meta}>{meta}</Text> : null} {meta ? <Text style={styles.meta}>{meta}</Text> : null}
</View> </View>

View File

@ -7,52 +7,37 @@ import { asString } from "../helpers/value";
import type { ContentMediaItem } from "../../types/media.types"; import type { ContentMediaItem } from "../../types/media.types";
const getImagePath = (item: Record<string, unknown>): string => {
return asString(
item.image_path || item.url || item.image_url || item.uri || item.path
).trim();
};
const getImageName = (item: Record<string, unknown>): string => {
return asString(item.image_name || item.name || item.title || item.caption).trim();
};
export function ImageGallery({ images }: { images: Record<string, unknown>[] }) { export function ImageGallery({ images }: { images: Record<string, unknown>[] }) {
const relationalMedia = useRelationalContentMedia(); const relationalMedia = useRelationalContentMedia();
const visible = images.filter((item) => getImagePath(item).length > 0);
// Explicit direct images passed via props take priority over relational media
if (visible.length > 0) {
const fallbackMedia: ContentMediaItem[] = visible.map((item, index) => {
const path = getImagePath(item);
const name = getImageName(item);
return {
id: `${path}-${index}`,
media_asset_id: `${path}-${index}`,
media_role: index === 0 ? "primary" : "gallery",
usage_type: "visual_reference",
sort_order: index,
caption: name || null,
alt_text: name || "Module image",
mime_type: "image/jpeg",
width: null,
height: null,
url: path,
storage_key: null,
requires_auth: false,
};
});
return <ContentMediaGallery media={fallbackMedia} title="Visual Reference" />;
}
// Fallback to relational content media when no direct images are provided
if (relationalMedia.length > 0) { if (relationalMedia.length > 0) {
return <ContentMediaGallery media={relationalMedia} title="Visual Reference" />; return <ContentMediaGallery media={relationalMedia} title="Visual reference" />;
} }
return null; const visible = images.filter((item) => asString(item.image_path).trim().length > 0);
if (!visible.length) return null;
const fallbackMedia: ContentMediaItem[] = visible.map((item, index) => {
const path = asString(item.image_path).trim();
const name = asString(item.image_name).trim();
return {
id: `${path}-${index}`,
media_asset_id: `${path}-${index}`,
media_role: index === 0 ? "primary" : "gallery",
usage_type: "visual_reference",
sort_order: index,
caption: name || null,
alt_text: name || "Module image",
mime_type: "image/jpeg",
width: null,
height: null,
url: path,
storage_key: null,
requires_auth: false,
};
});
return <ContentMediaGallery media={fallbackMedia} title="Visual reference" />;
} }
const styles = StyleSheet.create({ const styles = StyleSheet.create({

View File

@ -29,7 +29,8 @@ const styles = StyleSheet.create({
lineHeight: 17, lineHeight: 17,
fontWeight: "700", fontWeight: "700",
color: "#597064", color: "#597064",
letterSpacing: 0.15, textTransform: "uppercase",
letterSpacing: 0.4,
}, },
value: { fontSize: 16, lineHeight: 25, color: "#334155" }, value: { fontSize: 16, lineHeight: 25, color: "#334155" },
}); });

View File

@ -9,13 +9,7 @@ import { ContentValue } from "./ContentValue";
* content references. ContentValue recursively handles arrays, objects and * content references. ContentValue recursively handles arrays, objects and
* hydrated content/template references. * hydrated content/template references.
*/ */
export function ObjectSections({ export function ObjectSections({ value }: { value: Record<string, unknown> }) {
value,
withTopDivider = false,
}: {
value: Record<string, unknown>;
withTopDivider?: boolean;
}) {
const entries = Object.entries(value).filter(([, child]) => const entries = Object.entries(value).filter(([, child]) =>
isPresent(child), isPresent(child),
); );
@ -24,14 +18,8 @@ export function ObjectSections({
return ( return (
<View style={styles.root}> <View style={styles.root}>
{entries.map(([key, child], index) => ( {entries.map(([key, child]) => (
<View <View key={key} style={styles.section}>
key={key}
style={[
styles.section,
(index > 0 || withTopDivider) && styles.divider,
]}
>
<Text style={styles.label}>{humanizeKey(key)}</Text> <Text style={styles.label}>{humanizeKey(key)}</Text>
<ContentValue value={child} /> <ContentValue value={child} />
</View> </View>
@ -51,19 +39,13 @@ function isPresent(value: unknown): boolean {
const styles = StyleSheet.create({ const styles = StyleSheet.create({
root: { gap: 16 }, root: { gap: 16 },
section: { section: { gap: 7 },
gap: 7,
},
divider: {
paddingTop: 12,
borderTopWidth: StyleSheet.hairlineWidth,
borderTopColor: "#E8ECEF",
},
label: { label: {
fontWeight: "700", fontWeight: "700",
fontSize: 13, fontSize: 13,
lineHeight: 18, lineHeight: 18,
color: "#536F61", color: "#536F61",
letterSpacing: 0.15, textTransform: "uppercase",
letterSpacing: 0.35,
}, },
}); });

View File

@ -1,115 +0,0 @@
import React from "react";
import {
StyleProp,
StyleSheet,
Text,
TextStyle,
View,
ViewStyle,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { moderateScale, verticalScale } from "react-native-size-matters";
import { Colors } from "@/theme";
export interface OverviewCardProps {
title?: string;
icon?: keyof typeof Ionicons.glyphMap;
iconColor?: string;
iconSize?: number;
text?: string | null;
paragraphs?: Array<string | null | undefined>;
children?: React.ReactNode;
style?: StyleProp<ViewStyle>;
titleStyle?: StyleProp<TextStyle>;
textStyle?: StyleProp<TextStyle>;
}
export function OverviewCard({
title = "Overview",
icon = "information-circle",
iconColor = Colors.primary,
iconSize = moderateScale(20),
text,
paragraphs,
children,
style,
titleStyle,
textStyle,
}: OverviewCardProps) {
const filteredParagraphs = paragraphs?.filter(
(p): p is string => typeof p === "string" && p.trim().length > 0,
);
const hasText = typeof text === "string" && text.trim().length > 0;
const hasParagraphs =
Array.isArray(filteredParagraphs) && filteredParagraphs.length > 0;
if (!hasText && !hasParagraphs && !children) {
return null;
}
return (
<View style={[styles.card, style]}>
<View style={styles.header}>
{icon ? (
<Ionicons name={icon} size={iconSize} color={iconColor} />
) : null}
<Text style={[styles.title, titleStyle]}>{title}</Text>
</View>
{hasText ? (
<Text style={[styles.text, textStyle]}>{text}</Text>
) : null}
{hasParagraphs
? filteredParagraphs.map((para, index) => (
<Text
key={index}
style={[
index === 0 && !hasText ? styles.text : styles.paragraph,
textStyle,
]}
>
{para}
</Text>
))
: null}
{children}
</View>
);
}
const styles = StyleSheet.create({
card: {
backgroundColor: Colors.surface,
borderRadius: moderateScale(12),
padding: moderateScale(14),
borderWidth: 1,
borderColor: Colors.border,
},
header: {
flexDirection: "row",
alignItems: "center",
gap: moderateScale(8),
marginBottom: verticalScale(8),
},
title: {
fontSize: moderateScale(16),
fontWeight: "700",
color: Colors.textPrimary,
},
text: {
fontSize: moderateScale(13),
lineHeight: moderateScale(20),
color: Colors.textSecondary,
},
paragraph: {
fontSize: moderateScale(13),
lineHeight: moderateScale(20),
color: Colors.textSecondary,
marginTop: verticalScale(8),
},
});

View File

@ -53,7 +53,8 @@ const styles = StyleSheet.create({
lineHeight: 17, lineHeight: 17,
fontWeight: "700", fontWeight: "700",
color: "#617468", color: "#617468",
letterSpacing: 0.15, textTransform: "uppercase",
letterSpacing: 0.35,
}, },
value: { fontSize: 15, lineHeight: 23, color: "#334155" }, value: { fontSize: 15, lineHeight: 23, color: "#334155" },
}); });

View File

@ -9,15 +9,7 @@ import { Spacing } from "@/theme/spacing";
import { ContentLink } from "../../components/navigation/ContentLink"; import { ContentLink } from "../../components/navigation/ContentLink";
import { parseNavigableContentReference } from "../../utils/content-reference"; import { parseNavigableContentReference } from "../../utils/content-reference";
export interface ReferenceChipListProps { export function ReferenceChipList({ value }: { value: unknown }) {
value: unknown;
asBulletList?: boolean;
}
export function ReferenceChipList({
value,
asBulletList = true,
}: ReferenceChipListProps) {
const values = Array.isArray(value) ? value : [value]; const values = Array.isArray(value) ? value : [value];
const visible = values.filter( const visible = values.filter(
(item) => item !== null && item !== undefined && item !== "", (item) => item !== null && item !== undefined && item !== "",
@ -26,70 +18,47 @@ export function ReferenceChipList({
if (!visible.length) return null; if (!visible.length) return null;
return ( return (
<View style={asBulletList ? styles.bulletList : styles.list}> <View style={styles.list}>
{visible.map((item, index) => { {visible.map((item, index) => {
const reference = parseNavigableContentReference(item); const reference = parseNavigableContentReference(item);
const renderChip = () => { if (reference) {
if (reference) { const label =
const label = reference.label?.trim() ||
reference.label?.trim() || (reference.type === "content_ref"
(reference.type === "content_ref" ? reference.target.source_key?.trim()
? reference.target.source_key?.trim() : null) ||
: null) || "Open";
"Open";
return (
<ContentLink
key={
reference.type === "content_ref"
? `content-${reference.target.content_id}`
: `template-${reference.target.module_code}-${reference.target.template_code}`
}
reference={reference}
style={styles.link}
>
<View style={styles.linkChip}>
<Text style={styles.linkText}>{label}</Text>
<Ionicons
name="chevron-forward"
size={14}
color={Colors.primaryDark}
/>
</View>
</ContentLink>
);
}
const text = scalarLabel(item);
if (!text) return null;
return ( return (
<View key={`${text}-${index}`} style={styles.chip}> <ContentLink
<Text style={styles.text}>{text}</Text> key={
</View> reference.type === "content_ref"
); ? `content-${reference.target.content_id}`
}; : `template-${reference.target.module_code}-${reference.target.template_code}`
}
if (asBulletList) { reference={reference}
const key = reference style={styles.link}
? (reference.type === "content_ref" >
? `bullet-${reference.target.content_id}-${index}` <View style={styles.linkChip}>
: `bullet-${reference.target.module_code}-${reference.target.template_code}-${index}`) <Text style={styles.linkText}>{label}</Text>
: `bullet-${index}`; <Ionicons
name="chevron-forward"
return ( size={14}
<View key={key} style={styles.bulletRow}> color={Colors.primaryDark}
<View style={styles.dot} /> />
{renderChip()} </View>
</View> </ContentLink>
); );
} }
const text = scalarLabel(item);
if (!text) return null;
return ( return (
<React.Fragment key={index}> <View key={`${text}-${index}`} style={styles.chip}>
{renderChip()} <Text style={styles.text}>{text}</Text>
</React.Fragment> </View>
); );
})} })}
</View> </View>
@ -115,21 +84,6 @@ const styles = StyleSheet.create({
flexWrap: "wrap", flexWrap: "wrap",
gap: Spacing.sm, gap: Spacing.sm,
}, },
bulletList: {
gap: 10,
alignItems: "flex-start",
},
bulletRow: {
flexDirection: "row",
alignItems: "center",
gap: 10,
},
dot: {
width: 6,
height: 6,
borderRadius: 3,
backgroundColor: Colors.primary,
},
link: { link: {
alignSelf: "flex-start", alignSelf: "flex-start",
borderRadius: Radius.full, borderRadius: Radius.full,

Some files were not shown because too many files have changed in this diff Show More