Compare commits

...

172 Commits

Author SHA1 Message Date
Amit Salunke ededd6f0c1 Merge pull request 'feat/mobile-dynamic-plan-code' (#143) from feat/mobile-dynamic-plan-code into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/143
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-12-04 05:23:59 +00:00
Amit Salunke 053d08eb5d Merge pull request 'fix(m0042): stack tongue/pulse/method sections, show patterns label, preserve template heading case' (#142) from m0042 into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/142
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-12-04 05:23:18 +00:00
ShivaniKhaire 967aec6403 fix(m0042): stack tongue/pulse/method sections, show patterns label, preserve template heading case 2026-12-03 15:02:01 +05:30
Urvish Prajapati 5d76e8ba19 feat(modules): refetch module catalog on focus and lower staleTime to 30s 2026-12-03 12:40:43 +05:30
Urvish Prajapati 6291c325eb feat(modules): prefer API plan_code in toModuleIndexItem for dynamic deep-linking 2026-12-02 15:33:53 +05:30
Amit Salunke e153668f06 Merge pull request 'fix(profile): add country search bar with dial codes and clear phone on country change' (#135) from fix/edit-profile-country-picker into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/135
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-27 04:48:37 +00:00
Amit Salunke 4453a2a96c Merge pull request 'fix(mobile): unify logout confirmation modal and button labels across platforms' (#134) from fix/consistent-logout-confirmation into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/134
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-27 04:47:56 +00:00
Amit Salunke e442a9825a Merge pull request 'fix(mobile): map m0041 (Auriculotherapy) to THERAPEUTICS_EAR instead of LIFETIME_ALL' (#133) from fix/auriculotherapy-plan-code into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/133
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-27 04:47:09 +00:00
Urvish Prajapati b052bb97d7 fix(profile): add country search bar with dial codes and clear phone on country change 2026-11-26 11:35:50 +05:30
Urvish Prajapati 68e8c2a07b fix(mobile): unify logout confirmation modal and button labels across platforms 2026-11-26 11:11:03 +05:30
Urvish Prajapati b2c70e1b2e fix(mobile): map m0041 (Auriculotherapy) to THERAPEUTICS_EAR instead of LIFETIME_ALL 2026-11-25 15:34:57 +05:30
Amit Salunke 49fe5196ef Merge pull request 'fix(point-categories): align yuan source UI with card accordions and standard typography' (#132) from fix-point-categories into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/132
2026-11-19 10:11:00 +00:00
ShivaniKhaire ac89c8a834 fix(point-categories): make point link button compact chip matching ReferenceChipList 2026-11-19 15:38:58 +05:30
ShivaniKhaire 4b0a6b5669 fix(point-categories): sanitize meridian abbreviation codes from card headings 2026-11-19 15:20:55 +05:30
ShivaniKhaire 4885ac72b9 fix(point-categories): align yuan source UI with card accordions and standard typography 2026-11-19 14:49:21 +05:30
Amit Salunke eee01a5211 Merge pull request 'fix(gallery): resolve excess pagination dots and hide inherited point images in point categories (issue #125)' (#130) from fix/issue-125-pagination-dots into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/130
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-19 04:55:47 +00:00
Amit Salunke e24e235d18 Merge pull request 'fix(auth): defer same password check to backend and ensure accurate field error placement (issue #111)' (#129) from fix/issue-111-change-password-validation into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/129
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-19 04:52:15 +00:00
Amit Salunke 550de8025c Merge pull request 'fix(renderers): correct apostrophe placement in Lung's for Three Burners patterns (issue #126)' (#128) from issue-126 into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/128
2026-11-19 04:50:08 +00:00
ShivaniKhaire 8990f90132 fix(gallery): resolve excess pagination dots and hide inherited point images in point categories (issue #125) 2026-11-18 12:49:31 +05:30
ShivaniKhaire effed053b8 revert(gallery): keep ContentMediaGallery identical to other modules 2026-11-17 16:59:50 +05:30
ShivaniKhaire 0f68e31285 fix(gallery): restore point category relational media fallback while preserving exact pagination dots 2026-11-17 16:53:40 +05:30
ShivaniKhaire 8a158258ef fix(gallery): align pagination dots with available images and prioritize direct category media (issue #125) 2026-11-17 16:48:50 +05:30
ShivaniKhaire 7e75204237 fix(auth): defer same password check to backend and ensure accurate field error placement (issue #111) 2026-11-17 15:11:49 +05:30
ShivaniKhaire 4904c31493 fix(renderers): correct apostrophe placement in Lung's for Three Burners patterns (issue #126) 2026-11-17 14:38:45 +05:30
Amit Salunke 3240b91f11 Merge pull request 'fix(validation): add country-specific mobile phone validation and libphonenumber-js' (#127) from fix/country-specific-phone-validation into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/127
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-17 05:03:52 +00:00
Urvish Prajapati b2fe1e635e fix(validation): prioritize length errors over prefix errors in phone validation 2026-11-16 16:30:50 +05:30
Urvish Prajapati 0c60b835a0 fix(validation): add country-specific mobile phone validation and libphonenumber-js
- Integrate libphonenumber-js to validate country mobile numbering plans (e.g., France 06/07, India 6-9, UK 07)
- Add ISO-2 country codes to eliminate dropdown collisions between countries sharing dial codes (+1 for US and Canada)
- Automatically strip leading national trunk zero (0) when converting to standard international E.164 format
- Ensure new dependency is registered in package.json and package-lock.json for npm install
2026-11-16 16:13:36 +05:30
Amit Salunke 02cd589cc4 Merge pull request 'fix(auth): update change password confirm mismatch error message' (#123) from fix/change-password-confirm-visibility-and-error into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/123
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-12 04:37:01 +00:00
Amit Salunke 4c3730a550 Merge pull request 'fix(auth): enforce strict national phone length and prevent country code combining in mobile app' (#122) from fix/standardized-phone-validation into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/122
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-12 04:36:19 +00:00
Amit Salunke b1ce4179ad Merge pull request 'fix(settings): remove duplicate alert popup on change password error (issue #111)' (#119) from issue-111 into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/119
2026-11-12 04:35:24 +00:00
Amit Salunke 7706937b54 Merge pull request 'feat(auth): sort country selection alphabetically in registration and profile (issue #110)' (#118) from issue-110 into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/118
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-12 04:34:56 +00:00
Amit Salunke 83f99a2552 Merge pull request 'fix(renderers): add generic OverviewCard, fix missing info icon and redundant subtitle (issue #93)' (#116) from issue-93 into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/116
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-12 04:34:19 +00:00
Urvish Prajapati 78fbfe29cf fix(auth): update change password confirm mismatch error message 2026-11-11 15:48:23 +05:30
Urvish Prajapati 947ca339e5 fix(auth): enforce strict national phone length and prevent country code combining in mobile app 2026-11-11 15:19:13 +05:30
ShivaniKhaire 77d3847280 fix(settings): remove duplicate alert popup on change password error (issue #111)
- Prevent displaying duplicate error messages when entering an incorrect password
- Rely on inline error display below the input fields instead of showing redundant alert dialogs
2026-11-07 17:22:02 +05:30
ShivaniKhaire 52fc209274 feat(auth): sort country selection alphabetically in registration and profile (issue #110)
- Export SORTED_COUNTRY_CODES sorted by country name in constants/countries.ts
- Use SORTED_COUNTRY_CODES in SignUpForm to sort countries alphabetically in the Select Country modal
- Sort COMMON_COUNTRIES in EditProfileForm alphabetically for consistent UX
2026-11-07 17:18:00 +05:30
ShivaniKhaire 45933ddca6 fix(renderers): add generic OverviewCard, fix missing info icon and redundant subtitle (issue #93)
- Create reusable OverviewCard component with default information-circle icon
- Replace inconsistent SectionCard in SixStagesCollectionRenderer with OverviewCard
- Standardize OverviewCard across collection and detail renderers
- Add icon prop support to AccordionSection and SectionCard with auto-resolution for Overview
- Remove redundant patterns subtitle under FourLevels and FiveElements cards
2026-11-07 16:56:36 +05:30
Amit Salunke 3273d74780 Merge pull request 'fix(android): resolve release build autolinking, hermesc resolution, and package namespace' (#108) from fix/android-release-build-autolinking into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/108
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-06 05:00:11 +00:00
Amit Salunke c67c05428b Merge pull request 'fix(auth): standardize RFC email validation across mobile auth screens' (#112) from fix/email-format-validation into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/112
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-06 04:59:16 +00:00
Amit Salunke a15813b8fd Merge pull request 'fix(auth): clear phone number field when country changes during sign up' (#113) from fix/clear-phone-on-country-change into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/113
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-06 04:58:10 +00:00
Amit Salunke 470edf2f7a Merge pull request 'gynecology-fix' (#114) from gynecology-fix into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/114
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-05 10:26:05 +00:00
ShivaniKhaire 058d96f353 fix(tcm): remove generic content_ref hijack to restore standard pattern detail navigation 2026-11-05 15:39:50 +05:30
Urvish Prajapati 2e964173b4 fix(auth): clear phone number field when country changes during sign up 2026-11-05 15:33:14 +05:30
ShivaniKhaire 82e6bb0314 feat(gynecology): apply green accordion UI tone to disease pattern cards 2026-11-05 15:29:09 +05:30
Urvish Prajapati 829fa5b5cb fix(auth): standardize RFC email validation across mobile auth screens 2026-11-05 15:21:09 +05:30
ShivaniKhaire 39a88d8deb feat(gynecology): add m0042_ct0091-ct0102 disease overviews for other 2026-11-05 14:55:16 +05:30
ShivaniKhaire 138085751e fix(content): generically prioritize primary link navigation in collection screens 2026-11-05 14:50:00 +05:30
ShivaniKhaire b9e2821a26 feat(gynecology): add m0042_ct0071-ct0084 disease overviews 2026-11-05 14:39:03 +05:30
ShivaniKhaire 1eb0095e8a feat(gynecology): enable other category and add disease overviews 2026-11-05 14:13:39 +05:30
ShivaniKhaire d5bc75f0e4 feat(gynecology): enable diseases_after_childbirth and add disease overviews 2026-11-05 13:07:12 +05:30
ShivaniKhaire 2082af2d26 fix(six-stages): enable navigation and add entry template for m0015 2026-11-05 12:12:34 +05:30
ShivaniKhaire 719de15b4a fix(qi-blood): restore collection overview card and category resolution 2026-11-05 11:09:00 +05:30
ShivaniKhaire 026a62b2c2 style(gynecology): change overview and heading tone from purple to green 2026-11-05 09:34:54 +05:30
ShivaniKhaire 6354ae0cc5 feat(gynecology): add GynecologyDiseaseCollectionRenderer with disease overview and pattern accordions 2026-11-05 09:10:48 +05:30
Amit Salunke bf167e3f0a Merge pull request 'feature/nutrition' (#107) from feature/nutrition into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/107
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-04 09:13:10 +00:00
ShivaniKhaire d332e78f94 feat(nutrition): add NutritionCategoryDetailRenderer and hide raw category attribute cards 2026-11-04 14:29:06 +05:30
ShivaniKhaire 8862b93794 feat(nutrition): route entry template to catalog list and register category renderers
- Set entryTemplateCode to m0031_ct0001 in module-index.ts
- Register nutrition_category_collection, card, and detail in registry.ts
2026-11-04 14:29:06 +05:30
Urvish Prajapati f8e82d2fc9 fix(android): resolve release build autolinking, hermesc resolution, and package namespace 2026-11-04 12:55:12 +05:30
Amit Salunke 042c1cff36 Merge pull request 'feat(nutrition): direct navigation to food items, capitalize headings, and remove redundant food name card' (#105) from feature/nutrition into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/105
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-04 04:39:17 +00:00
ShivaniKhaire 93543583d6 feat(nutrition): direct navigation to food items, capitalize headings, and remove redundant food name card 2026-11-03 17:20:42 +05:30
Amit Salunke 4145375926 Merge pull request 'gynec-changes' (#104) from gynec-changes into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/104
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-02 10:54:01 +00:00
ShivaniKhaire b49ae9f047 fix: keep 's and ’s lowercase in humanizeKey 2026-11-02 16:20:24 +05:30
ShivaniKhaire 203fbbc0c9 feat(gynecology): remove view full details, explanation links, and disable clicks on empty catalog items 2026-11-02 16:16:16 +05:30
Amit Salunke 3663323c20 Merge pull request 'gynecology' (#102) from gynecology into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/102
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-02 04:43:39 +00:00
Amit Salunke c793ea27c7 Merge pull request 'ariculratherapy' (#103) from ariculratherapy into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/103
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-11-02 04:43:07 +00:00
ShivaniKhaire b921b2137d Render treatment principle as bulleted list matching clinical manifestations 2026-10-30 17:43:40 +05:30
ShivaniKhaire 68f122cc7e feat(gynecology): link all acupuncture points and explanation references to m0001 point details 2026-10-30 17:32:36 +05:30
ShivaniKhaire 053c93e708 style(gynecology): align pattern accordion with acupoints theme (colors, fonts, chips, lines) 2026-10-30 17:23:02 +05:30
ShivaniKhaire 39ca76f931 fix(gynecology): remove nested card-in-card borders in pattern accordion 2026-10-30 17:15:56 +05:30
ShivaniKhaire 3fc56f344e feat(gynecology): add pattern accordion card renderer matching design sketches 2026-10-30 17:11:16 +05:30
ShivaniKhaire d38407425f fix(renderers): remove duplicate ContentLinkAttributeSections from GenericDetailRenderer 2026-10-30 13:32:55 +05:30
ShivaniKhaire 2925ae4e28 revert(m0041): rely on backend template definitions for attribute labels 2026-10-30 12:46:59 +05:30
ShivaniKhaire a3af361419 fix(m0041): ensure m_p and s_p display as Main Points and Supplementary Points 2026-10-30 12:44:20 +05:30
Amit Salunke 08e954bba0 Merge pull request 'bug(issue-82):fixed country wise mobile number length issue' (#95) from fix/phone-validation-7-to-15-digits into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/95
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-30 05:29:35 +00:00
Urvish Prajapati b6a1e007bf Fixed conflics 2026-10-30 10:58:16 +05:30
Amit Salunke 03f1f2bcf6 Merge pull request 'fix(m0019): respect accordionDefaultExpanded setting in FiveElements sub-patterns (Issue-89)' (#99) from issue-89 into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/99
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-30 05:17:44 +00:00
Amit Salunke 71f5177f28 Merge pull request 'issue(87): make header title color consistent across all modules' (#98) from issue-87 into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/98
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-30 05:10:04 +00:00
Amit Salunke b329de9296 Merge pull request 'issue(28): fix partial search and prevent blank screen in mobile faceted search' (#97) from issue-28 into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/97
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-30 05:09:24 +00:00
Amit Salunke ae903b1c4c Merge pull request 'update(back-button-issue): added a circle style back button similar across all screens' (#96) from issue-61 into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/96
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-30 05:08:27 +00:00
Amit Salunke f5303482aa Merge pull request 'fix(profile-issue-88): auto-update country code on country change and disallow hyphens in phone number' (#94) from fix/profile-phone-country-code into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-mobile-ui/pulls/94
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-30 05:07:28 +00:00
ShivaniKhaire 3e03aeb4e2 fix(m0019): respect accordionDefaultExpanded setting in FiveElements sub-patterns (Issue-89) 2026-10-30 09:46:41 +05:30
ShivaniKhaire 9153dce196 issue(87): make header title color consistent across all modules 2026-10-30 09:33:26 +05:30
ShivaniKhaire 0b8d2c7c48 issue(28): fix partial search and prevent blank screen in mobile faceted search 2026-10-30 08:29:03 +05:30
Urvish Prajapati 045ed5fc49 update(back-button-issue): added a circle style back button similar across all screens 2026-10-29 14:27:51 +05:30
Urvish Prajapati 75b08672d6 fix(profile-issue-88): auto-update country code on country change and disallow hyphens in phone number 2026-10-29 14:06:44 +05:30
Urvish Prajapati c05acc9c33 bug(issue-82):fixed country wise mobile number length issue 2026-10-29 13:11:26 +05:30
ShivaniKhaire b520220e1c fix(ui): hide ContentCountBadge when count is 0 2026-10-29 13:10:41 +05:30
Amit Salunke 4e6b8ec8ee Merge pull request 'fix(m0001_ct0002): ensure Extra Points is displayed at the end after Du Channel' (#92) from Points into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-mobile-ui/pulls/92
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-29 07:02:47 +00:00
Amit Salunke 71d8034a24 Merge pull request 'feat(therapeutics): generic detail and collection UI improvements for therapeutics modules' (#91) from theraputics into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-mobile-ui/pulls/91
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-29 07:02:23 +00:00
Amit Salunke 349946f0c1 Merge pull request 'feat: add in-app environment switcher and update bundle id to com.renown.mobile.acupedia' (#90) from env-switch into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-mobile-ui/pulls/90
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-29 07:00:41 +00:00
ShivaniKhaire a1c9da8ca6 fix(m0001_ct0002): ensure Extra Points is displayed at the end after Du Channel 2026-10-29 12:14:18 +05:30
ShivaniKhaire 3ed151b72e feat(therapeutics): generic detail and collection UI improvements for therapeutics modules 2026-10-29 11:58:35 +05:30
Urvish Prajapati ba23af8076 feat: add in-app environment switcher and update bundle id to com.renown.mobile.acupedia
- Add in-app environment switcher (Prod, QA, .env) on Login and Settings
- Trigger auto-logout and clear query cache on environment change
- Dynamically inject active baseURL into Axios and media resolver
- Update bundle identifier in app.json to com.renown.mobile.acupedia
2026-10-28 16:23:33 +05:30
Amit Salunke f5a442311a Merge pull request 'issue(60): enforce 7-15 digits and 15 digit input limit on phone numbers' (#84) from fix/phone-validation-7-to-15-digits into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-mobile-ui/pulls/84
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-27 04:49:11 +00:00
Urvish Prajapati a2c9d613c6 issue(60): enforce 7-15 digits and 15 digit input limit on phone numbers 2026-10-26 16:26:07 +05:30
Amit Salunke f6ca6297ea Merge pull request 'issue(45): prevent keyboard overlapping confirm password field in signup' (#83) from fix/signup-keyboard-overlap into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-mobile-ui/pulls/83
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-26 08:29:33 +00:00
Amit Salunke d5184c1c37 Merge pull request 'issue(44): added country code option before phone number' (#82) from issue-44-country-code into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-mobile-ui/pulls/82
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-26 08:29:03 +00:00
Amit Salunke 59ddb35bb2 Merge pull request 'fix: added validation for update password' (#81) from change-password-validation into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-mobile-ui/pulls/81
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-26 08:28:27 +00:00
Amit Salunke 130f635017 Merge pull request 'fix(renderers): hide alternative name card on extra ordinary vessels detail' (#80) from fix/remove-eov-alt-name into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-mobile-ui/pulls/80
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-26 08:28:00 +00:00
Urvish Prajapati 5be81fb6a2 issue(45): prevent keyboard overlapping confirm password field in signup 2026-10-26 13:55:28 +05:30
ShivaniKhaire 2f5581800f fix(android): fix MainApplication ReactHost setup and enable release signing 2026-10-26 13:51:19 +05:30
Urvish Prajapati c761853965 issue(44): added country code option before phone number 2026-10-26 13:31:18 +05:30
Urvish Prajapati 08cc9adf1a fix: added validation for update password 2026-10-26 11:54:27 +05:30
ShivaniKhaire bd847d1c3b fix(renderers): hide alternative name card on extra ordinary vessels detail 2026-10-26 11:33:15 +05:30
Amit Salunke 98efd5899d Merge pull request 'patterns' (#79) from patterns into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-mobile-ui/pulls/79
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-26 04:35:19 +00:00
ShivaniKhaire 263650d03d feat(renderers): render reference points vertically as bullet list with chips 2026-10-26 09:53:05 +05:30
ShivaniKhaire c40e4cd254 fix(renderers): prevent duplicate treatment card rendering from ContentLinkAttributeSections 2026-10-26 09:42:58 +05:30
ShivaniKhaire 9ff35bcd70 Merge branch 'origin/main' into patterns and resolve conflicts 2026-10-26 09:24:13 +05:30
Amit Salunke aaa23fedfe Merge pull request 'Points' (#78) from Points into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-mobile-ui/pulls/78
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-26 02:19:51 +00:00
Amit Salunke 31b6476d14 Merge pull request 'issue(61): fixed back button design similarity and screen settings' (#77) from issue-61 into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-mobile-ui/pulls/77
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-26 02:18:56 +00:00
Amit Salunke fc215f5f42 Merge pull request 'issue(59):fixed the password validation rejecting emoji as special character' (#76) from issue-59 into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-mobile-ui/pulls/76
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-26 02:18:17 +00:00
ShivaniKhaire 525fe5b7e3 feat(renderers): render FourLevels treatment_principle as bullet list 2026-10-24 17:00:48 +05:30
ShivaniKhaire 27e62f99db feat(renderers): render structured treatment point references as chips in pattern details 2026-10-24 16:34:32 +05:30
ShivaniKhaire 91ae140c9f fix(twelve-channels): fix card spacing on detail and overview screens 2026-10-24 15:10:35 +05:30
ShivaniKhaire 8e73bcad73 feat(three-burners): render separate Treatment Principle and Treatment cards with updated display order 2026-10-24 14:54:29 +05:30
ShivaniKhaire f267674f78 feat(tcm-patterns): dynamically order detail sections by template presentation contracts 2026-10-24 13:42:55 +05:30
ShivaniKhaire 53c6077419 feat(tcm-patterns): support generic module catalog card rendering for TCM patterns list 2026-10-24 12:57:04 +05:30
ShivaniKhaire effaf75cf3 feat(six-stages): implement six stages collection and detail renderers with dynamic ordering 2026-10-24 12:44:52 +05:30
ShivaniKhaire 2a3c08ef57 fix(content-value): add missing index parameter to entries.map 2026-10-23 15:29:00 +05:30
ShivaniKhaire 00e8c7467e feat(five-elements): make pattern cards collapsible on final detail page 2026-10-23 14:30:06 +05:30
ShivaniKhaire a05c3c71b1 style(ui): add generic divider lines before nested object sections 2026-10-23 14:05:13 +05:30
ShivaniKhaire c1dc542975 remove heart icon 2026-10-23 13:00:22 +05:30
ShivaniKhaire da7e3e0bea style(ui): add generic divider lines before nested object sections 2026-10-23 12:16:28 +05:30
ShivaniKhaire dc1659b44a Render subtitle generically in EOV and module catalog cards 2026-10-23 10:47:20 +05:30
ShivaniKhaire 7289125e91 feat(content): hide favorite heart action generically for points modules 2026-10-23 09:57:56 +05:30
ShivaniKhaire 8b60e0f12f fix(renderers): exclude point_codes and source_point from generic link sections 2026-10-23 09:46:13 +05:30
ShivaniKhaire 958229cb0c feat(meridians): display generic content_label under count in standard index cards 2026-10-23 09:08:11 +05:30
ShivaniKhaire 06f438b0e0 feat(ear-acupuncture): display book icon for catalog index cards 2026-10-22 16:58:15 +05:30
ShivaniKhaire d3e4037051 fix(catalog): remove sub name from module catalog cards 2026-10-22 16:22:18 +05:30
ShivaniKhaire 2fce0e3192 color fix 2026-10-22 16:08:55 +05:30
Amit Salunke e7854ceb93 Merge pull request 'feat(mobile): render direct overview and patterns list in four levels with bullet points for treatment and explanation' (#75) from four-levels-of-patterns into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-mobile-ui/pulls/75
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-22 07:59:29 +00:00
Urvish Prajapati 358bb420a2 issue(61): fixed back button design similarity and screen settings 2026-10-22 13:26:45 +05:30
ShivaniKhaire ccbe12e2ce Merge branch 'main' into four-levels-of-patterns 2026-10-22 12:35:00 +05:30
Urvish Prajapati 0bb85852e2 issue(59):fixed the password validation rejecting emoji as special character 2026-10-22 11:42:06 +05:30
Amit Salunke 8f9caa1c39 Merge pull request 'qi-blood-fluids' (#74) from qi-blood-fluids into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-mobile-ui/pulls/74
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-22 05:58:45 +00:00
Amit Salunke eee9b3b380 Merge pull request 'extra-ordinary-vessel' (#70) from extra-ordinary-vessel into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-mobile-ui/pulls/70
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-22 05:57:44 +00:00
ShivaniKhaire 5f58a8dc30 capitalize title to Visual Reference across application 2026-10-21 16:37:04 +05:30
ShivaniKhaire d4bd2d43aa render clinical manifestations as BulletList in PathogenicFactorsDetailRenderer 2026-10-21 16:26:54 +05:30
ShivaniKhaire bfb3c361dc render clinical manifestations as BulletList in FourLevelsDetailRenderer 2026-10-21 16:16:36 +05:30
ShivaniKhaire 7d17bdb3de render clinical manifestations, connecting channel and treatment in EovDetailRenderer 2026-10-21 16:01:17 +05:30
ShivaniKhaire ff9be31f3b fix twelve channels clinical manifestation 2026-10-21 14:45:05 +05:30
ShivaniKhaire 98d0e49597 three burners clinical menifestation fix 2026-10-21 14:12:35 +05:30
ShivaniKhaire e21b8780dd fix six-stages clinical menifestation. 2026-10-21 12:48:38 +05:30
ShivaniKhaire 2a2c9ebc80 feat(m0013): render clinical manifestations using BulletList in QiBloodDetailRenderer 2026-10-20 15:26:08 +05:30
ShivaniKhaire 5d19418814 feat(mobile): render direct overview and patterns list in four levels with bullet points for treatment and explanation 2026-10-20 13:17:25 +05:30
ShivaniKhaire 7ead8b1cde feat(mobile): render clinical manifestation as bullet points 2026-10-20 12:35:28 +05:30
ShivaniKhaire 9ddc958a6a feat(mobile): add ExtraOrdinaryVesselsDetailRenderer with accordion section cards matching point leaf node UI 2026-10-20 12:23:32 +05:30
ShivaniKhaire f47f9cc710 feat(mobile): display subtitle in module catalog and detail renderers 2026-10-20 12:14:52 +05:30
Amit Salunke abcb9823c2 Merge pull request 'remove open content fallback description from catalog card' (#68) from fix-remove-open-content into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-mobile-ui/pulls/68
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-20 04:45:07 +00:00
Amit Salunke ec115ba9ce Merge pull request 'acupedia-acupoint' (#69) from acupedia-acupoint into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-mobile-ui/pulls/69
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-20 04:44:37 +00:00
Amit Salunke 3d7a285db3 Merge pull request 'fix repeated click duplicate pages (#43)' (#67) from issue-43 into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-mobile-ui/pulls/67
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-20 04:36:02 +00:00
ShivaniKhaire ce7d94ac10 feat(points): prioritize alt names in AcuPointCardRenderer and support ct0025 in MeridianPointsDetailRenderer 2026-10-19 17:00:57 +05:30
ShivaniKhaire 24838a68ee feat(m0001): render channel points as index cards in meridian points detail 2026-10-19 16:07:42 +05:30
ShivaniKhaire 348adf88ba remove open content fallback description from catalog card 2026-10-17 15:40:31 +05:30
ShivaniKhaire 4ef5c1cab9 fix repeated click duplicate pages (#43) 2026-10-15 14:48:12 +05:30
Amit Salunke be19a39127 Merge pull request 'Fix extra points UI' (#66) from fix/extra-point-card-ui into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-mobile-ui/pulls/66
2026-10-14 09:14:32 +00:00
Amit Salunke cd999e5cdb Merge pull request 'fix meridian detail renderer generic' (#65) from fix/generic-meridian-detail-renderer into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-mobile-ui/pulls/65
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-14 09:14:20 +00:00
ShivaniKhaire aee5aacec0 fix(ui): use StandardIndexCard in AcuPointCardRenderer for colorful badges and chevrons 2026-10-14 14:27:22 +05:30
ShivaniKhaire 8efd3cce49 feat(renderers): make meridian detail renderer generic and data-driven 2026-10-14 11:27:39 +05:30
Amit Salunke b93b8f672f Merge pull request 'fix(build): resolve Android release compilation and web bundling issues' (#56) from build-issues into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-mobile-ui/pulls/56
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-09 05:02:25 +00:00
Amit Salunke fef1751c55 Merge pull request 'Issue #41: fix(profile) validate and restrict phone number to 10 digits' (#49) from fix/issue-41-profile-phone-validation into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-mobile-ui/pulls/49
2026-10-06 12:16:11 +00:00
Amit Salunke 08ac950b7d Merge pull request 'Issue#37 : fix(m0018) add proper spacing and margins between Zang-Fu channel cards' (#51) from fix/issue-37-zang-fu-card-spacing into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-mobile-ui/pulls/51
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-06 12:15:37 +00:00
Amit Salunke ed0d9f9f17 Merge pull request 'Iuuse (#36): fix(m0013) increase Overview box size and typography in Qi-Blood module' (#50) from fix/issue-36-qi-blood-overview-box-size into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-mobile-ui/pulls/50
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-06 12:13:40 +00:00
Amit Salunke 0d3fe65a6d Merge pull request 'Issue (#40): handle mobile hardware and gesture back button in category details navigation (#40)' (#52) from fix/issue-40-back-button-navigation into main
Reviewed-on: https://10.10.0.4/AcuPedia/acupedia-mobile-ui/pulls/52
Reviewed-by: Amit Salunke <amit@noreply.localhost>
2026-10-06 12:13:18 +00:00
Amit Salunke 3572ed1c04 merged with main 2026-10-06 17:07:04 +05:30
Amit Salunke 2130240b9e Merge branch 'main' into fix/issue-40-back-button-navigation 2026-10-06 17:03:07 +05:30
Urvish Prajapati 8c6fc8624a fix(build): resolve Android release compilation and web bundling issues
- Configure metro.config.js with CommonJS condition priority to prevent ESM import.meta syntax errors on web
- Switch web.output to single in app.json for faster SPA client-side rendering
- Fix MainApplication.kt implementing reactNativeHost and reactHost via ReactNativeHostWrapper
- Remove obsolete hermesCommand resolution in android/app/build.gradle
2026-10-06 16:51:00 +05:30
ShivaniKhaire 2d05158fc2 fix(profile): allow variable length international phone numbers (Issue #41) 2026-10-03 10:54:03 +05:30
ShivaniKhaire 082ad5cb8b fix(profile): validate and restrict phone number to 10 digits (Issue #41) 2026-10-01 12:32:13 +05:30
ShivaniKhaire 09864ab02d fix(m0013): increase Overview box size and typography in Qi-Blood module (#36) 2026-09-30 16:58:21 +05:30
ShivaniKhaire 06f93cdad6 fix(m0018): add proper spacing and margins between Zang-Fu channel cards (#37) 2026-09-30 16:46:23 +05:30
ShivaniKhaire 3b24da2cc4 fix: handle mobile hardware and gesture back button in category details navigation (#40) 2026-09-30 16:34:21 +05:30
155 changed files with 8568 additions and 1782 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://api.acupedia.in/api #EXPO_PUBLIC_API_URL=https://qa-api.acupedia.in/api
EXPO_PUBLIC_STOREFRONT_URL=https://acupedia.in/store # EXPO_PUBLIC_STOREFRONT_URL=https://qa-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 Normal file
View File

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

Binary file not shown.

193
android/app/build.gradle Normal file
View File

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

BIN
android/app/debug.keystore Normal file

Binary file not shown.

14
android/app/proguard-rules.pro vendored Normal file
View File

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

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

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

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

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

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

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

View File

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

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

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

@ -0,0 +1,6 @@
<?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.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

View File

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

View File

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

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

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

24
android/build.gradle Normal file
View File

@ -0,0 +1,24 @@
// 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"

66
android/gradle.properties Normal file
View File

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

@ -0,0 +1,7 @@
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 Executable file
View File

@ -0,0 +1,248 @@
#!/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 Normal file
View File

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

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

39
android/settings.gradle Normal file
View File

@ -0,0 +1,39 @@
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.renownent.mobile.acupedia", "bundleIdentifier": "com.renown.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.renownent.mobile.acupedia", "package": "com.renown.mobile.acupedia",
"allowBackup": false "allowBackup": false
}, },
"web": { "web": {
"output": "static", "output": "single",
"favicon": "./assets/images/favicon.png" "favicon": "./assets/images/favicon.png"
}, },
"plugins": [ "plugins": [

11
eas.json Normal file
View File

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

View File

@ -371,7 +371,7 @@
); );
OTHER_SWIFT_FLAGS = "$(inherited) -D EXPO_CONFIGURATION_DEBUG"; 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.

After

Width:  |  Height:  |  Size: 734 KiB

View File

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

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>myapp</string> <string>acupedia</string>
<string>com.renownent.acupedia</string> <string>com.renownent.mobile.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>

12
metro.config.js Normal file
View File

@ -0,0 +1,12 @@
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": "~1.0.10", "expo-build-properties": "~57.0.22",
"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,6 +27,7 @@
"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,7 +2,48 @@ 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";
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"}}); import { getActiveApiUrl } from "@/store/environment.store";
apiClient.interceptors.request.use((config)=>{const token=getApiAccessToken(); if(token){const headers=AxiosHeaders.from(config.headers); headers.set("Authorization",`Bearer ${token}`); config.headers=headers;} return config;},(error)=>Promise.reject(normalizeApiError(error)));
apiClient.interceptors.response.use((response)=>response,(error:unknown)=>{const apiError=normalizeApiError(error); const requestHeaders=axios.isAxiosError(error)?AxiosHeaders.from(error.config?.headers):null; const hadBearerToken=Boolean(requestHeaders?.get("Authorization")?.toString().startsWith("Bearer ")); if(hadBearerToken && apiError.status===401) notifyUnauthorized(); return Promise.reject(apiError);}); const apiClient = axios.create({
baseURL: getActiveApiUrl(),
timeout: 30000,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"Bypass-Tunnel-Reminder": "true",
},
});
apiClient.interceptors.request.use(
(config) => {
const activeBaseUrl = getActiveApiUrl();
if (activeBaseUrl) {
config.baseURL = activeBaseUrl;
}
const token = getApiAccessToken();
if (token) {
const headers = AxiosHeaders.from(config.headers);
headers.set("Authorization", `Bearer ${token}`);
config.headers = headers;
}
return config;
},
(error) => Promise.reject(normalizeApiError(error))
);
apiClient.interceptors.response.use(
(response) => response,
(error: unknown) => {
const apiError = normalizeApiError(error);
const requestHeaders = axios.isAxiosError(error)
? AxiosHeaders.from(error.config?.headers)
: null;
const hadBearerToken = Boolean(
requestHeaders?.get("Authorization")?.toString().startsWith("Bearer ")
);
if (hadBearerToken && apiError.status === 401) notifyUnauthorized();
return Promise.reject(apiError);
}
);
export default apiClient; export default apiClient;

View File

@ -1,9 +1,11 @@
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 { Alert, Platform } from "react-native"; import { 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();
@ -13,40 +15,24 @@ 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");
}; };
if (Platform.OS === "web") { const handleAuthAction = () => {
const confirmed = typeof window !== "undefined" ? window.confirm("Are you sure you want to logout?") : true; if (isAuthenticated) {
if (confirmed) { setLogoutModalVisible(true);
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,
@ -142,5 +128,11 @@ export default function TabsLayout() {
}} }}
/> />
</Tabs> </Tabs>
<LogoutConfirmModal
visible={logoutModalVisible}
onCancel={() => setLogoutModalVisible(false)}
onConfirm={doLogout}
/>
</>
); );
} }

View File

@ -56,10 +56,11 @@ 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, refreshAccess]), }, [accessToken, modulesQuery.refetch, refreshAccess]),
); );
const items = useMemo( const items = useMemo(

View File

@ -1,5 +1,34 @@
import { Stack } from "expo-router"; import { router, 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,6 +18,7 @@ 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() {
@ -36,12 +37,9 @@ export default function ForgotPasswordScreen() {
const handleRequestOtp = async () => { const handleRequestOtp = async () => {
setEmailError(""); setEmailError("");
const cleanEmail = email.trim().toLowerCase(); const cleanEmail = email.trim().toLowerCase();
if (!cleanEmail) { const emailErr = validateEmail(cleanEmail);
setEmailError("Email is required"); if (emailErr) {
return; setEmailError(emailErr);
}
if (!/\S+@\S+\.\S+/.test(cleanEmail)) {
setEmailError("Please enter a valid email address");
return; return;
} }
@ -89,7 +87,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 (!/[^A-Za-z0-9\s]/.test(newPassword)) { } else if (!/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?~`]/.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 (!/[^A-Za-z0-9\s]/.test(newPassword)) { } else if (!/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?~`]/.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("Passwords do not match"); setConfirmError("Confirm password do not match.");
hasError = true; hasError = true;
} }
@ -89,11 +89,23 @@ 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);
if (Platform.OS === "web") { } else if (
window.alert(errMsg); typeof errMsg === "string" &&
errMsg.toLowerCase().includes("confirm")
) {
setConfirmError(errMsg);
} else { } else {
Alert.alert("Error", errMsg); setCurrentError(errMsg);
} }
} finally { } finally {
setIsLoading(false); setIsLoading(false);
@ -119,7 +131,10 @@ export default function ChangePasswordScreen() {
<FieldLabel label="Current Password" required /> <FieldLabel label="Current Password" required />
<PasswordInput <PasswordInput
value={currentPassword} value={currentPassword}
onChangeText={setCurrentPassword} onChangeText={(text) => {
setCurrentPassword(text);
if (currentError) setCurrentError("");
}}
placeholder="Enter current password" placeholder="Enter current password"
error={currentError} error={currentError}
/> />
@ -129,7 +144,10 @@ export default function ChangePasswordScreen() {
<FieldLabel label="New Password" required /> <FieldLabel label="New Password" required />
<PasswordInput <PasswordInput
value={newPassword} value={newPassword}
onChangeText={setNewPassword} onChangeText={(text) => {
setNewPassword(text);
if (newError) setNewError("");
}}
placeholder="Min. 8 characters with numbers & symbols" placeholder="Min. 8 characters with numbers & symbols"
error={newError} error={newError}
/> />
@ -139,7 +157,10 @@ export default function ChangePasswordScreen() {
<FieldLabel label="Confirm New Password" required /> <FieldLabel label="Confirm New Password" required />
<PasswordInput <PasswordInput
value={confirmPassword} value={confirmPassword}
onChangeText={setConfirmPassword} onChangeText={(text) => {
setConfirmPassword(text);
if (confirmError) setConfirmError("");
}}
placeholder="Re-enter new password" placeholder="Re-enter new password"
error={confirmError} error={confirmError}
/> />

View File

@ -4,6 +4,7 @@ import {
BackHandler, BackHandler,
Linking, Linking,
Platform, Platform,
Pressable,
ScrollView, ScrollView,
StyleSheet, StyleSheet,
Text, Text,
@ -13,11 +14,12 @@ 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, verticalScale } from "react-native-size-matters"; import { moderateScale, scale, 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 {
@ -25,6 +27,9 @@ 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;
@ -166,15 +171,22 @@ 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}>
<TouchableOpacity <Pressable
onPress={handleBack} onPress={handleBack}
style={styles.backButton} style={({ pressed }) => [
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 name="chevron-back" size={24} color={Colors.textPrimary} /> <Ionicons
</TouchableOpacity> name="chevron-back"
size={moderateScale(24)}
color={Colors.textPrimary}
/>
</Pressable>
<Text style={styles.headerTitle} numberOfLines={1}> <Text style={styles.headerTitle} numberOfLines={1}>
{title} {title}
</Text> </Text>
@ -237,10 +249,15 @@ const styles = StyleSheet.create({
backgroundColor: "#FFFFFF", backgroundColor: "#FFFFFF",
}, },
backButton: { backButton: {
width: moderateScale(36), width: scale(38),
height: moderateScale(36), height: scale(38),
alignItems: "center", borderRadius: scale(19),
justifyContent: "center", justifyContent: "center",
alignItems: "center",
backgroundColor: "#F1F5F9",
},
backButtonPressed: {
backgroundColor: "#E2E8F0",
}, },
headerTitle: { headerTitle: {
flex: 1, flex: 1,
@ -250,7 +267,7 @@ const styles = StyleSheet.create({
textAlign: "center", textAlign: "center",
marginHorizontal: moderateScale(8), marginHorizontal: moderateScale(8),
}, },
placeholder: { width: moderateScale(36) }, placeholder: { width: scale(38), height: scale(38) },
scrollContent: { scrollContent: {
flexGrow: 1, flexGrow: 1,
justifyContent: "center", justifyContent: "center",

View File

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

View File

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

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

408
src/constants/countries.ts Normal file
View File

@ -0,0 +1,408 @@
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,6 +17,7 @@ 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";
@ -41,7 +42,8 @@ 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, 10)); setPhone(digits.slice(0, 15));
if (phoneError) setPhoneError("");
}; };
const handleLogin = async () => { const handleLogin = async () => {
@ -51,19 +53,17 @@ export default function LoginForm({
setPasswordError(""); setPasswordError("");
if (activeTab === "email") { if (activeTab === "email") {
if (!email.trim()) { const emailErr = validateEmail(email);
setEmailError("Email is required"); if (emailErr) {
hasError = true; setEmailError(emailErr);
} 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 < 10) { } else if (phone.length < 7 || phone.length > 15) {
setPhoneError("Phone number must be 10 digits"); setPhoneError("Phone number must be between 7 and 15 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={10} maxLength={15}
leftIcon="call-outline" leftIcon="call-outline"
error={phoneError} error={phoneError}
/> />

View File

@ -1,19 +1,33 @@
import React from "react"; import React, { useState } from "react";
import { Pressable, StyleSheet, Text, View } from "react-native"; import { Pressable, StyleSheet, Text, TouchableOpacity, 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"
@ -27,13 +41,34 @@ 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>
<Text style={styles.subtitle}>
Login to continue
</Text>
</View> </View>
{ENABLE_ENV_SWITCHER && (
<EnvironmentSelectorModal
visible={modalVisible}
onClose={() => setModalVisible(false)}
/>
)}
</View> </View>
); );
} }
@ -44,11 +79,41 @@ 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,12 +1,37 @@
import React, { useState } from "react"; import React, { useState, useMemo } from "react";
import { Alert, StyleSheet, View } from "react-native"; import {
KeyboardAvoidingView,
Modal,
Platform,
Pressable,
ScrollView,
StyleSheet,
Text,
TextInput,
View,
} from "react-native";
import { useRouter } from "expo-router"; import { useRouter } from "expo-router";
import { verticalScale } from "react-native-size-matters"; import { Ionicons } from "@expo/vector-icons";
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";
@ -16,9 +41,13 @@ 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("");
@ -26,9 +55,62 @@ 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, 10)); setPhone(digits.slice(0, selectedCountry.maxLength));
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 () => {
@ -44,18 +126,23 @@ export default function SignUpForm() {
hasError = true; hasError = true;
} }
if (!email.trim()) { const emailErr = validateEmail(email);
setEmailError("Email is required"); if (emailErr) {
hasError = true; setEmailError(emailErr);
} else if (!/\S+@\S+\.\S+/.test(email)) {
setEmailError("Please enter a valid email address");
hasError = true; hasError = true;
} }
if (phone.trim() && phone.length < 10) { if (phone.trim()) {
setPhoneError("Phone number must be 10 digits"); const err = validatePhoneNumber(
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");
@ -72,7 +159,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 (!/[^A-Za-z0-9\s]/.test(password)) { } else if (!/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?~`]/.test(password)) {
setPasswordError("Password must contain at least one special character (!@#$)"); setPasswordError("Password must contain at least one special character (!@#$)");
hasError = true; hasError = true;
} }
@ -87,20 +174,28 @@ 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: phone.trim() ? phone.trim() : undefined, phone_number: formattedPhone,
country: selectedCountry.country,
}); });
const { user } = response; const { user } = response;
setRegisteredUser({ setRegisteredUser({
id: user.id, id: user.id,
name: user.display_name, name: user.display_name ?? fullName.trim(),
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
@ -114,6 +209,8 @@ 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);
} }
}; };
@ -141,18 +238,49 @@ export default function SignUpForm() {
error={emailError} error={emailError}
/> />
<BaseTextInput {/* Phone Number Field with Country Dial Code */}
<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="Phone Number (Optional)" placeholder={selectedCountry.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={10} maxLength={selectedCountry.maxLength}
leftIcon="call-outline" style={styles.phoneInput}
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}
@ -171,9 +299,128 @@ 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>
); );
} }
@ -185,4 +432,154 @@ 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,10 +1,15 @@
import React, { type ReactNode } from "react"; import React, { type ReactNode, useCallback } from "react";
import { Platform, Pressable, StyleSheet, Text, View } from "react-native"; import { BackHandler, Platform, Pressable, StyleSheet, Text, View } from "react-native";
import { Ionicons } from "@expo/vector-icons"; import { Ionicons } from "@expo/vector-icons";
import { router } from "expo-router"; import { router, useFocusEffect } from "expo-router";
import { moderateScale } from "react-native-size-matters"; import { moderateScale, scale } 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;
@ -14,6 +19,8 @@ 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({
@ -24,7 +31,32 @@ 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();
@ -41,7 +73,7 @@ export function ContentPageHeader({
const titleContent = ( const titleContent = (
<View style={styles.titleContent}> <View style={styles.titleContent}>
<Text numberOfLines={1} style={styles.title}> <Text numberOfLines={1} style={[styles.title, { color: resolvedTitleColor }]}>
{title} {title}
</Text> </Text>
{subtitle ? ( {subtitle ? (
@ -58,16 +90,16 @@ export function ContentPageHeader({
<Pressable <Pressable
accessibilityRole="button" accessibilityRole="button"
accessibilityLabel="Go back" accessibilityLabel="Go back"
hitSlop={10} hitSlop={{ top: 12, bottom: 12, left: 12, right: 12 }}
onPress={handleBack} onPress={handleBack}
style={({ pressed }) => [ style={({ pressed }) => [
styles.iconButton, styles.backButton,
pressed && styles.pressed, pressed && styles.backButtonPressed,
]} ]}
> >
<Ionicons <Ionicons
name="chevron-back" name="chevron-back"
size={24} size={moderateScale(24)}
color={Colors.textPrimary} color={Colors.textPrimary}
/> />
</Pressable> </Pressable>
@ -121,12 +153,16 @@ const styles = StyleSheet.create({
alignItems: "center", alignItems: "center",
justifyContent: "flex-end", justifyContent: "flex-end",
}, },
iconButton: { backButton: {
width: 40, width: scale(38),
height: 40, height: scale(38),
borderRadius: 20, borderRadius: scale(19),
alignItems: "center",
justifyContent: "center", justifyContent: "center",
alignItems: "center",
backgroundColor: "#F1F5F9",
},
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)} /> <ObjectSections value={asRecord(data.luo_connecting_vessel)} withTopDivider />
</SectionCard> </SectionCard>
); );

View File

@ -0,0 +1,69 @@
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: 10 * 60 * 1000, staleTime: 30 * 1000,
}); });
} }

View File

@ -1,10 +1,23 @@
import { useMemo } from "react"; import { useMemo } from "react";
import { buildModuleTemplateReference } from "@/features/modules/module-index"; import {
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 function useModuleDisplayName(moduleCode: string) { export interface ModuleDisplayInfo {
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(() => {
@ -13,6 +26,8 @@ export function useModuleDisplayName(moduleCode: string) {
return { return {
name: "Content", name: "Content",
homeRoute: "/modules", homeRoute: "/modules",
category: null,
isPointsModule: false,
}; };
} }
@ -24,14 +39,20 @@ export function useModuleDisplayName(moduleCode: string) {
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,6 +141,21 @@ 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>) => {
@ -169,6 +184,12 @@ 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
@ -192,12 +213,16 @@ export function ContentMediaGallery({ media, title = "Visual reference" }: Conte
{items.length > 1 ? ( {items.length > 1 ? (
<View style={styles.dots} accessibilityElementsHidden> <View style={styles.dots} accessibilityElementsHidden>
{items.map((item, index) => ( {visibleDots.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}
> >
@ -254,7 +279,12 @@ 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: { flexDirection: "row", flexWrap: "wrap", justifyContent: "center", gap: 7 }, dots: {
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,5 +1,6 @@
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.
@ -18,7 +19,7 @@ export function resolveMediaUri(
return directUrl; return directUrl;
} }
const mediaBaseUrl = (process.env.EXPO_PUBLIC_MEDIA_BASE_URL ?? "") const mediaBaseUrl = (getActiveMediaBaseUrl() || (process.env.EXPO_PUBLIC_MEDIA_BASE_URL ?? ""))
.trim() .trim()
.replace(/\/+$/, ""); .replace(/\/+$/, "");

View File

@ -1,22 +1,53 @@
import React from "react"; import React, { useMemo } 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 { humanizeKey } from "./helpers/value"; import { buildDefinitionLabelMap, humanizeKey, resolveAttributeLabel } 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(["code"]); const RESERVED_KEYS = new Set([
"code",
"id",
"slug",
"sort_order",
"link",
"food_name",
"foodname",
"content_count",
"content_label",
"food_items",
]);
/** /**
* Renderer-independent detail fallback. * Generic detail renderer for modules and catalog items.
* *
* `data` has already been filtered/ordered through the presentation contract by * Each attribute is rendered in its own separate SectionCard.
* ContentDetailScreen, so object insertion order is the intended display order. * For therapeutics modules, the redundant Hero name card is hidden.
*/ */
export function GenericDetailRenderer({ content, data }: DetailRendererProps) { export function GenericDetailRenderer({
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={{
@ -27,15 +58,25 @@ export function GenericDetailRenderer({ content, data }: DetailRendererProps) {
}} }}
showsVerticalScrollIndicator={false} showsVerticalScrollIndicator={false}
> >
<Hero title={content.title || "Untitled content"} subtitle={content.summary ?? undefined} /> <Hero
title={heroTitle}
subtitle={content.summary ?? undefined}
/>
<ImageGallery images={[]} /> <ImageGallery images={[]} />
{Object.entries(data) {Object.entries(data)
.filter(([key]) => !RESERVED_KEYS.has(key)) .filter(
.map(([key, value]) => ( ([key]) =>
<SectionCard key={key} title={humanizeKey(key)}> !RESERVED_KEYS.has(key.toLowerCase()) &&
!(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,6 +33,9 @@ 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
@ -40,6 +43,8 @@ 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,6 +6,7 @@ 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,
@ -24,24 +25,15 @@ export function EightPrinciplesCollectionRenderer(
const header = ( const header = (
<View style={styles.overviewContainer}> <View style={styles.overviewContainer}>
<View style={styles.overviewCard}> <OverviewCard
<View style={styles.overviewHeader}> style={styles.overviewCard}
<Ionicons name="information-circle" size={20} color={Colors.primary} /> paragraphs={[
<Text style={styles.overviewTitle}>Overview</Text> "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.",
</View> "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 style={styles.overviewText}> "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.",
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. "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> ]}
<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>
); );
@ -111,35 +103,8 @@ 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,9 +14,16 @@ 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,6 +7,7 @@ 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,
@ -15,21 +16,14 @@ import type {
export function FiveElementsCollectionRenderer(props: CollectionRendererProps) { export function FiveElementsCollectionRenderer(props: CollectionRendererProps) {
const header = ( const header = (
<View style={styles.overviewContainer}> <View style={styles.overviewContainer}>
<View style={styles.overviewCard}> <OverviewCard
<View style={styles.overviewHeader}> style={styles.overviewCard}
<Ionicons name="information-circle" size={20} color={Colors.primary} /> paragraphs={[
<Text style={styles.overviewTitle}>Overview</Text> "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.",
</View> "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 style={styles.overviewText}> "The sequences below detail the Generating, Overacting, and Insulting relationships and their specific clinical presentations.",
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>
); );
@ -51,11 +45,10 @@ 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 label = const subtitle =
asString(attributes.content_label) || asString(attributes.sub_title) ||
asString(attributes.description) || asString(attributes.description) ||
item.summary || (item.summary && item.summary !== "Open sequence" ? item.summary : null);
"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;
@ -72,9 +65,11 @@ export function FiveElementsCardRenderer({
<View style={styles.textContainer}> <View style={styles.textContainer}>
<Text style={styles.title}>{title}</Text> <Text style={styles.title}>{title}</Text>
{subtitle ? (
<Text style={styles.description} numberOfLines={1}> <Text style={styles.description} numberOfLines={1}>
{label} {subtitle}
</Text> </Text>
) : null}
</View> </View>
<ContentCountBadge <ContentCountBadge
@ -91,35 +86,8 @@ 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,6 +7,7 @@ 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,
@ -15,30 +16,17 @@ import type {
export function FourLevelsCollectionRenderer(props: CollectionRendererProps) { export function FourLevelsCollectionRenderer(props: CollectionRendererProps) {
const header = ( const header = (
<View style={styles.overviewContainer}> <View style={styles.overviewContainer}>
<View style={styles.overviewCard}> <OverviewCard
<View style={styles.overviewHeader}> style={styles.overviewCard}
<Ionicons name="information-circle" size={20} color={Colors.primary} /> paragraphs={[
<Text style={styles.overviewTitle}>Overview</Text> "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.",
</View> "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 style={styles.overviewText}> "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.",
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 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> "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 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.",
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>
); );
@ -60,11 +48,10 @@ 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 label = const subtitle =
asString(attributes.content_label) || asString(attributes.sub_title) ||
asString(attributes.description) || asString(attributes.description) ||
item.summary || (item.summary && item.summary !== "Open content" ? item.summary : null);
"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;
@ -81,9 +68,11 @@ export function FourLevelsCardRenderer({
<View style={styles.textContainer}> <View style={styles.textContainer}>
<Text style={styles.title}>{title}</Text> <Text style={styles.title}>{title}</Text>
{subtitle ? (
<Text style={styles.description} numberOfLines={1}> <Text style={styles.description} numberOfLines={1}>
{label} {subtitle}
</Text> </Text>
) : null}
</View> </View>
<ContentCountBadge <ContentCountBadge
@ -100,35 +89,8 @@ 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

@ -0,0 +1,578 @@
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,12 +1,45 @@
import React from "react"; import React, { useMemo } 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 { CollectionItemRendererProps, CollectionRendererProps } from "../../types/renderer.types"; import type {
CollectionItemRendererProps,
CollectionRendererProps,
SearchResultItem,
} from "../../types/renderer.types";
function sortWithExtraPointsAfterDu(items: SearchResultItem[]): SearchResultItem[] {
const isExtra = (item: SearchResultItem) => {
const name = (asString(item.attributes.name) || item.title || "").toLowerCase();
const code = (asString(item.attributes.code) || item.slug || "").toLowerCase();
return name.includes("extra") || code.includes("extra");
};
const extraItems = items.filter(isExtra);
const regularItems = items.filter((item) => !isExtra(item));
regularItems.sort((a, b) => {
const aOrder =
typeof a.attributes.sort_order === "number"
? a.attributes.sort_order
: 999;
const bOrder =
typeof b.attributes.sort_order === "number"
? b.attributes.sort_order
: 999;
return aOrder - bOrder;
});
return [...regularItems, ...extraItems];
}
export function MeridianIndexCollectionRenderer(props: CollectionRendererProps) { export function MeridianIndexCollectionRenderer(props: CollectionRendererProps) {
return <CollectionScaffold {...props} />; const sortedItems = useMemo(
() => sortWithExtraPointsAfterDu(props.items),
[props.items],
);
return <CollectionScaffold {...props} items={sortedItems} />;
} }
export function MeridianCollectionRenderer(props: CollectionRendererProps) { export function MeridianCollectionRenderer(props: CollectionRendererProps) {
return <CollectionScaffold {...props} />; return <CollectionScaffold {...props} />;
@ -17,6 +50,7 @@ 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,55 +1,644 @@
import React from "react"; import React, { useMemo, useState } from "react";
import { Pressable, StyleSheet, Text, View } from "react-native"; import {
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 { asNumber, asString } from "../helpers/value"; import {
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 title = asString(attributes.name) || item.title; const rawTitle =
const label = asString(attributes.content_label) || item.summary || "Open content"; asString(attributes.food_name) ||
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="button" accessibilityRole={isClickable ? "button" : undefined}
onPress={onPress} disabled={!isClickable}
style={({ pressed }) => [styles.row, pressed && styles.pressed]} onPress={isClickable ? onPress : undefined}
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}>{title}</Text> <Text style={styles.title}>{cleanTitle}</Text>
<Text style={styles.description} numberOfLines={1}> {label ? (
<Text numberOfLines={2} style={styles.subtitle}>
{label} {label}
</Text> </Text>
) : null}
</View> </View>
<ContentCountBadge <ContentCountBadge
count={asNumber(attributes.content_count)} count={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),
@ -77,10 +666,12 @@ const styles = StyleSheet.create({
fontSize: moderateScale(15), fontSize: moderateScale(15),
fontWeight: "600", fontWeight: "600",
color: Colors.textPrimary, color: Colors.textPrimary,
marginBottom: verticalScale(2),
}, },
description: { subtitle: {
fontSize: moderateScale(12), fontSize: moderateScale(12),
color: Colors.textSecondary, color: Colors.textSecondary,
marginTop: verticalScale(2),
lineHeight: moderateScale(16),
}, },
}); });

View File

@ -6,6 +6,7 @@ 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,
@ -16,24 +17,15 @@ export function PathogenicFactorsCollectionRenderer(
) { ) {
const header = ( const header = (
<View style={styles.overviewContainer}> <View style={styles.overviewContainer}>
<View style={styles.overviewCard}> <OverviewCard
<View style={styles.overviewHeader}> style={styles.overviewCard}
<Ionicons name="information-circle" size={20} color={Colors.primary} /> paragraphs={[
<Text style={styles.overviewTitle}>Overview</Text> "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.",
</View> "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 style={styles.overviewText}> "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).",
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. "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> ]}
<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>
); );
@ -105,35 +97,8 @@ 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,13 +1,44 @@
import React from "react"; import React, { useMemo } from "react";
import { Pressable, Text, View } from "react-native"; import { asString } from "../helpers/value";
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 { CollectionItemRendererProps, CollectionRendererProps } from "../../types/renderer.types"; import type {
CollectionItemRendererProps,
CollectionRendererProps,
SearchResultItem,
} from "../../types/renderer.types";
function sortWithExtraPointsAfterDu(items: SearchResultItem[]): SearchResultItem[] {
const isExtra = (item: SearchResultItem) => {
const name = (asString(item.attributes.name) || item.title || "").toLowerCase();
const code = (asString(item.attributes.code) || item.slug || "").toLowerCase();
return name.includes("extra") || code.includes("extra");
};
const extraItems = items.filter(isExtra);
const regularItems = items.filter((item) => !isExtra(item));
regularItems.sort((a, b) => {
const aOrder =
typeof a.attributes.sort_order === "number"
? a.attributes.sort_order
: 999;
const bOrder =
typeof b.attributes.sort_order === "number"
? b.attributes.sort_order
: 999;
return aOrder - bOrder;
});
return [...regularItems, ...extraItems];
}
export function AcuPointIndexCollectionRenderer(props: CollectionRendererProps) { export function AcuPointIndexCollectionRenderer(props: CollectionRendererProps) {
return <CollectionScaffold {...props} />; const sortedItems = useMemo(
() => sortWithExtraPointsAfterDu(props.items),
[props.items],
);
return <CollectionScaffold {...props} items={sortedItems} />;
} }
export function AcuPointCollectionRenderer(props: CollectionRendererProps) { export function AcuPointCollectionRenderer(props: CollectionRendererProps) {
return <CollectionScaffold {...props} />; return <CollectionScaffold {...props} />;
@ -25,15 +56,17 @@ 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 (
<Pressable onPress={onPress}> <StandardIndexCard
<View style={{ padding: 14, gap: 7 }}> title={asString(a.point_name) || asString(a.name) || item.title}
<View style={{ flexDirection: "row", gap: 10 }}> subtitle={subtitle || null}
<Text style={{ flex: 1, fontSize: 17, fontWeight: "600" }}>{asString(a.point_name) || asString(a.name) || item.title}</Text> onPress={onPress}
</View> />
<Text>{asString(a.channel)}</Text>
<ChipList items={asStringArray(a.point_type).slice(0, 3)} />
</View>
</Pressable>
); );
} }

View File

@ -6,6 +6,7 @@ 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,
@ -30,6 +31,9 @@ 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({
@ -39,9 +43,10 @@ export function QiBloodCollectionRenderer(props: CollectionRendererProps) {
const overviewText = useMemo(() => { const overviewText = useMemo(() => {
if (overviewQuery.resolution.status === "ready") { if (overviewQuery.resolution.status === "ready") {
return extractOverviewFromData(overviewQuery.resolution.data); const extracted = extractOverviewFromData(overviewQuery.resolution.data);
if (extracted) return extracted;
} }
return ""; return DEFAULT_QI_BLOOD_OVERVIEW;
}, [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
@ -65,15 +70,7 @@ export function QiBloodCollectionRenderer(props: CollectionRendererProps) {
const header = ( const header = (
<View style={styles.headerContainer}> <View style={styles.headerContainer}>
{overviewText ? ( {overviewText ? <OverviewCard text={overviewText} /> : null}
<View style={styles.overviewCard}>
<View style={styles.overviewHeader}>
<Ionicons name="information-circle" size={20} color={Colors.primary} />
<Text style={styles.overviewTitle}>Overview</Text>
</View>
<Text style={styles.overviewText}>{overviewText}</Text>
</View>
) : null}
<Text style={styles.sectionHeading}>Categories</Text> <Text style={styles.sectionHeading}>Categories</Text>
</View> </View>
@ -127,36 +124,11 @@ export function QiBloodCardRenderer({
const styles = StyleSheet.create({ const styles = StyleSheet.create({
headerContainer: { headerContainer: {
paddingHorizontal: moderateScale(16), paddingBottom: verticalScale(8),
paddingTop: verticalScale(14), gap: 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(15), fontSize: moderateScale(16),
fontWeight: "700", fontWeight: "700",
color: Colors.textPrimary, color: Colors.textPrimary,
marginLeft: moderateScale(4), marginLeft: moderateScale(4),

View File

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