Compare commits

..

No commits in common. "main" and "fix/issue-12-subscription-back-navigation" have entirely different histories.

155 changed files with 1781 additions and 8567 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

19
android/.gitignore vendored
View File

@ -1,19 +0,0 @@
# OSX
#
.DS_Store
# Android/IntelliJ
#
build/
.idea
.gradle
local.properties
*.iml
*.hprof
.cxx/
# generated inline modules
app/src/main/java/inline/
# Bundle artifacts
*.jsbundle

View File

@ -1,193 +0,0 @@
apply plugin: "com.android.application"
apply plugin: "org.jetbrains.kotlin.android"
apply plugin: "com.facebook.react"
def projectRoot = rootDir.getAbsoluteFile().getParentFile().getAbsolutePath()
/**
* This is the configuration block to customize your React Native Android app.
* By default you don't need to apply any configuration, just uncomment the lines you need.
*/
react {
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()
// 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()
enableBundleCompression = (findProperty('android.enableBundleCompression') ?: false).toBoolean()
// Use Expo CLI to bundle the app, this ensures the Metro config
// works correctly with Expo projects.
cliFile = new File(["node", "--print", "require.resolve('@expo/cli', { paths: [require.resolve('expo/package.json')] })"].execute(null, rootDir).text.trim())
bundleCommand = "export:embed"
/* Folders */
// The root of your project, i.e. where "package.json" lives. Default is '../..'
// root = file("../../")
// The folder where the react-native NPM package is. Default is ../../node_modules/react-native
// reactNativeDir = file("../../node_modules/react-native")
// The folder where the react-native Codegen package is. Default is ../../node_modules/@react-native/codegen
// codegenDir = file("../../node_modules/@react-native/codegen")
/* Variants */
// The list of variants to that are debuggable. For those we're going to
// skip the bundling of the JS bundle and the assets. By default is just 'debug'.
// If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants.
// debuggableVariants = ["liteDebug", "prodDebug"]
/* Bundling */
// A list containing the node command and its flags. Default is just 'node'.
// nodeExecutableAndArgs = ["node"]
//
// The path to the CLI configuration file. Default is empty.
// bundleConfig = file(../rn-cli.config.js)
//
// The name of the generated asset file containing your JS bundle
// bundleAssetName = "MyApplication.android.bundle"
//
// The entry file for bundle generation. Default is 'index.android.js' or 'index.js'
// entryFile = file("../js/MyApplication.android.js")
//
// A list of extra flags to pass to the 'bundle' commands.
// See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle
// extraPackagerArgs = []
/* Hermes Commands */
// The hermes compiler command to run. By default it is 'hermesc'
// hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc"
//
// The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map"
// hermesFlags = ["-O", "-output-source-map"]
/* Autolinking */
autolinkLibrariesWithApp()
}
/**
* Set this to true in release builds to optimize the app using [R8](https://developer.android.com/topic/performance/app-optimization/enable-app-optimization).
*/
def enableMinifyInReleaseBuilds = (findProperty('android.enableMinifyInReleaseBuilds') ?: false).toBoolean()
/**
* The preferred build flavor of JavaScriptCore (JSC)
*
* For example, to use the international variant, you can use:
* `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
*
* The international variant includes ICU i18n library and necessary data
* allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
* give correct results when using with locales other than en-US. Note that
* this variant is about 6MiB larger per architecture than default.
*/
def jscFlavor = 'io.github.react-native-community:jsc-android:2026004.+'
android {
ndkVersion rootProject.ext.ndkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
compileSdk rootProject.ext.compileSdkVersion
namespace 'com.renown.mobile.acupedia'
defaultConfig {
applicationId 'com.renown.mobile.acupedia'
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0.0"
buildConfigField "String", "REACT_NATIVE_RELEASE_LEVEL", "\"${findProperty('reactNativeReleaseLevel') ?: 'stable'}\""
}
def keystorePropertiesFile = rootProject.file("keystore.properties")
def keystoreProperties = new Properties()
if (keystorePropertiesFile.exists()) {
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}
signingConfigs {
debug {
storeFile file('debug.keystore')
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
}
release {
if (keystorePropertiesFile.exists()) {
storeFile file(keystoreProperties['storeFile'])
storePassword keystoreProperties['storePassword']
keyAlias keystoreProperties['keyAlias']
keyPassword keystoreProperties['keyPassword']
}
}
}
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
signingConfig (keystorePropertiesFile.exists() ? signingConfigs.release : signingConfigs.debug)
def enableShrinkResources = findProperty('android.enableShrinkResourcesInReleaseBuilds') ?: 'false'
shrinkResources enableShrinkResources.toBoolean()
minifyEnabled enableMinifyInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
def enablePngCrunchInRelease = findProperty('android.enablePngCrunchInReleaseBuilds') ?: 'true'
crunchPngs enablePngCrunchInRelease.toBoolean()
}
}
packagingOptions {
jniLibs {
def enableLegacyPackaging = findProperty('expo.useLegacyPackaging') ?: 'false'
useLegacyPackaging enableLegacyPackaging.toBoolean()
}
}
androidResources {
ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:!CVS:!thumbs.db:!picasa.ini:!*~'
}
}
// Apply static values from `gradle.properties` to the `android.packagingOptions`
// Accepts values in comma delimited lists, example:
// android.packagingOptions.pickFirsts=/LICENSE,**/picasa.ini
["pickFirsts", "excludes", "merges", "doNotStrip"].each { prop ->
// Split option: 'foo,bar' -> ['foo', 'bar']
def options = (findProperty("android.packagingOptions.$prop") ?: "").split(",");
// Trim all elements in place.
for (i in 0..<options.size()) options[i] = options[i].trim();
// `[] - ""` is essentially `[""].filter(Boolean)` removing all empty strings.
options -= ""
if (options.length > 0) {
println "android.packagingOptions.$prop += $options ($options.length)"
// Ex: android.packagingOptions.pickFirsts += '**/SCCS/**'
options.each {
android.packagingOptions[prop] += it
}
}
}
dependencies {
// The version of react-native is set by the React Native Gradle Plugin
implementation("com.facebook.react:react-android")
def isGifEnabled = (findProperty('expo.gif.enabled') ?: "") == "true";
def isWebpEnabled = (findProperty('expo.webp.enabled') ?: "") == "true";
def isWebpAnimatedEnabled = (findProperty('expo.webp.animated') ?: "") == "true";
if (isGifEnabled) {
// For animated gif support
implementation("com.facebook.fresco:animated-gif:${expoLibs.versions.fresco.get()}")
}
if (isWebpEnabled) {
// For webp support
implementation("com.facebook.fresco:webpsupport:${expoLibs.versions.fresco.get()}")
if (isWebpAnimatedEnabled) {
// Animated webp support
implementation("com.facebook.fresco:animated-webp:${expoLibs.versions.fresco.get()}")
}
}
if (hermesEnabled.toBoolean()) {
implementation("com.facebook.react:hermes-android")
} else {
implementation jscFlavor
}
}

Binary file not shown.

View File

@ -1,14 +0,0 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# react-native-reanimated
-keep class com.swmansion.reanimated.** { *; }
-keep class com.facebook.react.turbomodule.** { *; }
# Add any project specific keep options here:

View File

@ -1,7 +0,0 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<application android:usesCleartextTraffic="true" tools:targetApi="28" tools:ignore="GoogleAppIndexingWarning" tools:replace="android:usesCleartextTraffic" />
</manifest>

View File

@ -1,7 +0,0 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<application android:usesCleartextTraffic="true" tools:targetApi="28" tools:ignore="GoogleAppIndexingWarning" tools:replace="android:usesCleartextTraffic" />
</manifest>

View File

@ -1,33 +0,0 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32" tools:replace="android:maxSdkVersion"/>
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="32" tools:replace="android:maxSdkVersion"/>
<queries>
<intent>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="https"/>
</intent>
</queries>
<application android:name=".MainApplication" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:allowBackup="false" android:theme="@style/AppTheme" android:supportsRtl="true" android:enableOnBackInvokedCallback="false" android:usesCleartextTraffic="true">
<meta-data android:name="expo.modules.updates.ENABLED" android:value="false"/>
<meta-data android:name="expo.modules.updates.ENABLE_BSDIFF_PATCH_SUPPORT" android:value="true"/>
<meta-data android:name="expo.modules.updates.EXPO_UPDATES_CHECK_ON_LAUNCH" android:value="ALWAYS"/>
<meta-data android:name="expo.modules.updates.EXPO_UPDATES_LAUNCH_WAIT_MS" android:value="0"/>
<activity android:name=".MainActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|uiMode|smallestScreenSize|assetsPaths" android:launchMode="singleTask" android:windowSoftInputMode="adjustResize" android:theme="@style/Theme.App.SplashScreen" android:exported="true" android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="myapp"/>
<data android:scheme="acupedia"/>
</intent-filter>
</activity>
</application>
</manifest>

View File

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

View File

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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

View File

@ -1,6 +0,0 @@
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/splashscreen_background"/>
<item>
<bitmap android:gravity="center" android:src="@drawable/splashscreen_logo"/>
</item>
</layer-list>

View File

@ -1,37 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2014 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetLeft="@dimen/abc_edit_text_inset_horizontal_material"
android:insetRight="@dimen/abc_edit_text_inset_horizontal_material"
android:insetTop="@dimen/abc_edit_text_inset_top_material"
android:insetBottom="@dimen/abc_edit_text_inset_bottom_material"
>
<selector>
<!--
This file is a copy of abc_edit_text_material (https://bit.ly/3k8fX7I).
The item below with state_pressed="false" and state_focused="false" causes a NullPointerException.
NullPointerException:tempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)'
<item android:state_pressed="false" android:state_focused="false" android:drawable="@drawable/abc_textfield_default_mtrl_alpha"/>
For more info, see https://bit.ly/3CdLStv (react-native/pull/29452) and https://bit.ly/3nxOMoR.
-->
<item android:state_enabled="false" android:drawable="@drawable/abc_textfield_default_mtrl_alpha"/>
<item android:drawable="@drawable/abc_textfield_activated_mtrl_alpha"/>
</selector>
</inset>

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@mipmap/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
<monochrome android:drawable="@mipmap/ic_launcher_monochrome"/>
</adaptive-icon>

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@mipmap/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
<monochrome android:drawable="@mipmap/ic_launcher_monochrome"/>
</adaptive-icon>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

View File

@ -1 +0,0 @@
<resources/>

View File

@ -1,6 +0,0 @@
<resources>
<color name="splashscreen_background">#208AEF</color>
<color name="iconBackground">#E6F4FE</color>
<color name="colorPrimary">#023c69</color>
<color name="colorPrimaryDark">#208AEF</color>
</resources>

View File

@ -1,6 +0,0 @@
<resources>
<string name="app_name">acupedia</string>
<string name="expo_system_ui_user_interface_style" translatable="false">automatic</string>
<string name="expo_splash_screen_resize_mode" translatable="false">contain</string>
<string name="expo_splash_screen_status_bar_translucent" translatable="false">false</string>
</resources>

View File

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

View File

@ -1,24 +0,0 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath('com.android.tools.build:gradle')
classpath('com.facebook.react:react-native-gradle-plugin')
classpath('org.jetbrains.kotlin:kotlin-gradle-plugin')
}
}
allprojects {
repositories {
google()
mavenCentral()
maven { url 'https://www.jitpack.io' }
}
}
apply plugin: "expo-root-project"
apply plugin: "com.facebook.react.rootproject"

View File

@ -1,66 +0,0 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx512m -XX:MaxMetaspaceSize=256m
org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Enable AAPT2 PNG crunching
android.enablePngCrunchInReleaseBuilds=true
# Use this property to specify which architecture you want to build.
# You can also override it from the CLI using
# ./gradlew <task> -PreactNativeArchitectures=x86_64
reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64
# Use this property to enable support to the new architecture.
# This will allow you to use TurboModules and the Fabric render in
# your application. You should enable this flag either if you want
# to write custom TurboModules/Fabric components OR use libraries that
# are providing them.
newArchEnabled=true
# Use this property to enable or disable the Hermes JS engine.
# If set to false, you will be using JSC instead.
hermesEnabled=true
# Use this property to enable edge-to-edge display support.
# This allows your app to draw behind system bars for an immersive UI.
# Note: Only works with ReactActivity and should not be used with custom Activity.
edgeToEdgeEnabled=true
# Enable GIF support in React Native images (~200 B increase)
expo.gif.enabled=true
# Enable webp support in React Native images (~85 KB increase)
expo.webp.enabled=true
# Enable animated webp support (~3.4 MB increase)
# Disabled by default because iOS doesn't support animated webp
expo.webp.animated=false
# Enable network inspector
EX_DEV_CLIENT_NETWORK_INSPECTOR=true
# Use legacy packaging to compress native libraries in the resulting APK.
expo.useLegacyPackaging=false
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

Binary file not shown.

View File

@ -1,7 +0,0 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

248
android/gradlew vendored
View File

@ -1,248 +0,0 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

98
android/gradlew.bat vendored
View File

@ -1,98 +0,0 @@
@REM Copyright (c) Meta Platforms, Inc. and affiliates.
@REM
@REM This source code is licensed under the MIT license found in the
@REM LICENSE file in the root directory of this source tree.
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -1,4 +0,0 @@
storeFile=acupedia-release.keystore
storePassword=Cspl@1234
keyAlias=acupedia-release
keyPassword=Cspl@1234

View File

@ -1,39 +0,0 @@
pluginManagement {
def reactNativeGradlePlugin = new File(
providers.exec {
workingDir(rootDir)
commandLine("node", "--print", "require.resolve('@react-native/gradle-plugin/package.json', { paths: [require.resolve('react-native/package.json')] })")
}.standardOutput.asText.get().trim()
).getParentFile().absolutePath
includeBuild(reactNativeGradlePlugin)
def expoPluginsPath = new File(
providers.exec {
workingDir(rootDir)
commandLine("node", "--print", "require.resolve('expo-modules-autolinking/package.json', { paths: [require.resolve('expo/package.json')] })")
}.standardOutput.asText.get().trim(),
"../android/expo-gradle-plugin"
).absolutePath
includeBuild(expoPluginsPath)
}
plugins {
id("com.facebook.react.settings")
id("expo-autolinking-settings")
}
extensions.configure(com.facebook.react.ReactSettingsExtension) { ex ->
if (System.getenv('EXPO_USE_COMMUNITY_AUTOLINKING') == '1') {
ex.autolinkLibrariesFromCommand()
} else {
ex.autolinkLibrariesFromCommand(expoAutolinking.rnConfigCommand)
}
}
expoAutolinking.useExpoModules()
rootProject.name = 'acupedia'
expoAutolinking.useExpoVersionCatalog()
include ':app'
includeBuild(expoAutolinking.reactNativeGradlePlugin)

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,11 +24,11 @@
"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": {
"output": "single", "output": "static",
"favicon": "./assets/images/favicon.png" "favicon": "./assets/images/favicon.png"
}, },
"plugins": [ "plugins": [

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,7 +1,7 @@
<?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>
@ -27,8 +27,8 @@
<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>
@ -77,5 +77,5 @@
<string>Automatic</string> <string>Automatic</string>
<key>UIViewControllerBasedStatusBarAppearance</key> <key>UIViewControllerBasedStatusBarAppearance</key>
<false/> <false/>
</dict> </dict>
</plist> </plist>

View File

@ -1,12 +0,0 @@
const { getDefaultConfig } = require('expo/metro-config');
const config = getDefaultConfig(__dirname);
// Prioritize CommonJS / require / react-native conditions to avoid ESM import.meta in web builds
config.resolver.unstable_conditionNames = ['browser', 'require', 'react-native'];
if (config.resolver.unstable_conditionsByPlatform) {
config.resolver.unstable_conditionsByPlatform.web = ['browser', 'require', 'react-native'];
}
module.exports = config;

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 handleAuthAction = () => {
if (isAuthenticated) {
const doLogout = () => { const doLogout = () => {
setLogoutModalVisible(false);
logout(); logout();
router.replace("/login"); router.replace("/login");
}; };
const handleAuthAction = () => { if (Platform.OS === "web") {
if (isAuthenticated) { const confirmed = typeof window !== "undefined" ? window.confirm("Are you sure you want to logout?") : true;
setLogoutModalVisible(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

@ -1,34 +1,5 @@
import { router, Stack } from "expo-router"; import { Stack } from "expo-router";
import React from "react"; import React from "react";
// ============================================================================
// GLOBAL NAVIGATION THROTTLE (Generic Fix for Repeated Click / Double Navigation)
// ============================================================================
const NAVIGATION_THROTTLE_MS = 700;
let lastNavigationTimestamp = 0;
const originalPush = router.push.bind(router);
const originalNavigate = router.navigate.bind(router);
router.push = ((...args: Parameters<typeof originalPush>) => {
const now = Date.now();
if (now - lastNavigationTimestamp < NAVIGATION_THROTTLE_MS) {
return;
}
lastNavigationTimestamp = now;
return originalPush(...args);
}) as typeof router.push;
router.navigate = ((...args: Parameters<typeof originalNavigate>) => {
const now = Date.now();
if (now - lastNavigationTimestamp < NAVIGATION_THROTTLE_MS) {
return;
}
lastNavigationTimestamp = now;
return originalNavigate(...args);
}) as typeof router.navigate;
// ============================================================================
import * as RN from "react-native"; import * as RN from "react-native";
import { import {
useFonts, useFonts,

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 (
typeof errMsg === "string" &&
errMsg.toLowerCase().includes("same")
) {
setNewError(errMsg);
} else if (
typeof errMsg === "string" &&
(errMsg.toLowerCase().includes("current") || errMsg.toLowerCase().includes("old"))
) {
setCurrentError(errMsg); setCurrentError(errMsg);
} else if ( if (Platform.OS === "web") {
typeof errMsg === "string" && window.alert(errMsg);
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,33 +1,19 @@
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"
@ -41,34 +27,13 @@ export default function LoginHeader() {
/> />
</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: {

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,23 +44,18 @@ 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(),
selectedCountry.code,
selectedCountry.country
);
if (err) {
setPhoneError(err);
hasError = true; hasError = true;
} }
}
if (!password) { if (!password) {
setPasswordError("Password is required"); setPasswordError("Password is required");
@ -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}>
<View style={[styles.phoneContainer, phoneError ? styles.errorBorder : null]}>
<Pressable
accessibilityRole="button"
accessibilityLabel="Select Country and Dial Code"
onPress={() => setShowCountryModal(true)}
style={styles.dialCodeButton}
>
<Text style={styles.dialCodeText}>{selectedCountry.label}</Text>
<Ionicons
name="chevron-down"
size={moderateScale(14)}
color={AuthColors.textSecondary}
style={{ marginLeft: scale(5) }}
/>
</Pressable>
<View style={styles.phoneDivider} />
<TextInput
value={phone} value={phone}
onChangeText={handlePhoneChange} onChangeText={handlePhoneChange}
placeholder={selectedCountry.placeholder || "Phone Number (Optional)"} placeholder="Phone Number (Optional)"
placeholderTextColor={AuthColors.textSecondary}
keyboardType="number-pad" keyboardType="number-pad"
autoCapitalize="none" autoCapitalize="none"
autoCorrect={false} autoCorrect={false}
textContentType="telephoneNumber" textContentType="telephoneNumber"
maxLength={selectedCountry.maxLength} maxLength={10}
style={styles.phoneInput} leftIcon="call-outline"
error={phoneError}
/> />
</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

@ -1,15 +1,10 @@
import React, { type ReactNode, useCallback } from "react"; import React, { type ReactNode } from "react";
import { BackHandler, Platform, Pressable, StyleSheet, Text, View } from "react-native"; import { 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 } 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,32 +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(
useCallback(() => {
if (!onBack) return;
const subscription = BackHandler.addEventListener(
"hardwareBackPress",
() => {
onBack();
return true;
}
);
return () => {
subscription.remove();
};
}, [onBack])
);
const handleBack = () => { const handleBack = () => {
if (onBack) { if (onBack) {
onBack(); onBack();
@ -73,7 +41,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 +58,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 +121,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"),
)
.map(([key, value]) => {
const label = resolveAttributeLabel(key, definitionMap);
return (
<SectionCard key={key} title={label}>
<ContentValue value={value} /> <ContentValue value={value} />
</SectionCard> </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}>
{subtitle} {label}
</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}>
{subtitle} {label}
</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,644 +1,55 @@
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.content_label) || item.summary || "Open content";
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.subtitle) ||
(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)
: null) ||
asString(attributes.description) ||
item.summary ||
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 ? ( <Text style={styles.description} numberOfLines={1}>
<Text numberOfLines={2} style={styles.subtitle}>
{label} {label}
</Text> </Text>
) : 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 +77,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,13 @@
import React, { useMemo } from "react"; import React from "react";
import { asString } from "../helpers/value"; import { Pressable, Text, View } from "react-native";
import { asString, asStringArray } from "../helpers/value";
import { CollectionScaffold } from "../shared/CollectionScaffold"; import { CollectionScaffold } from "../shared/CollectionScaffold";
import { ChipList } from "../shared/ChipList";
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} />;
@ -56,17 +25,15 @@ export function AcuPointIndexCardRenderer({ item, onPress }: CollectionItemRende
} }
export function AcuPointCardRenderer({ item, onPress }: CollectionItemRendererProps) { export function AcuPointCardRenderer({ item, onPress }: CollectionItemRendererProps) {
const a = item.attributes; const a = item.attributes;
const altNames = [asString(a.alt_name_1), asString(a.alt_name_2)].filter(Boolean).join(" · ");
const subtitle =
altNames ||
asString(a.pt_meaning) ||
asString(a.channel);
return ( return (
<StandardIndexCard <Pressable onPress={onPress}>
title={asString(a.point_name) || asString(a.name) || item.title} <View style={{ padding: 14, gap: 7 }}>
subtitle={subtitle || null} <View style={{ flexDirection: "row", gap: 10 }}>
onPress={onPress} <Text style={{ flex: 1, fontSize: 17, fontWeight: "600" }}>{asString(a.point_name) || asString(a.name) || item.title}</Text>
/> </View>
<Text>{asString(a.channel)}</Text>
<ChipList items={asStringArray(a.point_type).slice(0, 3)} />
</View>
</Pressable>
); );
} }

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,
@ -31,9 +30,6 @@ function extractOverviewFromData(data: Record<string, unknown> | undefined): str
return ""; return "";
} }
const DEFAULT_QI_BLOOD_OVERVIEW =
"Qi and Blood (Qi Xue) pattern identification assesses disharmonies in the fundamental vital substances of the body. Pathological changes in Qi, Blood, and Body Fluids reflect deficiencies, stagnation, rebellion, and collapse affecting overall vitality and organ function.";
export function QiBloodCollectionRenderer(props: CollectionRendererProps) { export function QiBloodCollectionRenderer(props: CollectionRendererProps) {
// Dynamically load the overview from the module's identification template (m0013_ct0006) // Dynamically load the overview from the module's identification template (m0013_ct0006)
const overviewQuery = useSingleTemplateContentQuery({ const overviewQuery = useSingleTemplateContentQuery({
@ -43,10 +39,9 @@ export function QiBloodCollectionRenderer(props: CollectionRendererProps) {
const overviewText = useMemo(() => { const overviewText = useMemo(() => {
if (overviewQuery.resolution.status === "ready") { if (overviewQuery.resolution.status === "ready") {
const extracted = extractOverviewFromData(overviewQuery.resolution.data); return extractOverviewFromData(overviewQuery.resolution.data);
if (extracted) return extracted;
} }
return DEFAULT_QI_BLOOD_OVERVIEW; return "";
}, [overviewQuery.resolution]); }, [overviewQuery.resolution]);
// Filter out the identification entry from the category cards list, leaving only the 4 categories // Filter out the identification entry from the category cards list, leaving only the 4 categories
@ -70,7 +65,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>
@ -124,11 +127,36 @@ export function QiBloodCardRenderer({
const styles = StyleSheet.create({ const styles = StyleSheet.create({
headerContainer: { headerContainer: {
paddingBottom: verticalScale(8), paddingHorizontal: moderateScale(16),
gap: verticalScale(14), paddingTop: verticalScale(14),
paddingBottom: verticalScale(4),
gap: verticalScale(12),
},
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,
}, },
sectionHeading: { sectionHeading: {
fontSize: moderateScale(16), fontSize: moderateScale(15),
fontWeight: "700", fontWeight: "700",
color: Colors.textPrimary, color: Colors.textPrimary,
marginLeft: moderateScale(4), marginLeft: moderateScale(4),

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,
},
});

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