Compare commits

...

102 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
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
104 changed files with 5468 additions and 1364 deletions

12
.env
View File

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

2
.gitignore vendored
View File

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

View File

@ -11,7 +11,7 @@ def projectRoot = rootDir.getAbsoluteFile().getParentFile().getAbsolutePath()
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"
// 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()
@ -87,9 +87,9 @@ android {
buildToolsVersion rootProject.ext.buildToolsVersion
compileSdk rootProject.ext.compileSdkVersion
namespace 'com.anonymous.acupedia'
namespace 'com.renown.mobile.acupedia'
defaultConfig {
applicationId 'com.anonymous.acupedia'
applicationId 'com.renown.mobile.acupedia'
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1

View File

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

View File

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

View File

@ -1,4 +1,4 @@
package com.anonymous.acupedia
package com.renown.mobile.acupedia
import android.app.Application
import android.content.res.Configuration
@ -55,3 +55,4 @@ class MainApplication : Application(), ReactApplication {
ApplicationLifecycleDispatcher.onConfigurationChanged(this, newConfig)
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.7 KiB

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.0 KiB

After

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.1 KiB

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.8 KiB

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

After

Width:  |  Height:  |  Size: 20 KiB

View File

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

View File

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

View File

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

View File

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

View File

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

11
eas.json Normal file
View File

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

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 734 KiB

View File

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

View File

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

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

View File

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

View File

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

View File

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

View File

@ -18,6 +18,7 @@ import BaseTextInput from "@/components/forms/BaseTextInput";
import PasswordInput from "@/components/forms/PasswordInput";
import PrimaryButton from "@/components/buttons/PrimaryButton";
import FieldLabel from "@/components/forms/FieldLabel";
import { validateEmail } from "@/constants/countries";
import { forgotPassword, resetPassword } from "@/features/auth/api/auth.api";
export default function ForgotPasswordScreen() {
@ -36,12 +37,9 @@ export default function ForgotPasswordScreen() {
const handleRequestOtp = async () => {
setEmailError("");
const cleanEmail = email.trim().toLowerCase();
if (!cleanEmail) {
setEmailError("Email is required");
return;
}
if (!/\S+@\S+\.\S+/.test(cleanEmail)) {
setEmailError("Please enter a valid email address");
const emailErr = validateEmail(cleanEmail);
if (emailErr) {
setEmailError(emailErr);
return;
}

View File

@ -63,7 +63,7 @@ export default function ChangePasswordScreen() {
setConfirmError("Please confirm your new password");
hasError = true;
} else if (newPassword !== confirmPassword) {
setConfirmError("Passwords do not match");
setConfirmError("Confirm password do not match.");
hasError = true;
}
@ -89,11 +89,23 @@ export default function ChangePasswordScreen() {
const errMsg =
err?.response?.data?.detail ||
"Failed to update password. Please check your current password.";
setCurrentError(errMsg);
if (Platform.OS === "web") {
window.alert(errMsg);
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);
} else if (
typeof errMsg === "string" &&
errMsg.toLowerCase().includes("confirm")
) {
setConfirmError(errMsg);
} else {
Alert.alert("Error", errMsg);
setCurrentError(errMsg);
}
} finally {
setIsLoading(false);
@ -119,7 +131,10 @@ export default function ChangePasswordScreen() {
<FieldLabel label="Current Password" required />
<PasswordInput
value={currentPassword}
onChangeText={setCurrentPassword}
onChangeText={(text) => {
setCurrentPassword(text);
if (currentError) setCurrentError("");
}}
placeholder="Enter current password"
error={currentError}
/>
@ -129,7 +144,10 @@ export default function ChangePasswordScreen() {
<FieldLabel label="New Password" required />
<PasswordInput
value={newPassword}
onChangeText={setNewPassword}
onChangeText={(text) => {
setNewPassword(text);
if (newError) setNewError("");
}}
placeholder="Min. 8 characters with numbers & symbols"
error={newError}
/>
@ -139,7 +157,10 @@ export default function ChangePasswordScreen() {
<FieldLabel label="Confirm New Password" required />
<PasswordInput
value={confirmPassword}
onChangeText={setConfirmPassword}
onChangeText={(text) => {
setConfirmPassword(text);
if (confirmError) setConfirmError("");
}}
placeholder="Re-enter new password"
error={confirmError}
/>

View File

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

View File

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

View File

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

View File

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

View File

@ -1,12 +1,37 @@
import React, { useState } from "react";
import { Alert, StyleSheet, View } from "react-native";
import React, { useState, useMemo } from "react";
import {
KeyboardAvoidingView,
Modal,
Platform,
Pressable,
ScrollView,
StyleSheet,
Text,
TextInput,
View,
} from "react-native";
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 PasswordInput from "@/components/forms/PasswordInput";
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 { register } from "@/features/auth/api/auth.api";
@ -16,9 +41,13 @@ export default function SignUpForm() {
const [fullName, setFullName] = useState("");
const [email, setEmail] = useState("");
const [selectedCountry, setSelectedCountry] = useState<CountryCode>(DEFAULT_COUNTRY);
const [phone, setPhone] = useState("");
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [showCountryModal, setShowCountryModal] = useState(false);
const [countrySearch, setCountrySearch] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [fullNameError, setFullNameError] = useState("");
const [emailError, setEmailError] = useState("");
@ -26,9 +55,62 @@ export default function SignUpForm() {
const [passwordError, setPasswordError] = 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 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, "");
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 () => {
@ -44,17 +126,22 @@ export default function SignUpForm() {
hasError = true;
}
if (!email.trim()) {
setEmailError("Email is required");
hasError = true;
} else if (!/\S+@\S+\.\S+/.test(email)) {
setEmailError("Please enter a valid email address");
const emailErr = validateEmail(email);
if (emailErr) {
setEmailError(emailErr);
hasError = true;
}
if (phone.trim() && phone.length < 10) {
setPhoneError("Phone number must be 10 digits");
hasError = true;
if (phone.trim()) {
const err = validatePhoneNumber(
phone.trim(),
selectedCountry.code,
selectedCountry.country
);
if (err) {
setPhoneError(err);
hasError = true;
}
}
if (!password) {
@ -87,20 +174,28 @@ export default function SignUpForm() {
if (hasError) return;
setIsLoading(true);
try {
const formattedPhone = phone.trim()
? formatE164Phone(selectedCountry.code, phone.trim(), selectedCountry.country)
: undefined;
const response = await register({
email: email.trim().toLowerCase(),
password,
full_name: fullName.trim(),
phone_number: phone.trim() ? phone.trim() : undefined,
phone_number: formattedPhone,
country: selectedCountry.country,
});
const { user } = response;
setRegisteredUser({
id: user.id,
name: user.display_name,
name: user.display_name ?? fullName.trim(),
email: user.email,
phone_number: user.phone_number ?? formattedPhone,
country: user.country ?? selectedCountry.country,
});
// Redirect directly to login screen without alert block
@ -114,6 +209,8 @@ export default function SignUpForm() {
errMsg = detail[0].msg || JSON.stringify(detail[0]);
}
alert("Registration Failed: " + errMsg);
} finally {
setIsLoading(false);
}
};
@ -141,18 +238,49 @@ export default function SignUpForm() {
error={emailError}
/>
<BaseTextInput
value={phone}
onChangeText={handlePhoneChange}
placeholder="Phone Number (Optional)"
keyboardType="number-pad"
autoCapitalize="none"
autoCorrect={false}
textContentType="telephoneNumber"
maxLength={10}
leftIcon="call-outline"
error={phoneError}
/>
{/* 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}
onChangeText={handlePhoneChange}
placeholder={selectedCountry.placeholder || "Phone Number (Optional)"}
placeholderTextColor={AuthColors.textSecondary}
keyboardType="number-pad"
autoCapitalize="none"
autoCorrect={false}
textContentType="telephoneNumber"
maxLength={selectedCountry.maxLength}
style={styles.phoneInput}
/>
</View>
{phoneError ? (
<Text style={styles.errorText}>{phoneError}</Text>
) : (
<Text style={styles.phoneHelperText}>
{selectedCountry.minLength === selectedCountry.maxLength
? `${selectedCountry.country}: Requires exactly ${selectedCountry.maxLength} digits`
: `${selectedCountry.country}: ${selectedCountry.minLength} to ${selectedCountry.maxLength} digits`}
</Text>
)}
</View>
<PasswordInput
value={password}
@ -171,9 +299,128 @@ export default function SignUpForm() {
<View style={styles.buttonSpacing}>
<PrimaryButton
title="Sign Up"
loading={isLoading}
onPress={handleSignUp}
/>
</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>
);
}
@ -185,4 +432,154 @@ const styles = StyleSheet.create({
buttonSpacing: {
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

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

View File

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

View File

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

View File

@ -141,6 +141,21 @@ export function ContentMediaGallery({ media, title = "Visual Reference" }: Conte
const [viewerIndex, setViewerIndex] = useState<number | null>(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;
const handleMomentumEnd = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
@ -169,6 +184,12 @@ export function ContentMediaGallery({ media, title = "Visual Reference" }: Conte
offset: carouselWidth * index,
index,
})}
onScrollToIndexFailed={(info) => {
listRef.current?.scrollToOffset({
offset: info.index * carouselWidth,
animated: true,
});
}}
onMomentumScrollEnd={handleMomentumEnd}
renderItem={({ item, index }) => (
<Pressable
@ -192,12 +213,16 @@ export function ContentMediaGallery({ media, title = "Visual Reference" }: Conte
{items.length > 1 ? (
<View style={styles.dots} accessibilityElementsHidden>
{items.map((item, index) => (
{visibleDots.map(({ item, index }) => (
<Pressable
key={item.id}
onPress={() => {
setActiveIndex(index);
listRef.current?.scrollToIndex({ index, animated: true });
try {
listRef.current?.scrollToIndex({ index, animated: true });
} catch {
listRef.current?.scrollToOffset({ offset: index * carouselWidth, animated: true });
}
}}
hitSlop={6}
>
@ -254,7 +279,12 @@ const styles = StyleSheet.create({
},
zoomText: { color: Colors.white, fontSize: 12, fontWeight: "700" },
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 },
dotActive: { width: 18, backgroundColor: Colors.primary },
});

View File

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

View File

@ -1,22 +1,53 @@
import React from "react";
import React, { useMemo } from "react";
import { ScrollView } from "react-native";
import type { DetailRendererProps } from "../types/renderer.types";
import { humanizeKey } from "./helpers/value";
import { buildDefinitionLabelMap, humanizeKey, resolveAttributeLabel } from "./helpers/value";
import { ContentValue } from "./shared/ContentValue";
import { Hero } from "./shared/Hero";
import { ImageGallery } from "./shared/ImageGallery";
import { SectionCard } from "./shared/SectionCard";
const RESERVED_KEYS = new Set(["code"]);
const RESERVED_KEYS = new Set([
"code",
"id",
"slug",
"sort_order",
"link",
"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
* ContentDetailScreen, so object insertion order is the intended display order.
* Each attribute is rendered in its own separate SectionCard.
* For therapeutics modules, the redundant Hero name card is hidden.
*/
export function GenericDetailRenderer({ content, data }: DetailRendererProps) {
export function GenericDetailRenderer({
content,
data,
moduleCode,
templateCode,
definitions,
}: 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 (
<ScrollView
contentContainerStyle={{
@ -27,15 +58,25 @@ export function GenericDetailRenderer({ content, data }: DetailRendererProps) {
}}
showsVerticalScrollIndicator={false}
>
<Hero title={content.title || "Untitled content"} subtitle={content.summary ?? undefined} />
<Hero
title={heroTitle}
subtitle={content.summary ?? undefined}
/>
<ImageGallery images={[]} />
{Object.entries(data)
.filter(([key]) => !RESERVED_KEYS.has(key))
.map(([key, value]) => (
<SectionCard key={key} title={humanizeKey(key)}>
<ContentValue value={value} />
</SectionCard>
))}
.filter(
([key]) =>
!RESERVED_KEYS.has(key.toLowerCase()) &&
!(isTherapeutic && key.toLowerCase() === "name"),
)
.map(([key, value]) => {
const label = resolveAttributeLabel(key, definitionMap);
return (
<SectionCard key={key} title={label}>
<ContentValue value={value} />
</SectionCard>
);
})}
</ScrollView>
);
}

View File

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

View File

@ -7,6 +7,7 @@ import { Colors } from "@/theme";
import { asNumber, asString } from "../helpers/value";
import { CollectionScaffold } from "../shared/CollectionScaffold";
import { ContentCountBadge } from "../shared/ContentCountBadge";
import { OverviewCard } from "../shared/OverviewCard";
import type {
CollectionItemRendererProps,
CollectionRendererProps,
@ -15,21 +16,14 @@ import type {
export function FiveElementsCollectionRenderer(props: CollectionRendererProps) {
const header = (
<View style={styles.overviewContainer}>
<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}>
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>
<OverviewCard
style={styles.overviewCard}
paragraphs={[
"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.",
"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).",
"The sequences below detail the Generating, Overacting, and Insulting relationships and their specific clinical presentations.",
]}
/>
<Text style={styles.sectionHeading}>Sequences</Text>
</View>
);
@ -51,11 +45,10 @@ export function FiveElementsCardRenderer({
}: CollectionItemRendererProps) {
const attributes = item.attributes;
const title = asString(attributes.title) || asString(attributes.name) || item.title;
const label =
asString(attributes.content_label) ||
const subtitle =
asString(attributes.sub_title) ||
asString(attributes.description) ||
item.summary ||
"Open sequence";
(item.summary && item.summary !== "Open sequence" ? item.summary : null);
const sortOrder = asNumber(attributes.sort_order);
const sequenceNumber = typeof sortOrder === "number" ? sortOrder + 1 : undefined;
@ -72,9 +65,11 @@ export function FiveElementsCardRenderer({
<View style={styles.textContainer}>
<Text style={styles.title}>{title}</Text>
<Text style={styles.description} numberOfLines={1}>
{label}
</Text>
{subtitle ? (
<Text style={styles.description} numberOfLines={1}>
{subtitle}
</Text>
) : null}
</View>
<ContentCountBadge
@ -91,35 +86,8 @@ const styles = StyleSheet.create({
marginBottom: verticalScale(14),
},
overviewCard: {
backgroundColor: "#FFFFFF",
borderRadius: moderateScale(16),
borderWidth: 1,
borderColor: "#E2EAE5",
padding: moderateScale(16),
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: {
fontSize: moderateScale(15),
fontWeight: "700",

View File

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

View File

@ -1,27 +1,377 @@
import React from "react";
import { Pressable, StyleSheet, Text, View } from "react-native";
import React, { useMemo, useState } from "react";
import {
ActivityIndicator,
LayoutAnimation,
Platform,
Pressable,
StyleSheet,
Text,
UIManager,
View,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { useRouter } from "expo-router";
import { moderateScale, verticalScale } from "react-native-size-matters";
import { Colors } from "@/theme";
import { asNumber, asString, asStringArray, humanizeKey } from "../helpers/value";
import {
asNumber,
asString,
asStringArray,
buildDefinitionLabelMap,
humanizeKey,
resolveAttributeLabel,
} from "../helpers/value";
import { CollectionScaffold } from "../shared/CollectionScaffold";
import { ContentCountBadge } from "../shared/ContentCountBadge";
import { greenTone } from "../shared/reading-palette";
import {
useModuleContentDetailQuery,
useModuleTemplateContentDetailsQuery,
useTemplateDefinitionsQuery,
} from "../../hooks/use-content-queries";
import type {
CollectionItemRendererProps,
CollectionRendererProps,
} from "../../types/renderer.types";
if (Platform.OS === "android" && UIManager.setLayoutAnimationEnabledExperimental) {
UIManager.setLayoutAnimationEnabledExperimental(true);
}
export function ModuleCatalogCollectionRenderer(props: CollectionRendererProps) {
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({
item,
onPress,
}: CollectionItemRendererProps) {
const attributes = item.attributes;
const rawTitle = asString(attributes.name) || item.title;
const rawTitle =
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()
@ -47,12 +397,27 @@ export function ModuleCatalogCardRenderer({
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 (
<Pressable
accessibilityRole="button"
onPress={onPress}
style={({ pressed }) => [styles.row, pressed && styles.pressed]}
accessibilityRole={isClickable ? "button" : undefined}
disabled={!isClickable}
onPress={isClickable ? onPress : undefined}
style={({ pressed }) => [
styles.row,
isClickable && pressed && styles.pressed,
]}
>
<View style={styles.iconWrapper}>
<Ionicons name="book-outline" size={22} color={Colors.primary} />
@ -68,14 +433,212 @@ export function ModuleCatalogCardRenderer({
</View>
<ContentCountBadge
count={asNumber(attributes.content_count)}
count={count}
label={asString(attributes.content_label)}
/>
<Ionicons name="chevron-forward" size={20} color="#9CA3AF" />
{isClickable ? (
<Ionicons name="chevron-forward" size={20} color="#9CA3AF" />
) : null}
</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({
row: {
minHeight: moderateScale(68),
@ -111,3 +674,4 @@ const styles = StyleSheet.create({
lineHeight: moderateScale(16),
},
});

View File

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

View File

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

View File

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

View File

@ -6,7 +6,7 @@ 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 { SectionCard } from "../shared/SectionCard";
import { OverviewCard } from "../shared/OverviewCard";
import type {
CollectionItemRendererProps,
CollectionRendererProps,
@ -17,9 +17,7 @@ export function SixStagesCollectionRenderer(props: CollectionRendererProps) {
const header = overviewText ? (
<View style={styles.overviewContainer}>
<SectionCard title="Overview" defaultExpanded={true}>
<Text style={styles.overviewText}>{overviewText}</Text>
</SectionCard>
<OverviewCard text={overviewText} />
</View>
) : null;
@ -93,11 +91,6 @@ const styles = StyleSheet.create({
overviewContainer: {
marginBottom: verticalScale(14),
},
overviewText: {
fontSize: moderateScale(14),
lineHeight: moderateScale(22),
color: "#374151",
},
row: {
minHeight: moderateScale(68),
flexDirection: "row",

View File

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

View File

@ -234,8 +234,7 @@ const styles = StyleSheet.create({
lineHeight: 17,
fontWeight: "700",
color: "#597064",
textTransform: "uppercase",
letterSpacing: 0.4,
letterSpacing: 0.15,
},
pathway: {
fontSize: 16,

View File

@ -8,6 +8,7 @@ import { Colors } from "@/theme";
import type { DetailRendererProps } from "../../types/renderer.types";
import { ContentLinkAttributeSections } from "../shared/ContentLinkAttributeSections";
import { Hero } from "../shared/Hero";
import { OverviewCard } from "../shared/OverviewCard";
import { Paragraphs } from "../shared/Paragraphs";
import { SectionCard } from "../shared/SectionCard";
import { asRecordArray, asString, asStringArray } from "../helpers/value";
@ -96,20 +97,7 @@ export function FiveElementsDetailRenderer({
{/* Overview Card (rendered only when overview/content exists in data) */}
{overviewParagraphs.length > 0 ? (
<View style={styles.overviewCard}>
<View style={styles.overviewHeader}>
<Ionicons name="information-circle" size={20} color={Colors.primary} />
<Text style={styles.overviewTitle}>Overview</Text>
</View>
{overviewParagraphs.map((para, idx) => (
<Text
key={idx}
style={[styles.overviewText, idx > 0 && styles.paragraphSpacing]}
>
{para}
</Text>
))}
</View>
<OverviewCard paragraphs={overviewParagraphs} />
) : null}
{/* Dynamic Sequences List from data.sections */}
@ -181,20 +169,7 @@ export function FiveElementsDetailRenderer({
{/* Overview Card (rendered only when overview/content exists in data) */}
{overviewParagraphs.length > 0 ? (
<View style={styles.overviewCard}>
<View style={styles.overviewHeader}>
<Ionicons name="information-circle" size={20} color={Colors.primary} />
<Text style={styles.overviewTitle}>Overview</Text>
</View>
{overviewParagraphs.map((para, idx) => (
<Text
key={idx}
style={[styles.overviewText, idx > 0 && styles.paragraphSpacing]}
>
{para}
</Text>
))}
</View>
<OverviewCard paragraphs={overviewParagraphs} />
) : null}
{/* Collapsible Pattern Cards from data.sections */}
@ -206,7 +181,6 @@ export function FiveElementsDetailRenderer({
<SectionCard
key={idx}
title={sectionTitle}
defaultExpanded={false}
>
{sectionContent.length > 0 ? (
<Paragraphs items={sectionContent} />
@ -231,32 +205,6 @@ const styles = StyleSheet.create({
paddingBottom: verticalScale(40),
gap: verticalScale(14),
},
overviewCard: {
backgroundColor: "#FFFFFF",
borderRadius: moderateScale(16),
borderWidth: 1,
borderColor: "#E2EAE5",
padding: moderateScale(16),
},
overviewHeader: {
flexDirection: "row",
alignItems: "center",
marginBottom: verticalScale(8),
gap: moderateScale(8),
},
overviewTitle: {
fontSize: moderateScale(16),
fontWeight: "700",
color: Colors.textPrimary,
},
overviewText: {
fontSize: moderateScale(13),
lineHeight: verticalScale(19),
color: Colors.textSecondary,
},
paragraphSpacing: {
marginTop: verticalScale(10),
},
sequencesContainer: {
gap: verticalScale(10),
},

View File

@ -15,6 +15,7 @@ import { BulletList } from "../shared/BulletList";
import { ContentLinkAttributeSections } from "../shared/ContentLinkAttributeSections";
import { ContentValue } from "../shared/ContentValue";
import { Hero } from "../shared/Hero";
import { OverviewCard } from "../shared/OverviewCard";
import { Paragraphs } from "../shared/Paragraphs";
import { SectionCard } from "../shared/SectionCard";
@ -115,15 +116,7 @@ export function FourLevelsDetailRenderer({
<Hero title={title} />
{/* Direct Overview Card matching Four Levels 1st page */}
{overview ? (
<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}>{overview}</Text>
</View>
) : null}
{overview ? <OverviewCard text={overview} /> : null}
{/* Patterns List with numbered cards matching 1st page */}
<View style={styles.patternsSection}>
@ -288,29 +281,6 @@ const styles = StyleSheet.create({
paddingBottom: verticalScale(40),
gap: verticalScale(14),
},
overviewCard: {
backgroundColor: "#FFFFFF",
borderRadius: moderateScale(16),
borderWidth: 1,
borderColor: "#E2EAE5",
padding: moderateScale(16),
},
overviewHeader: {
flexDirection: "row",
alignItems: "center",
marginBottom: verticalScale(8),
gap: moderateScale(8),
},
overviewTitle: {
fontSize: moderateScale(16),
fontWeight: "700",
color: Colors.textPrimary,
},
overviewText: {
fontSize: moderateScale(13),
lineHeight: verticalScale(19),
color: Colors.textSecondary,
},
patternsSection: {
gap: verticalScale(10),
},

View File

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

View File

@ -278,7 +278,6 @@ const styles = StyleSheet.create({
lineHeight: 18,
fontWeight: "700",
color: "#536F61",
textTransform: "uppercase",
letterSpacing: 0.35,
letterSpacing: 0.15,
},
});

View File

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

View File

@ -8,6 +8,7 @@ import type { DetailRendererProps } from "../../types/renderer.types";
import { BackActionContext } from "../../context/BackActionContext";
import { ContentLinkAttributeSections } from "../shared/ContentLinkAttributeSections";
import { Hero } from "../shared/Hero";
import { OverviewCard } from "../shared/OverviewCard";
import { SectionCard } from "../shared/SectionCard";
import { BulletList } from "../shared/BulletList";
import { Paragraphs } from "../shared/Paragraphs";
@ -77,6 +78,11 @@ function parseClinicalManifestations(raw: unknown): string[] {
return [text];
}
const DEFAULT_CATEGORY_FALLBACKS: Record<string, string> = {
qi_and_blood:
"Qi and blood are mutually dependent. Qi generates, moves, and holds blood, while blood nourishes and carries qi. Pathological changes often involve both substances concurrently, manifesting as combined patterns of deficiency and stasis.",
};
function extractCategoryOverview(data: Record<string, unknown>, categoryCode: string): string {
const normalizedCode = categoryCode.toLowerCase().replace(/[^a-z0-9_]/g, "_");
@ -106,6 +112,10 @@ function extractCategoryOverview(data: Record<string, unknown>, categoryCode: st
return data.content.trim();
}
if (DEFAULT_CATEGORY_FALLBACKS[normalizedCode]) {
return DEFAULT_CATEGORY_FALLBACKS[normalizedCode];
}
return "";
}
@ -329,15 +339,7 @@ export function QiBloodDetailRenderer({
<Hero title={categoryTitle} />
{/* Category Overview Card */}
{categoryOverview ? (
<View style={styles.overviewCard}>
<View style={styles.overviewHeader}>
<Ionicons name="information-circle" size={20} color={Colors.primary} />
<Text style={styles.overviewTitle}>Overview</Text>
</View>
<Text style={styles.overviewText}>{categoryOverview}</Text>
</View>
) : null}
{categoryOverview ? <OverviewCard text={categoryOverview} /> : null}
{/* Numbered Patterns List */}
{rootPatterns.length > 0 ? (
@ -381,29 +383,6 @@ const styles = StyleSheet.create({
paddingBottom: verticalScale(40),
gap: verticalScale(14),
},
overviewCard: {
backgroundColor: "#FFFFFF",
borderRadius: moderateScale(16),
borderWidth: 1,
borderColor: "#E2EAE5",
padding: moderateScale(18),
},
overviewHeader: {
flexDirection: "row",
alignItems: "center",
marginBottom: verticalScale(10),
gap: moderateScale(8),
},
overviewTitle: {
fontSize: moderateScale(16),
fontWeight: "700",
color: Colors.textPrimary,
},
overviewText: {
fontSize: moderateScale(14),
lineHeight: moderateScale(22),
color: Colors.textSecondary,
},
patternsContainer: {
gap: verticalScale(10),
},

View File

@ -2,7 +2,12 @@ import React, { useMemo } from "react";
import { ScrollView, StyleSheet } from "react-native";
import type { DetailRendererProps } from "../../types/renderer.types";
import { asString, humanizeKey } from "../helpers/value";
import {
asString,
buildDefinitionLabelMap,
humanizeKey,
resolveAttributeLabel,
} from "../helpers/value";
import {
findAttributePresentationRule,
isEmptyValue,
@ -41,9 +46,7 @@ export function SixStagesDetailRenderer({
const title = humanizeKey(rawTitle);
const orderedSections = useMemo(() => {
const definitionByLabel = new Map(
(definitions ?? []).map((d) => [d.code, d.label]),
);
const definitionByLabel = buildDefinitionLabelMap(definitions);
return Object.entries(data)
.filter(
@ -55,8 +58,7 @@ export function SixStagesDetailRenderer({
.map(([key, value]) => {
const rule = findAttributePresentationRule(key, presentationAttributes);
const order = presentationDisplayOrder(rule);
const rawLabel = definitionByLabel.get(key) || key;
const label = humanizeKey(rawLabel);
const label = resolveAttributeLabel(key, definitionByLabel);
return { key, value, order, label };
})
.sort((a, b) => a.order - b.order || a.label.localeCompare(b.label));

View File

@ -2,7 +2,12 @@ import React, { useMemo } from "react";
import { ScrollView, StyleSheet } from "react-native";
import type { DetailRendererProps } from "../../types/renderer.types";
import { asString, humanizeKey } from "../helpers/value";
import {
asString,
buildDefinitionLabelMap,
humanizeKey,
resolveAttributeLabel,
} from "../helpers/value";
import {
findAttributePresentationRule,
isEmptyValue,
@ -36,9 +41,7 @@ export function TcmPatternDetailRenderer({
const title = humanizeKey(rawTitle);
const orderedSections = useMemo(() => {
const definitionByLabel = new Map(
(definitions ?? []).map((d) => [d.code, d.label]),
);
const definitionByLabel = buildDefinitionLabelMap(definitions);
return Object.entries(data)
.filter(
@ -49,8 +52,7 @@ export function TcmPatternDetailRenderer({
.map(([key, value]) => {
const rule = findAttributePresentationRule(key, presentationAttributes);
const order = presentationDisplayOrder(rule);
const rawLabel = definitionByLabel.get(key) || key;
const label = humanizeKey(rawLabel);
const label = resolveAttributeLabel(key, definitionByLabel);
return { key, value, order, label };
})
.sort((a, b) => a.order - b.order || a.label.localeCompare(b.label));

View File

@ -7,11 +7,12 @@ import { Colors } from "@/theme";
import type { DetailRendererProps } from "../../types/renderer.types";
import { BackActionContext } from "../../context/BackActionContext";
import { Hero } from "../shared/Hero";
import { OverviewCard } from "../shared/OverviewCard";
import { SectionCard } from "../shared/SectionCard";
import { Paragraphs } from "../shared/Paragraphs";
import { BulletList } from "../shared/BulletList";
import { ContentValue } from "../shared/ContentValue";
import { asString, asStringArray } from "../helpers/value";
import { asString, asStringArray, formatPatternTitle } from "../helpers/value";
import { useContentSearchInfiniteQuery } from "../../hooks/use-content-search-infinite-query";
interface PatternData {
@ -72,7 +73,7 @@ const BURNER_CONFIGS: Array<{ key: string; title: string }> = [
// Embedded fallback patterns for guaranteed zero-latency / offline rendering
const FALLBACK_PATTERNS: Record<string, PatternData> = {
"wind_heat_in_the_lungs_defensive_qi_portion": {
name: "Wind-Heat in the Lungs’ Defensive Qi portion",
name: "Wind-Heat in the Lung's Defensive Qi portion",
clinicalManifestation:
"Fever, aversion to cold, headache, sore throat, slight sweating, runny nose with yellow discharge, swollen tonsils, body aches, slight thirst",
pathology:
@ -154,7 +155,9 @@ function extractBurnerList(data: Record<string, unknown>, burnerKey: string): st
for (const [k, v] of Object.entries(data)) {
const normK = normalizeKey(k);
if (normK === normTarget && Array.isArray(v)) {
return v.map((item) => asString(item).trim()).filter((item) => item.length > 0);
return v
.map((item) => formatPatternTitle(asString(item).trim()))
.filter((item) => item.length > 0);
}
}
return [];
@ -227,8 +230,9 @@ export function ThreeBurnersDetailRenderer({
const items = patternsQuery.data?.pages?.flatMap((p) => p.items) ?? [];
for (const it of items) {
const a = it.attributes as Record<string, unknown>;
const name = asString(a.name) || it.title;
if (!name) continue;
const rawName = asString(a.name) || it.title;
if (!rawName) continue;
const name = formatPatternTitle(rawName);
const clinicalRaw =
a["clinical menifestation"] ??
@ -284,7 +288,8 @@ export function ThreeBurnersDetailRenderer({
const activePatternData: PatternData | null = useMemo(() => {
if (isDirectLeafPattern) {
const name = asString(data.name) || content.title || "Three Burners Pattern";
const rawName = asString(data.name) || content.title || "Three Burners Pattern";
const name = formatPatternTitle(rawName);
const clinicalRaw =
data["clinical menifestation"] ??
data["clinical manifestation"] ??
@ -309,11 +314,16 @@ export function ThreeBurnersDetailRenderer({
}
if (!selectedPatternName) return null;
return (
patternMap.get(normalizeKey(selectedPatternName)) || {
name: selectedPatternName,
}
);
const found = patternMap.get(normalizeKey(selectedPatternName));
if (found) {
return {
...found,
name: formatPatternTitle(found.name),
};
}
return {
name: formatPatternTitle(selectedPatternName),
};
}, [isDirectLeafPattern, data, content.title, selectedPatternName, patternMap]);
// Connect drilldown navigation to the top-header back button
@ -414,25 +424,28 @@ export function ThreeBurnersDetailRenderer({
<View style={styles.patternsContainer}>
<Text style={styles.sectionHeading}>Patterns</Text>
{selectedBurner.patterns.map((patternName, idx) => (
<Pressable
key={patternName}
accessibilityRole="button"
accessibilityLabel={`Open ${patternName}`}
onPress={() => setSelectedPatternName(patternName)}
style={({ pressed }) => [styles.patternRow, pressed && styles.pressed]}
>
<View style={styles.numberBadge}>
<Text style={styles.numberText}>{idx + 1}</Text>
</View>
{selectedBurner.patterns.map((patternName, idx) => {
const formattedTitle = formatPatternTitle(patternName);
return (
<Pressable
key={patternName}
accessibilityRole="button"
accessibilityLabel={`Open ${formattedTitle}`}
onPress={() => setSelectedPatternName(patternName)}
style={({ pressed }) => [styles.patternRow, pressed && styles.pressed]}
>
<View style={styles.numberBadge}>
<Text style={styles.numberText}>{idx + 1}</Text>
</View>
<View style={styles.patternTitleContainer}>
<Text style={styles.patternTitle}>{patternName}</Text>
</View>
<View style={styles.patternTitleContainer}>
<Text style={styles.patternTitle}>{formattedTitle}</Text>
</View>
<Ionicons name="chevron-forward" size={20} color="#9CA3AF" />
</Pressable>
))}
<Ionicons name="chevron-forward" size={20} color="#9CA3AF" />
</Pressable>
);
})}
</View>
</ScrollView>
@ -457,15 +470,7 @@ export function ThreeBurnersDetailRenderer({
<Hero title="Three Burners" />
{/* Overview Card */}
{overviewText ? (
<View style={styles.overviewCard}>
<View style={styles.overviewHeader}>
<Ionicons name="information-circle" size={20} color={Colors.primary} />
<Text style={styles.overviewTitle}>Overview</Text>
</View>
<Text style={styles.overviewText}>{overviewText}</Text>
</View>
) : null}
{overviewText ? <OverviewCard text={overviewText} /> : null}
{/* Burner Categories (1. Upper Burner, 2. Middle Burner, 3. Lower Burner) */}
<View style={styles.patternsContainer}>
@ -505,29 +510,6 @@ const styles = StyleSheet.create({
paddingBottom: verticalScale(40),
gap: verticalScale(14),
},
overviewCard: {
backgroundColor: "#FFFFFF",
borderRadius: moderateScale(16),
borderWidth: 1,
borderColor: "#E2EAE5",
padding: moderateScale(16),
},
overviewHeader: {
flexDirection: "row",
alignItems: "center",
marginBottom: verticalScale(8),
gap: moderateScale(8),
},
overviewTitle: {
fontSize: moderateScale(16),
fontWeight: "700",
color: Colors.textPrimary,
},
overviewText: {
fontSize: moderateScale(13),
lineHeight: verticalScale(20),
color: Colors.textSecondary,
},
patternsContainer: {
gap: verticalScale(10),
},

View File

@ -7,6 +7,7 @@ import { Colors } from "@/theme";
import type { DetailRendererProps } from "../../types/renderer.types";
import { BackActionContext } from "../../context/BackActionContext";
import { Hero } from "../shared/Hero";
import { OverviewCard } from "../shared/OverviewCard";
import { SectionCard } from "../shared/SectionCard";
import { Paragraphs } from "../shared/Paragraphs";
import { BulletList } from "../shared/BulletList";
@ -613,15 +614,7 @@ export function TwelveChannelsDetailRenderer({
<Hero title="Twelve Channels" />
{/* 1. Overview Card */}
{overviewText ? (
<View style={styles.overviewCard}>
<View style={styles.overviewHeader}>
<Ionicons name="information-circle" size={20} color={Colors.primary} />
<Text style={styles.overviewTitle}>Overview</Text>
</View>
<Text style={styles.overviewText}>{overviewText}</Text>
</View>
) : null}
{overviewText ? <OverviewCard text={overviewText} /> : null}
{/* 2. Organ vs Channel Card */}
{organVsChannelText ? (
@ -756,29 +749,6 @@ const styles = StyleSheet.create({
paddingBottom: verticalScale(40),
gap: verticalScale(14),
},
overviewCard: {
backgroundColor: "#F0FDF4",
borderRadius: moderateScale(14),
borderWidth: 1,
borderColor: "#DCFCE7",
padding: moderateScale(16),
},
overviewHeader: {
flexDirection: "row",
alignItems: "center",
marginBottom: moderateScale(8),
gap: moderateScale(6),
},
overviewTitle: {
fontSize: moderateScale(15),
fontWeight: "700",
color: Colors.primaryDark,
},
overviewText: {
fontSize: moderateScale(14),
color: Colors.textSecondary,
lineHeight: moderateScale(21),
},
infoCard: {
backgroundColor: "#FFFFFF",
borderRadius: moderateScale(14),

View File

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

View File

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

View File

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

View File

@ -2,7 +2,11 @@ import type { CollectionItemRendererComponent, CollectionRendererComponent, Deta
import { GenericCollectionRenderer } from "./GenericCollectionRenderer";
import { GenericCardRenderer } from "./GenericCardRenderer";
import { GenericDetailRenderer } from "./GenericDetailRenderer";
import { ModuleCatalogCollectionRenderer, ModuleCatalogCardRenderer } from "./collections/ModuleCatalogRenderers";
import {
ModuleCatalogCollectionRenderer,
ModuleCatalogCardRenderer,
PatternAccordionCardRenderer,
} from "./collections/ModuleCatalogRenderers";
import { AcuPointCollectionRenderer, AcuPointIndexCollectionRenderer, AcuPointCardRenderer, AcuPointIndexCardRenderer } from "./collections/PointRenderers";
import { MeridianCollectionRenderer, MeridianIndexCollectionRenderer, MeridianCardRenderer, MeridianIndexCardRenderer } from "./collections/MeridianRenderers";
import { EovCollectionRenderer, EovIndexCollectionRenderer, EovCardRenderer, EovIndexCardRenderer } from "./collections/EovRenderers";
@ -49,6 +53,11 @@ import { SixStagesCollectionRenderer, SixStagesCardRenderer } from "./collection
import { SixStagesDetailRenderer } from "./details/SixStagesDetailRenderer";
import { TcmPatternDetailRenderer } from "./details/TcmPatternDetailRenderer";
import { ExtraOrdinaryVesselsDetailRenderer } from "./details/ExtraOrdinaryVesselsDetailRenderer";
import { NutritionCategoryDetailRenderer } from "./details/NutritionCategoryDetailRenderer";
import {
GynecologyDiseaseCollectionRenderer,
createGynecologyDiseaseCollectionRenderer,
} from "./collections/GynecologyRenderers";
export const collectionRenderers: Readonly<Record<string, CollectionRendererComponent>> = Object.freeze({
module_catalog_collection: ModuleCatalogCollectionRenderer,
@ -64,33 +73,25 @@ export const collectionRenderers: Readonly<Record<string, CollectionRendererComp
four_levels_collection: FourLevelsCollectionRenderer,
eight_principles_collection: EightPrinciplesCollectionRenderer,
pathogenic_factors_collection: PathogenicFactorsCollectionRenderer,
five_elements_collection: FiveElementsCollectionRenderer,
qi_blood_collection: QiBloodCollectionRenderer,
twelve_channels_collection: TwelveChannelsCollectionRenderer,
three_burners_collection: ThreeBurnersCollectionRenderer,
six_stages_collection: SixStagesCollectionRenderer,
chinese_scalp_acupuncture_collection: ModuleCatalogCollectionRenderer,
nutrition_food_collection: ModuleCatalogCollectionRenderer,
nutrition_category_collection: ModuleCatalogCollectionRenderer,
nutrition_effect_collection: ModuleCatalogCollectionRenderer,
m0042_ct0001_collection: ModuleCatalogCollectionRenderer,
m0016_ct0001_collection: FourLevelsCollectionRenderer,
m0011_ct0005_collection: EightPrinciplesCollectionRenderer,
m0014_ct0001_collection: PathogenicFactorsCollectionRenderer,
five_elements_collection: FiveElementsCollectionRenderer,
m0019_ct0005_collection: FiveElementsCollectionRenderer,
qi_blood_collection: QiBloodCollectionRenderer,
m0013_ct0001_collection: QiBloodCollectionRenderer,
twelve_channels_collection: TwelveChannelsCollectionRenderer,
m0018_ct0002_collection: TwelveChannelsCollectionRenderer,
three_burners_collection: ThreeBurnersCollectionRenderer,
m0017_ct0002_collection: ThreeBurnersCollectionRenderer,
six_stages_collection: SixStagesCollectionRenderer,
m0015_ct0001_collection: SixStagesCollectionRenderer,
m0015_ct0002_collection: SixStagesCollectionRenderer,
m0015_ct0003_collection: SixStagesCollectionRenderer,
m0015_ct0004_collection: SixStagesCollectionRenderer,
m0015_ct0005_collection: SixStagesCollectionRenderer,
m0015_ct0006_collection: SixStagesCollectionRenderer,
tcm_pattern_list_collection: ModuleCatalogCollectionRenderer,
m0012_ct0001_collection: ModuleCatalogCollectionRenderer,
disease_collection: ModuleCatalogCollectionRenderer,
auriculotherapy_collection: ModuleCatalogCollectionRenderer,
gynecology_disease_collection: GynecologyDiseaseCollectionRenderer,
// Module-specific renderers removed for generic handling
});
export const collectionItemRenderers: Readonly<Record<string, CollectionItemRendererComponent>> = Object.freeze({
module_catalog_card: ModuleCatalogCardRenderer,
pattern_accordion_card: PatternAccordionCardRenderer,
gynecology_pattern_card: PatternAccordionCardRenderer,
acu_point_index_card: AcuPointIndexCardRenderer,
acu_point_card: AcuPointCardRenderer,
meridian_index_card: MeridianIndexCardRenderer,
@ -104,33 +105,23 @@ export const collectionItemRenderers: Readonly<Record<string, CollectionItemRend
eight_principles_card: EightPrinciplesCardRenderer,
pathogenic_factors_card: PathogenicFactorsCardRenderer,
five_elements_card: FiveElementsCardRenderer,
qi_blood_card: QiBloodCardRenderer,
twelve_channels_card: TwelveChannelsCardRenderer,
three_burners_card: ThreeBurnersCardRenderer,
six_stages_card: SixStagesCardRenderer,
chinese_scalp_acupuncture_card: ModuleCatalogCardRenderer,
nutrition_food_card: ModuleCatalogCardRenderer,
nutrition_category_card: ModuleCatalogCardRenderer,
nutrition_effect_card: ModuleCatalogCardRenderer,
m0042_ct0001_card: ModuleCatalogCardRenderer,
m0016_ct0001_card: FourLevelsCardRenderer,
m0011_ct0005_card: EightPrinciplesCardRenderer,
m0014_ct0001_card: PathogenicFactorsCardRenderer,
m0019_ct0005_card: FiveElementsCardRenderer,
qi_blood_card: QiBloodCardRenderer,
m0013_ct0001_card: QiBloodCardRenderer,
twelve_channels_card: TwelveChannelsCardRenderer,
m0018_ct0002_card: TwelveChannelsCardRenderer,
three_burners_card: ThreeBurnersCardRenderer,
m0017_ct0002_card: ThreeBurnersCardRenderer,
six_stages_card: SixStagesCardRenderer,
m0015_ct0001_card: SixStagesCardRenderer,
m0015_ct0002_card: SixStagesCardRenderer,
m0015_ct0003_card: SixStagesCardRenderer,
m0015_ct0004_card: SixStagesCardRenderer,
m0015_ct0005_card: SixStagesCardRenderer,
m0015_ct0006_card: SixStagesCardRenderer,
tcm_pattern_list_card: ModuleCatalogCardRenderer,
m0012_ct0001_card: ModuleCatalogCardRenderer,
disease_card: ModuleCatalogCardRenderer,
auriculotherapy_card: ModuleCatalogCardRenderer,
// Module-specific card renderers removed for generic handling
});
export const detailRenderers: Readonly<Record<string, DetailRendererComponent>> = Object.freeze({
extra_ordinary_vessel_detail: ExtraOrdinaryVesselsDetailRenderer,
module_catalog_detail: IndexEntryDetailRenderer,
nutrition_category_detail: NutritionCategoryDetailRenderer,
acu_point_index_detail: IndexEntryDetailRenderer,
meridian_index_detail: MeridianPointsDetailRenderer,
meridian_points_detail: MeridianPointsDetailRenderer,
@ -164,10 +155,8 @@ export const detailRenderers: Readonly<Record<string, DetailRendererComponent>>
chinese_scalp_acupuncture_detail: AcuPointDetailRenderer,
nutrition_food_detail: GenericDetailRenderer,
nutrition_effect_detail: GenericDetailRenderer,
m0042_ct0001_detail: IndexEntryDetailRenderer,
m0042_ct0002_detail: IndexEntryDetailRenderer,
m0042_ct0003_detail: IndexEntryDetailRenderer,
m0042_ct0004_detail: IndexEntryDetailRenderer,
disease_detail: GenericDetailRenderer,
auriculotherapy_detail: GenericDetailRenderer,
m0016_ct0002_detail: FourLevelsDetailRenderer,
m0011_ct0001_detail: EightPrinciplesDetailRenderer,
m0011_ct0002_detail: EightPrinciplesDetailRenderer,
@ -230,6 +219,25 @@ export function resolveCollectionRenderer(
const normalizedModule = moduleCode?.trim().toLowerCase();
const normalizedTemplate = templateCode?.trim().toLowerCase();
if (code === "gynecology_disease_collection") {
return normalizedTemplate
? createGynecologyDiseaseCollectionRenderer(normalizedTemplate)
: GynecologyDiseaseCollectionRenderer;
}
if (
normalizedModule === "m0042" &&
normalizedTemplate &&
normalizedTemplate !== "m0042_ct0001" &&
normalizedTemplate !== "m0042_ct0002" &&
normalizedTemplate !== "m0042_ct0003" &&
normalizedTemplate !== "m0042_ct0004" &&
normalizedTemplate !== "m0042_ct0006" &&
normalizedTemplate !== "m0042_ct0007"
) {
return createGynecologyDiseaseCollectionRenderer(normalizedTemplate);
}
if (normalizedTemplate === "m0016_ct0001" || normalizedModule === "m0016") {
return FourLevelsCollectionRenderer;
}
@ -264,6 +272,10 @@ export function resolveCollectionRenderer(
) {
return ModuleCatalogCollectionRenderer;
}
// Generic fallback for any mXXXX_ct... template
if (normalizedTemplate?.startsWith("m") && normalizedTemplate?.includes("_ct")) {
return ModuleCatalogCollectionRenderer;
}
if (code && collectionRenderers[code]) return collectionRenderers[code];
reportMissingRenderer("collection", code);
@ -282,6 +294,20 @@ export function resolveCollectionItemRenderer(
const normalizedModule = moduleCode?.trim().toLowerCase();
const normalizedTemplate = templateCode?.trim().toLowerCase();
if (
code === "gynecology_pattern_card" ||
(normalizedModule === "m0042" &&
normalizedTemplate &&
normalizedTemplate !== "m0042_ct0001" &&
normalizedTemplate !== "m0042_ct0002" &&
normalizedTemplate !== "m0042_ct0003" &&
normalizedTemplate !== "m0042_ct0004" &&
normalizedTemplate !== "m0042_ct0006" &&
normalizedTemplate !== "m0042_ct0007")
) {
return PatternAccordionCardRenderer;
}
if (normalizedTemplate === "m0016_ct0001" || normalizedModule === "m0016") {
return FourLevelsCardRenderer;
}
@ -317,6 +343,10 @@ export function resolveCollectionItemRenderer(
) {
return ModuleCatalogCardRenderer;
}
// Generic fallback for any mXXXX_ct... template
if (normalizedTemplate?.startsWith("m") && normalizedTemplate?.includes("_ct")) {
return ModuleCatalogCardRenderer;
}
if (code && collectionItemRenderers[code]) return collectionItemRenderers[code];
reportMissingRenderer("collection-item", code);
@ -348,6 +378,13 @@ export function resolveDetailRenderer(
return MeridianPointsDetailRenderer;
}
if (
normalizedTemplate === "m0031_ct0003" ||
code === "nutrition_category_detail"
) {
return NutritionCategoryDetailRenderer;
}
if (
normalizedTemplate === "m0016_ct0002" ||
(normalizedModule === "m0016" && (code === "pattern_detail" || code === "module_catalog_detail"))
@ -410,6 +447,10 @@ export function resolveDetailRenderer(
return ExtraOrdinaryVesselsDetailRenderer;
}
// Generic fallback for any mXXXX_ct... template
if (normalizedTemplate?.startsWith("m") && normalizedTemplate?.includes("_ct")) {
return GenericDetailRenderer;
}
if (code && detailRenderers[code]) return detailRenderers[code];
reportMissingRenderer("detail", code);
return GenericDetailRenderer;

View File

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

View File

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

View File

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

View File

@ -152,6 +152,25 @@ export function ContentValue({
);
}
if (typeof value === "string") {
const text = value.trim();
if (text.includes("\n") || text.includes(";")) {
const bullets = parseBullets(text);
if (bullets.length > 1) {
return <BulletList items={bullets} />;
}
}
if (text.includes(",")) {
const parts = parseBullets(text);
if (
parts.length > 1 &&
parts.every((p) => p.length > 0 && p.length < 50 && !p.endsWith("."))
) {
return <BulletList items={parts} />;
}
}
}
return (
<Text style={[styles.text, textStyle]}>
{typeof value === "boolean" ? (value ? "Yes" : "No") : String(value)}
@ -198,7 +217,6 @@ const styles = StyleSheet.create({
lineHeight: 17,
fontWeight: "700",
color: Colors.textSecondary,
textTransform: "uppercase",
letterSpacing: 0.35,
letterSpacing: 0.15,
},
});

View File

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

View File

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

View File

@ -64,7 +64,6 @@ const styles = StyleSheet.create({
fontSize: 13,
lineHeight: 18,
color: "#536F61",
textTransform: "uppercase",
letterSpacing: 0.35,
letterSpacing: 0.15,
},
});

View File

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

View File

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

View File

@ -1,4 +1,5 @@
import React, { type PropsWithChildren, isValidElement } from "react";
import { Ionicons } from "@expo/vector-icons";
import { isEmptyValue } from "../../utils/attribute-presentation";
import { AccordionSection } from "./AccordionSection";
@ -7,6 +8,8 @@ import { useSettingsStore } from "@/store/settings.store";
export interface SectionCardProps {
title: string;
defaultExpanded?: boolean;
icon?: keyof typeof Ionicons.glyphMap;
iconColor?: string;
}
function hasRenderableContent(node: React.ReactNode): boolean {
@ -37,6 +40,8 @@ function hasRenderableContent(node: React.ReactNode): boolean {
export function SectionCard({
title,
defaultExpanded,
icon,
iconColor,
children,
}: PropsWithChildren<SectionCardProps>) {
if (!hasRenderableContent(children)) return null;
@ -48,8 +53,19 @@ export function SectionCard({
const isExpanded =
defaultExpanded !== undefined ? defaultExpanded : accordionDefaultExpanded;
const resolvedIcon =
icon ??
(title.trim().toLowerCase() === "overview"
? ("information-circle" as const)
: undefined);
return (
<AccordionSection title={title} defaultExpanded={isExpanded}>
<AccordionSection
title={title}
defaultExpanded={isExpanded}
icon={resolvedIcon}
iconColor={iconColor}
>
{children}
</AccordionSection>
);

View File

@ -57,11 +57,30 @@ export function CollectionTemplateScreen({
const merged = useMemo(() => {
const pages = query.data?.pages ?? [];
const items = pages.flatMap((page) => page.items);
if (templateCode === "m0001_ct0002") {
const isExtra = (item: (typeof items)[0]) => {
const name = (item.attributes?.name ? String(item.attributes.name) : item.title || "").toLowerCase();
const code = (item.attributes?.code ? String(item.attributes.code) : item.slug || "").toLowerCase();
return name.includes("extra") || code.includes("extra");
};
const extraItems = items.filter(isExtra);
const regularItems = items.filter((item) => !isExtra(item));
regularItems.sort((a, b) => {
const aOrder = typeof a.attributes?.sort_order === "number" ? (a.attributes.sort_order as number) : 999;
const bOrder = typeof b.attributes?.sort_order === "number" ? (b.attributes.sort_order as number) : 999;
return aOrder - bOrder;
});
return {
total: pages[0]?.total ?? 0,
items: [...regularItems, ...extraItems],
};
}
return {
total: pages[0]?.total ?? 0,
items: pages.flatMap((page) => page.items),
items,
};
}, [query.data]);
}, [query.data, templateCode]);
const collectionRendererCode = contract.presentation.renderers.collection;
const itemRendererCode = contract.presentation.renderers.collection_item;
@ -134,8 +153,15 @@ export function CollectionTemplateScreen({
const isCatalog =
collectionRendererCode === "module_catalog_collection" ||
itemRendererCode === "module_catalog_card" ||
collectionRendererCode === "disease_collection" ||
itemRendererCode === "disease_card" ||
collectionRendererCode === "auriculotherapy_collection" ||
itemRendererCode === "auriculotherapy_card" ||
collectionRendererCode === "gynecology_disease_collection" ||
moduleCode === "m0042" ||
templateCode === "m0001_ct0001" ||
templateCode === "m0002_ct0001";
templateCode === "m0002_ct0001" ||
templateCode === "m0041_ct0001";
const pageTone: PageTone = isCatalog ? "green" : "purple";
return (
@ -165,6 +191,12 @@ export function CollectionTemplateScreen({
}
}}
onItemPress={(item) => {
const primaryLink = item.attributes?.link;
const primaryRefs = getNavigableContentReferences(primaryLink);
if (primaryRefs.length === 1) {
router.push(buildContentReferenceRoute(primaryRefs[0]) as never);
return;
}
const references = Object.values(item.attributes).flatMap((value) =>
getNavigableContentReferences(value),
);
@ -193,6 +225,12 @@ export function CollectionTemplateScreen({
}
}}
onItemPress={(item) => {
const primaryLink = item.attributes?.link;
const primaryRefs = getNavigableContentReferences(primaryLink);
if (primaryRefs.length === 1) {
router.push(buildContentReferenceRoute(primaryRefs[0]) as never);
return;
}
const references = Object.values(item.attributes).flatMap((value) =>
getNavigableContentReferences(value),
);

View File

@ -9,6 +9,7 @@ import { DetailPageShell } from "../renderers/shared/DetailPageShell";
import { applyPresentationContractToData } from "../utils/attribute-presentation";
import { BackActionContext } from "../context/BackActionContext";
import { PageToneProvider, type PageTone } from "../context/PageToneContext";
import { humanizeKey } from "../renderers/helpers/value";
export interface ContentDetailScreenProps {
moduleCode: string;
@ -98,9 +99,11 @@ function ContentDetailScreenResolved({
const presentationAttributes = screen.contractQuery.data?.presentation.attributes ?? [];
const presentedData = applyPresentationContractToData(response.data, presentationAttributes);
const foodName = typeof response.data.food_name === "string" ? response.data.food_name.trim() : "";
const pointName = typeof response.data.point_name === "string" ? response.data.point_name.trim() : "";
const name = typeof response.data.name === "string" ? response.data.name.trim() : "";
const displayTitle = pointName || name || response.content.title;
const rawTitle = foodName || pointName || name || response.content.title;
const displayTitle = humanizeKey(rawTitle);
const alternateNames = [response.data.alt_name_1, response.data.alt_name_2]
.filter((value): value is string => typeof value === "string" && value.trim().length > 0)
.map((value) => value.trim())
@ -133,7 +136,7 @@ function ContentDetailScreenResolved({
contentId={response.content.id}
content={{
id: response.content.id,
title: response.content.title,
title: displayTitle,
slug: response.content.slug,
summary: response.content.summary,
}}
@ -147,12 +150,12 @@ function ContentDetailScreenResolved({
moduleCode={moduleCode}
templateCode={templateCode}
contentId={response.content.id}
content={{
id: response.content.id,
title: response.content.title,
slug: response.content.slug,
summary: response.content.summary,
}}
content={{
id: response.content.id,
title: displayTitle,
slug: response.content.slug,
summary: response.content.summary,
}}
data={presentedData}
definitions={screen.definitionsQuery.data?.attributes ?? []}
presentationAttributes={presentationAttributes}

View File

@ -31,6 +31,7 @@ export interface ModuleResponse extends ModuleSummary {
release_version: string | null;
expected_release_date: string | null;
release_notes: string | null;
plan_code?: string | null;
metadata: Record<string, unknown>;
created_by: string | null;
updated_by: string | null;

View File

@ -75,6 +75,7 @@ const MODULE_VISUALS: Record<string, ModuleVisualConfig> = {
color: "#10B981",
isDefaultFree: false,
planCode: "PATTERN_CORE",
entryTemplateCode: "m0015_ct0007",
},
m0016: {
icon: "trending-up-outline",
@ -114,12 +115,13 @@ const MODULE_VISUALS: Record<string, ModuleVisualConfig> = {
color: "#10B981",
isDefaultFree: true,
planCode: "NUTRITION_CORE",
entryTemplateCode: "m0031_ct0001",
},
m0041: {
icon: "body-outline",
color: "#8B5CF6",
isDefaultFree: false,
planCode: "LIFETIME_ALL",
planCode: "THERAPEUTICS_EAR",
},
m0042: {
icon: "woman-outline",
@ -222,6 +224,7 @@ export function toModuleIndexItem(module: ModuleResponse): ModuleIndexItem {
const visual = MODULE_VISUALS[module.code.toLowerCase()];
const metadataIcon = readMetadataString(module, "icon");
const metadataColor = readMetadataString(module, "color");
const apiPlanCode = asNonBlankString(module.plan_code);
const metadataPlanCode = readMetadataString(module, "plan_code");
const metadataIsDefaultFree = readMetadataBoolean(module, "is_default_free");
@ -239,7 +242,7 @@ export function toModuleIndexItem(module: ModuleResponse): ModuleIndexItem {
icon: metadataIcon ?? visual?.icon ?? "folder-outline",
color: metadataColor ?? visual?.color ?? "#4F46E5",
isDefaultFree: metadataIsDefaultFree ?? visual?.isDefaultFree ?? false,
planCode: metadataPlanCode ?? visual?.planCode ?? "",
planCode: apiPlanCode ?? metadataPlanCode ?? visual?.planCode ?? "",
};
}

View File

@ -1,10 +1,11 @@
import React, { useState, useEffect } from "react";
import React, { useState, useEffect, useMemo } from "react";
import {
Modal,
Pressable,
ScrollView,
StyleSheet,
Text,
TextInput,
View,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
@ -19,6 +20,15 @@ import DropdownField from "@/components/forms/DropdownField";
import FieldLabel from "@/components/forms/FieldLabel";
import PrimaryButton from "@/components/buttons/PrimaryButton";
import { Colors } from "@/theme";
import {
SORTED_COUNTRY_CODES,
getCountryRuleByName,
validatePhoneNumber,
isValidPhoneNumber,
parsePhoneNumber,
formatE164Phone,
cleanPhoneInput,
} from "@/constants/countries";
interface EditProfileFormProps {
initialName?: string;
@ -29,46 +39,6 @@ interface EditProfileFormProps {
isLoading?: boolean;
}
const COMMON_COUNTRIES = [
"India",
"United States",
"United Kingdom",
"Canada",
"Australia",
"Germany",
"Singapore",
"Malaysia",
"New Zealand",
"United Arab Emirates",
"South Africa",
"Ireland",
"Netherlands",
"Switzerland",
"France",
"Spain",
];
export const isValidPhoneNumber = (val?: string): boolean => {
if (!val || !val.trim()) return true;
const trimmed = val.trim();
// Must match valid phone character format (optional '+', digits, spaces, hyphens, parentheses)
const phoneRegex = /^\+?[0-9\s\-()]+$/;
if (!phoneRegex.test(trimmed)) {
return false;
}
const digits = trimmed.replace(/\D/g, "");
// ITU-T E.164 standard allows 6 to 15 digits
return digits.length >= 6 && digits.length <= 15;
};
const cleanPhoneInput = (text: string): string => {
const trimmedStart = text.trimStart();
const hasPlus = trimmedStart.startsWith("+");
const rest = hasPlus ? trimmedStart.slice(1) : text;
const filtered = rest.replace(/[^0-9\s\-()]/g, "");
return hasPlus ? `+${filtered}` : filtered;
};
export default function EditProfileForm({
initialName = "User Name",
initialEmail = "user@example.com",
@ -83,6 +53,20 @@ export default function EditProfileForm({
const [nameError, setNameError] = useState("");
const [phoneError, setPhoneError] = useState("");
const [showCountryModal, setShowCountryModal] = useState(false);
const [countrySearch, setCountrySearch] = useState("");
const activeRule = getCountryRuleByName(country);
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.toLowerCase().includes(q) ||
c.label.toLowerCase().includes(q)
);
}, [countrySearch]);
useEffect(() => {
setFullName(initialName);
@ -104,15 +88,25 @@ export default function EditProfileForm({
};
const handlePhoneChange = (text: string) => {
const cleaned = cleanPhoneInput(text);
const cleaned = cleanPhoneInput(text, activeRule.maxLength + activeRule.code.length + 2);
setPhone(cleaned);
if (phoneError) {
if (!cleaned.trim() || isValidPhoneNumber(cleaned)) {
if (!cleaned.trim() || isValidPhoneNumber(cleaned, activeRule.code, country)) {
setPhoneError("");
}
}
};
const handleCountrySelect = (newCountry: string) => {
if (newCountry !== country) {
setPhone("");
setCountry(newCountry);
if (phoneError) setPhoneError("");
}
setShowCountryModal(false);
setCountrySearch("");
};
const handleSave = () => {
let hasError = false;
setNameError("");
@ -125,14 +119,26 @@ export default function EditProfileForm({
}
const trimmedPhone = phone.trim();
if (trimmedPhone && !isValidPhoneNumber(trimmedPhone)) {
setPhoneError("Please enter a valid phone number");
hasError = true;
if (trimmedPhone) {
const rule = getCountryRuleByName(country);
const err = validatePhoneNumber(trimmedPhone, rule.code, country);
if (err) {
setPhoneError(err);
hasError = true;
}
}
if (hasError) return;
onSave?.(trimmedName, trimmedPhone, country);
// Normalize phone before saving: ensure no spaces or hyphens, formatted as +<dialCode><nationalDigits>
let normalizedPhone = "";
if (trimmedPhone) {
const rule = getCountryRuleByName(country);
const parsed = parsePhoneNumber(trimmedPhone, country);
normalizedPhone = formatE164Phone(rule.code, parsed.localDigits, country);
}
onSave?.(trimmedName, normalizedPhone, country);
};
return (
@ -169,9 +175,9 @@ export default function EditProfileForm({
<BaseTextInput
value={phone}
onChangeText={handlePhoneChange}
placeholder="e.g. +91 9876543210"
placeholder={activeRule.placeholder ? `e.g. ${activeRule.code} ${activeRule.placeholder}` : `e.g. ${activeRule.code} 9876543210`}
keyboardType="phone-pad"
maxLength={25}
maxLength={activeRule.maxLength + activeRule.code.length + 2}
textContentType="telephoneNumber"
autoCapitalize="none"
autoCorrect={false}
@ -179,7 +185,9 @@ export default function EditProfileForm({
/>
{!phoneError && (
<Text style={styles.helperText}>
Enter mobile number with country code for login and notifications.
{activeRule.minLength === activeRule.maxLength
? `${activeRule.country} (${activeRule.code}): Requires exactly ${activeRule.maxLength} digits`
: `${activeRule.country} (${activeRule.code}): ${activeRule.minLength} to ${activeRule.maxLength} digits`}
</Text>
)}
</View>
@ -206,18 +214,27 @@ export default function EditProfileForm({
visible={showCountryModal}
transparent
animationType="slide"
onRequestClose={() => setShowCountryModal(false)}
onRequestClose={() => {
setShowCountryModal(false);
setCountrySearch("");
}}
>
<Pressable
style={styles.modalOverlay}
onPress={() => setShowCountryModal(false)}
onPress={() => {
setShowCountryModal(false);
setCountrySearch("");
}}
>
<View style={styles.modalSheet}>
<Pressable style={styles.modalSheet} onPress={() => {}}>
<View style={styles.modalHeader}>
<Text style={styles.modalTitle}>Select Country</Text>
<Pressable
hitSlop={8}
onPress={() => setShowCountryModal(false)}
onPress={() => {
setShowCountryModal(false);
setCountrySearch("");
}}
>
<Ionicons
name="close"
@ -227,45 +244,82 @@ export default function EditProfileForm({
</Pressable>
</View>
{/* Country Search Bar */}
<View style={styles.modalSearchContainer}>
<Ionicons
name="search-outline"
size={moderateScale(17)}
color={Colors.textSecondary}
/>
<TextInput
value={countrySearch}
onChangeText={setCountrySearch}
placeholder="Search country or code..."
placeholderTextColor={Colors.textSecondary}
style={styles.modalSearchInput}
autoCapitalize="none"
autoCorrect={false}
/>
{countrySearch.length > 0 && (
<Pressable
hitSlop={8}
onPress={() => setCountrySearch("")}
>
<Ionicons
name="close-circle"
size={moderateScale(17)}
color={Colors.textSecondary}
/>
</Pressable>
)}
</View>
<ScrollView
showsVerticalScrollIndicator={false}
contentContainerStyle={styles.countryList}
keyboardShouldPersistTaps="handled"
>
{COMMON_COUNTRIES.map((c) => {
const isSelected = country === c;
return (
<Pressable
key={c}
style={({ pressed }) => [
styles.countryItem,
isSelected && styles.countryItemSelected,
pressed && styles.countryItemPressed,
]}
onPress={() => {
setCountry(c);
setShowCountryModal(false);
}}
>
<Text
style={[
styles.countryName,
isSelected && styles.countryNameSelected,
{filteredCountries.length === 0 ? (
<View style={styles.emptyContainer}>
<Text style={styles.emptyText}>No countries found</Text>
</View>
) : (
filteredCountries.map((c) => {
const isSelected = country === c.country;
return (
<Pressable
key={c.iso2 + c.country}
style={({ pressed }) => [
styles.countryItem,
isSelected && styles.countryItemSelected,
pressed && styles.countryItemPressed,
]}
onPress={() => handleCountrySelect(c.country)}
>
{c}
</Text>
{isSelected && (
<Ionicons
name="checkmark"
size={moderateScale(18)}
color={Colors.primary}
/>
)}
</Pressable>
);
})}
<View style={styles.countryRow}>
<Text style={styles.countryDialCode}>{c.code}</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>
</Pressable>
</Pressable>
</Modal>
</View>
@ -323,6 +377,52 @@ const styles = StyleSheet.create({
color: Colors.textPrimary,
},
modalSearchContainer: {
flexDirection: "row",
alignItems: "center",
marginHorizontal: scale(16),
marginTop: verticalScale(10),
marginBottom: verticalScale(4),
paddingHorizontal: scale(12),
paddingVertical: verticalScale(8),
backgroundColor: "#F8FAFC",
borderRadius: moderateScale(10),
borderWidth: 1,
borderColor: "#E2E8F0",
gap: scale(8),
},
modalSearchInput: {
flex: 1,
fontSize: moderateScale(14),
color: Colors.textPrimary,
padding: 0,
},
emptyContainer: {
paddingVertical: verticalScale(24),
alignItems: "center",
},
emptyText: {
fontSize: moderateScale(14),
color: Colors.textSecondary,
},
countryRow: {
flexDirection: "row",
alignItems: "center",
gap: scale(10),
flex: 1,
},
countryDialCode: {
fontSize: moderateScale(13),
fontWeight: "700",
color: Colors.textSecondary,
minWidth: scale(46),
},
countryList: {
paddingHorizontal: scale(16),
paddingTop: verticalScale(8),

View File

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

View File

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

View File

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

View File

@ -36,6 +36,8 @@ export default function LoginScreen() {
<ScrollView
contentContainerStyle={styles.contentContainer}
keyboardShouldPersistTaps="handled"
keyboardDismissMode="on-drag"
automaticallyAdjustKeyboardInsets={true}
showsVerticalScrollIndicator={false}
>
<View style={styles.container}>

View File

@ -29,6 +29,8 @@ export default function SignUpScreen() {
<ScrollView
contentContainerStyle={styles.contentContainer}
keyboardShouldPersistTaps="handled"
keyboardDismissMode="on-drag"
automaticallyAdjustKeyboardInsets={true}
showsVerticalScrollIndicator={false}
>
<View style={styles.container}>
@ -60,6 +62,7 @@ const styles = StyleSheet.create({
contentContainer: {
flexGrow: 1,
paddingBottom: verticalScale(32),
},
container: {

View File

@ -65,8 +65,9 @@ export default function HomeScreen() {
useFocusEffect(
useCallback(() => {
void modulesQuery.refetch().catch((error) => console.warn("Unable to refresh modules:", error));
void refreshSession().catch((error) => console.warn("Unable to refresh session:", error));
}, [refreshSession]),
}, [modulesQuery.refetch, refreshSession]),
);
const unlockedModules = useMemo(() => {

View File

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

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