Compare commits

..

3 Commits

25 changed files with 416 additions and 495 deletions

View File

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

View File

@ -1,408 +1,353 @@
import { parsePhoneNumberFromString, type CountryCode as LibCountryCode } from "libphonenumber-js/max";
import {
getCountries,
getCountryCallingCode,
getExampleNumber,
parsePhoneNumberFromString,
type CountryCode as LibCountryCode,
} from "libphonenumber-js/max";
import metadata from "libphonenumber-js/metadata.max.json";
import examples from "libphonenumber-js/examples.mobile.json";
export interface CountryCode {
iso2: LibCountryCode;
code: string;
label: string;
country: string;
currency: string;
minLength: number;
maxLength: number;
placeholder: string;
validPrefixes?: string[];
example?: string;
}
type CountryMetadataTuple = readonly unknown[];
interface MetadataJson {
countries: Record<string, CountryMetadataTuple>;
country_calling_codes: Record<string, string[]>;
}
const typedMetadata = metadata as unknown as MetadataJson;
/** Converts an ISO 3166-1 alpha-2 code (e.g. "IN") into its Unicode flag emoji. */
const isoToFlag = (iso2: string): string => {
const upper = iso2.toUpperCase();
if (!/^[A-Z]{2}$/.test(upper)) return "🏳️";
return String.fromCodePoint(
0x1f1e6 + upper.charCodeAt(0) - 65,
0x1f1e6 + upper.charCodeAt(1) - 65
);
};
const regionDisplayNames =
typeof Intl !== "undefined" && typeof Intl.DisplayNames === "function"
? new Intl.DisplayNames(["en"], { type: "region" })
: null;
const getRegionName = (iso2: string): string => {
try {
return regionDisplayNames?.of(iso2) || iso2;
} catch {
return iso2;
}
};
const buildCountryRule = (iso2: LibCountryCode): CountryCode => {
const callingCode = getCountryCallingCode(iso2);
const code = `+${callingCode}`;
const flag = isoToFlag(iso2);
const country = getRegionName(iso2);
const countryMeta = typedMetadata.countries[iso2];
const mobileDesc = countryMeta?.[11] as unknown[] | undefined;
const mobileTuple = mobileDesc?.[1] as [string, number[]?] | undefined;
const generalLengths = countryMeta?.[3] as number[] | undefined;
const mobileLengths = mobileTuple?.[1] ?? generalLengths ?? [7, 15];
const minLength = Math.min(...mobileLengths);
const maxLength = Math.max(...mobileLengths);
const exampleNumber = getExampleNumber(iso2, examples);
const example = exampleNumber?.nationalNumber;
const placeholder =
minLength === maxLength
? `${minLength}-digit mobile number`
: `${minLength}-${maxLength} digit mobile number`;
return {
iso2,
code,
label: `${flag} ${code}`,
country,
minLength,
maxLength,
placeholder,
example,
};
};
// Order primary country per calling code before secondary territories (e.g. US before AG for +1, GB before GG for +44).
const isPrimaryForCallingCode = (iso2: LibCountryCode): boolean => {
const callingCode = getCountryCallingCode(iso2);
return typedMetadata.country_calling_codes[callingCode]?.[0] === iso2;
};
const allCountries = getCountries();
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" },
];
...allCountries.filter(isPrimaryForCallingCode),
...allCountries.filter((iso) => !isPrimaryForCallingCode(iso)),
].map(buildCountryRule);
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 DEFAULT_COUNTRY: CountryCode =
COUNTRY_CODES.find((c) => c.iso2 === "IN") ?? COUNTRY_CODES[0];
export const getCountryRuleByIso = (iso?: string | null): CountryCode => {
if (!iso) return DEFAULT_COUNTRY;
const upper = iso.toUpperCase().trim();
const upper = iso.trim().toUpperCase();
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();
const stripped = countryName.replace(/\s*\(\+\d+\)\s*$/, "").trim().toLowerCase();
if (!stripped) return DEFAULT_COUNTRY;
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",
}
c.country.toLowerCase() === stripped ||
c.iso2.toLowerCase() === stripped
) ||
COUNTRY_CODES.find(
(c) =>
c.country.toLowerCase().startsWith(stripped) ||
stripped.startsWith(c.country.toLowerCase())
) ||
DEFAULT_COUNTRY
);
};
export const getCountryRuleByDialCode = (dialCode?: string | null, countryHint?: string | null): CountryCode => {
export const getCountryRuleByDialCode = (
dialCode?: string | null,
countryHint?: string | null
): CountryCode => {
if (!dialCode) return DEFAULT_COUNTRY;
const normalizedDial = dialCode.startsWith("+") ? dialCode : `+${dialCode}`;
if (countryHint) {
const byCountry = getCountryRuleByName(countryHint);
if (byCountry && byCountry.code === dialCode) {
return byCountry;
}
if (byCountry.code === normalizedDial) 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",
}
COUNTRY_CODES.find((c) => c.code === normalizedDial) || DEFAULT_COUNTRY
);
};
const extractNationalDigits = (
cleaned: string,
digitsOnly: string,
rule: CountryCode
): string => {
const dialDigits = rule.code.replace(/\D/g, "");
// Try parsing as a national/international number directly for this country first.
const direct = parsePhoneNumberFromString(cleaned, rule.iso2);
if (direct?.nationalNumber && (!direct.country || direct.country === rule.iso2)) {
return direct.nationalNumber;
}
if (
digitsOnly.startsWith(dialDigits) &&
digitsOnly.length > dialDigits.length + 4
) {
return digitsOnly.slice(dialDigits.length);
}
return digitsOnly;
};
/**
* 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).
* Validates a mobile phone number generically against the selected country's
* libphonenumber-js rules, lengths, and number type.
* Returns null if valid, or a descriptive user-friendly error message.
*/
export const validatePhoneNumber = (
val?: string | null,
value: string,
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.";
const trimmed = value.trim();
if (!trimmed) {
return "Mobile number is required";
}
// Strictly disallow hyphens, dashes, and invalid symbols
if (/[\-_()/[\]]/.test(trimmed)) {
return "Phone number cannot contain hyphens or special symbols.";
if (!/^\+?[\d\s\-()]+$/.test(trimmed)) {
return "Mobile number can only contain digits";
}
// 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 rule = country
? getCountryRuleByName(country)
: dialCode
? getCountryRuleByDialCode(dialCode, country)
: DEFAULT_COUNTRY;
const cleaned = trimmed.replace(/[\s\-()]/g, "");
const digitsOnly = cleaned.replace(/\D/g, "");
if (!digitsOnly) {
return "Mobile number is required";
}
const allDigits = trimmed.replace(/\D/g, "");
if (allDigits.length === 0) {
return "Please enter a valid phone number with numeric digits.";
const nationalDigits = extractNationalDigits(cleaned, digitsOnly, rule);
const lengthLabel =
rule.minLength === rule.maxLength
? `exactly ${rule.minLength} digits`
: `${rule.minLength} to ${rule.maxLength} digits`;
if (nationalDigits.length < rule.minLength || nationalDigits.length > rule.maxLength) {
return `For ${rule.country}, the mobile number must be ${lengthLabel}.`;
}
let rule = country ? getCountryRuleByName(country) : undefined;
if (!rule && dialCode) {
rule = getCountryRuleByDialCode(dialCode, country);
}
if (!rule) {
rule = DEFAULT_COUNTRY;
const candidate = cleaned.startsWith("+") ? cleaned : `${rule.code}${nationalDigits}`;
const parsed = parsePhoneNumberFromString(candidate, rule.iso2);
if (!parsed || !parsed.isValid()) {
return "Please enter a valid number";
}
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 numberType = parsed.getType();
if (numberType && numberType !== "MOBILE" && numberType !== "FIXED_LINE_OR_MOBILE") {
return "Please enter a valid number";
}
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}).`;
return null;
};
export const isValidPhoneNumber = (
val?: string | null,
val: string,
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"
fullNumber: string,
fallbackCountry?: string
): { 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 defaultRule = fallbackCountry
? getCountryRuleByName(fallbackCountry)
: DEFAULT_COUNTRY;
const trimmed = (fullNumber || "").trim();
if (!trimmed) {
return {
country: defaultRule.country,
dialCode: defaultRule.code,
localDigits: "",
iso2: defaultRule.iso2,
};
}
const trimmed = fullPhone.trim();
const parsed = parsePhoneNumberFromString(trimmed, defaultRule.iso2);
if (parsed) {
if (parsed && parsed.countryCallingCode) {
const matchedRule = parsed.country
? getCountryRuleByIso(parsed.country)
: getCountryRuleByDialCode(`+${parsed.countryCallingCode}`, fallbackCountry);
return {
country: matchedRule.country,
dialCode: `+${parsed.countryCallingCode}`,
dialCode: matchedRule.code,
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 cleaned = trimmed.replace(/[\s\-()]/g, "");
if (cleaned.startsWith("+")) {
const sorted = [...COUNTRY_CODES].sort((a, b) => b.code.length - a.code.length);
for (const c of sorted) {
if (cleaned.startsWith(c.code)) {
return {
country: c.country,
dialCode: c.code,
localDigits: cleaned.slice(c.code.length).replace(/\D/g, ""),
iso2: c.iso2,
};
}
}
}
const rawDigits = trimmed.replace(/\D/g, "");
return {
country: defaultRule.country,
dialCode: defaultRule.code,
localDigits: rawDigits.slice(0, defaultRule.maxLength),
localDigits: cleaned.replace(/\D/g, ""),
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}`;
export const formatE164Phone = (
dialCode: string,
localDigits: string,
country?: string
): string => {
const rule = country
? getCountryRuleByName(country)
: getCountryRuleByDialCode(dialCode, country);
const cleaned = (localDigits || "").trim().replace(/[\s\-()]/g, "");
if (!cleaned) return "";
const digits = cleaned.replace(/\D/g, "");
const nationalDigits = extractNationalDigits(cleaned, digits, rule);
const candidate = cleaned.startsWith("+") ? cleaned : `${rule.code}${nationalDigits}`;
const parsed = parsePhoneNumberFromString(candidate, rule.iso2);
if (parsed && parsed.isValid()) {
return parsed.format("E.164");
if (parsed) {
return parsed.number;
}
let cleanLocal = rawDigits;
if (rule.iso2 !== "IT" && cleanLocal.startsWith("0")) {
cleanLocal = cleanLocal.replace(/^0+/, "");
return nationalDigits ? `${rule.code}${nationalDigits}` : "";
};
export const cleanPhoneInput = (text: string, maxLength = 15): string => {
if (!text) return "";
const trimmed = text.trim();
if (trimmed.startsWith("+")) {
const digitsOnly = trimmed.slice(1).replace(/\D/g, "");
return `+${digitsOnly}`.slice(0, maxLength + 1);
}
return `${code}${cleanLocal}`;
return trimmed.replace(/\D/g, "").slice(0, maxLength);
};
/**
* 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,
currentValue: string,
oldCountry: string,
newCountry: string
): string => {
const trimmed = currentPhone.trim();
if (!trimmed) return "";
const trimmed = (currentValue || "").trim();
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} `;
if (!parsed.localDigits) return "";
return formatE164Phone(newRule.code, parsed.localDigits, newRule.country);
};
/**
* 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 EMAIL_REGEX = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
export const validateEmail = (email?: string | null): string | null => {
if (!email || !email.trim()) {
export const validateEmail = (value: string): string | null => {
const trimmed = value.trim();
if (!trimmed) {
return "Email is required";
}
if (!EMAIL_REGEX.test(email.trim())) {
if (trimmed.includes(" ")) {
return "Email cannot contain spaces";
}
if (!EMAIL_REGEX.test(trimmed)) {
return "Please enter a valid email address";
}
return null;
};
export const isValidEmail = (email?: string | null): boolean => {
return validateEmail(email) === null;
export const isValidEmail = (val: string): boolean => {
return validateEmail(val) === null;
};

View File

@ -20,27 +20,31 @@ interface LoginTabsProps {
}
export default function LoginTabs({
activeTab,
onTabChange,
activeTab: _activeTab,
onTabChange: _onTabChange,
}: LoginTabsProps) {
// Temporarily hidden: restore return JSX below (and Phone tab inside) when multi-tab login is re-enabled
return null;
/*
return (
<View style={styles.container}>
<Pressable
accessibilityRole="button"
accessibilityLabel="Login with Email"
style={styles.tab}
onPress={() => onTabChange("email")}
onPress={() => _onTabChange("email")}
>
<Text
style={[
styles.text,
activeTab === "email" && styles.activeText,
_activeTab === "email" && styles.activeText,
]}
>
Email
</Text>
{activeTab === "email" && (
{_activeTab === "email" && (
<View style={styles.indicator} />
)}
</Pressable>
@ -49,23 +53,24 @@ export default function LoginTabs({
accessibilityRole="button"
accessibilityLabel="Login with Phone"
style={styles.tab}
onPress={() => onTabChange("phone")}
onPress={() => _onTabChange("phone")}
>
<Text
style={[
styles.text,
activeTab === "phone" && styles.activeText,
_activeTab === "phone" && styles.activeText,
]}
>
Phone
</Text>
{activeTab === "phone" && (
{_activeTab === "phone" && (
<View style={styles.indicator} />
)}
</Pressable>
</View>
);
*/
}
const styles = StyleSheet.create({

View File

@ -261,7 +261,11 @@ export default function SignUpForm() {
<TextInput
value={phone}
onChangeText={handlePhoneChange}
placeholder={selectedCountry.placeholder || "Phone Number (Optional)"}
placeholder={
selectedCountry.example
? `e.g. ${selectedCountry.example}`
: selectedCountry.placeholder || "Phone Number (Optional)"
}
placeholderTextColor={AuthColors.textSecondary}
keyboardType="number-pad"
autoCapitalize="none"

View File

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

View File

@ -2,7 +2,7 @@ import React, { useMemo } from "react";
import { ScrollView } from "react-native";
import type { DetailRendererProps } from "../types/renderer.types";
import { buildDefinitionLabelMap, humanizeKey, resolveAttributeLabel } from "./helpers/value";
import { humanizeKey } from "./helpers/value";
import { ContentValue } from "./shared/ContentValue";
import { Hero } from "./shared/Hero";
import { ImageGallery } from "./shared/ImageGallery";
@ -40,7 +40,10 @@ export function GenericDetailRenderer({
);
const definitionMap = useMemo(
() => buildDefinitionLabelMap(definitions),
() =>
new Map(
(definitions ?? []).map((d) => [d.code, d.label]),
),
[definitions],
);
@ -70,7 +73,8 @@ export function GenericDetailRenderer({
!(isTherapeutic && key.toLowerCase() === "name"),
)
.map(([key, value]) => {
const label = resolveAttributeLabel(key, definitionMap);
const rawLabel = definitionMap.get(key) || key;
const label = humanizeKey(rawLabel);
return (
<SectionCard key={key} title={label}>
<ContentValue value={value} />

View File

@ -549,13 +549,7 @@ export function GynecologyDiseaseCollectionRenderer(
</View>
);
return (
<CollectionScaffold
{...props}
header={header}
countLabel="Identifications of patterns"
/>
);
return <CollectionScaffold {...props} header={header} />;
}
export function createGynecologyDiseaseCollectionRenderer(templateCode: string) {

View File

@ -14,21 +14,13 @@ import { useRouter } from "expo-router";
import { moderateScale, verticalScale } from "react-native-size-matters";
import { Colors } from "@/theme";
import {
asNumber,
asString,
asStringArray,
buildDefinitionLabelMap,
humanizeKey,
resolveAttributeLabel,
} from "../helpers/value";
import { asNumber, asString, asStringArray, humanizeKey } 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,
@ -43,10 +35,6 @@ 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-");
@ -82,16 +70,6 @@ export function PatternAccordionCardRenderer({
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",
@ -160,8 +138,8 @@ export function PatternAccordionCardRenderer({
? rawManifestations.split("\n").map((s) => s.trim()).filter(Boolean)
: [];
const tongue = stripTrailingPeriod(asString(detailData.tongue));
const pulse = stripTrailingPeriod(asString(detailData.pulse));
const tongue = asString(detailData.tongue);
const pulse = 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)
@ -235,7 +213,7 @@ export function PatternAccordionCardRenderer({
{clinicalManifestations.length > 0 ? (
<View style={accordionStyles.section}>
<Text style={accordionStyles.sectionTitle}>
{resolveAttributeLabel("clinical_manifestations", labelMap, "Clinical Manifestations")}
Clinical Manifestations
</Text>
<View style={accordionStyles.bulletList}>
{clinicalManifestations.map((itemText, idx) => (
@ -248,23 +226,22 @@ export function PatternAccordionCardRenderer({
</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>
{/* 2. Tongue & Pulse (Side-by-Side as drawn) */}
{tongue || pulse ? (
<View style={accordionStyles.twoColumnBox}>
{tongue ? (
<View style={accordionStyles.column}>
<Text style={accordionStyles.columnLabel}>Tongue</Text>
<Text style={accordionStyles.columnValue}>{tongue}</Text>
</View>
) : null}
{tongue && pulse ? <View style={accordionStyles.columnDivider} /> : null}
{pulse ? (
<View style={accordionStyles.column}>
<Text style={accordionStyles.columnLabel}>Pulse</Text>
<Text style={accordionStyles.columnValue}>{pulse}</Text>
</View>
) : null}
</View>
) : null}
@ -272,7 +249,7 @@ export function PatternAccordionCardRenderer({
{treatmentPrinciples.length > 0 ? (
<View style={accordionStyles.section}>
<Text style={accordionStyles.sectionTitle}>
{resolveAttributeLabel("treatment_principle", labelMap, "Treatment Principle")}
Treatment Principle
</Text>
<View style={accordionStyles.bulletList}>
{treatmentPrinciples.map((itemText, idx) => (
@ -285,44 +262,42 @@ export function PatternAccordionCardRenderer({
</View>
) : null}
{/* 4. Acupuncture Points */}
{pointChips.length > 0 ? (
{/* 4. Acupuncture Points & Method */}
{pointChips.length > 0 || acuMethod ? (
<View style={accordionStyles.section}>
<Text style={accordionStyles.sectionTitle}>
{resolveAttributeLabel("acupuncture", labelMap, "Acupuncture Points")}
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>
{pointChips.length > 0 ? (
<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>
) : null}
{acuMethod ? (
<View style={accordionStyles.methodContainer}>
<Text style={accordionStyles.subSectionLabel}>Method:</Text>
<Text style={accordionStyles.methodText}>{acuMethod}</Text>
</View>
) : null}
</View>
) : null}
@ -330,7 +305,7 @@ export function PatternAccordionCardRenderer({
{explanations.length > 0 ? (
<View style={accordionStyles.section}>
<Text style={accordionStyles.sectionTitle}>
{resolveAttributeLabel("explanation", labelMap, "Explanation")}
Explanation
</Text>
<View style={accordionStyles.explanationList}>
{explanations.map((exp, idx) => (
@ -346,9 +321,7 @@ export function PatternAccordionCardRenderer({
{/* 6. Category */}
{category ? (
<View style={accordionStyles.categoryRow}>
<Text style={accordionStyles.categoryLabel}>
{`${resolveAttributeLabel("category", labelMap, "Category")}:`}
</Text>
<Text style={accordionStyles.categoryLabel}>Category:</Text>
<View style={accordionStyles.categoryBadge}>
<Text style={accordionStyles.categoryBadgeText}>{category}</Text>
</View>
@ -522,7 +495,8 @@ const accordionStyles = StyleSheet.create({
lineHeight: moderateScale(16),
fontWeight: "700",
color: "#4A6B5B",
letterSpacing: 0.15,
textTransform: "uppercase",
letterSpacing: 0.7,
},
bulletList: {
gap: verticalScale(8),
@ -545,10 +519,38 @@ const accordionStyles = StyleSheet.create({
lineHeight: moderateScale(21),
color: "#334155",
},
sectionText: {
twoColumnBox: {
flexDirection: "row",
backgroundColor: greenTone.soft,
borderRadius: moderateScale(10),
borderWidth: 1,
borderColor: greenTone.border,
paddingHorizontal: moderateScale(14),
paddingVertical: verticalScale(11),
alignItems: "stretch",
},
column: {
flex: 1,
gap: verticalScale(3),
},
columnDivider: {
width: StyleSheet.hairlineWidth,
backgroundColor: greenTone.border,
marginHorizontal: moderateScale(12),
},
columnLabel: {
fontSize: moderateScale(11),
lineHeight: moderateScale(15),
fontWeight: "700",
color: "#597064",
textTransform: "uppercase",
letterSpacing: 0.5,
},
columnValue: {
fontSize: moderateScale(14),
lineHeight: moderateScale(21),
color: "#334155",
lineHeight: moderateScale(20),
color: "#1E293B",
fontWeight: "600",
},
principleBox: {
backgroundColor: greenTone.soft,
@ -589,6 +591,23 @@ const accordionStyles = StyleSheet.create({
fontWeight: "700",
color: "#35664E",
},
methodContainer: {
marginTop: verticalScale(4),
flexDirection: "row",
alignItems: "flex-start",
gap: moderateScale(6),
},
subSectionLabel: {
fontSize: moderateScale(13),
fontWeight: "700",
color: "#597064",
},
methodText: {
flex: 1,
fontSize: moderateScale(13),
lineHeight: moderateScale(19),
color: "#334155",
},
explanationList: {
gap: verticalScale(8),
},
@ -621,7 +640,8 @@ const accordionStyles = StyleSheet.create({
lineHeight: moderateScale(15),
fontWeight: "700",
color: "#597064",
letterSpacing: 0.15,
textTransform: "uppercase",
letterSpacing: 0.5,
},
categoryBadge: {
backgroundColor: "#EEF7F1",

View File

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

View File

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

View File

@ -216,7 +216,8 @@ const styles = StyleSheet.create({
fontSize: moderateScale(12),
fontWeight: "700",
color: Colors.textSecondary,
letterSpacing: 0.2,
textTransform: "uppercase",
letterSpacing: 1,
marginBottom: verticalScale(12),
marginLeft: moderateScale(4),
},

View File

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

View File

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

View File

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

View File

@ -1,5 +1,3 @@
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);
@ -56,53 +54,3 @@ export function formatPatternTitle(value: string): string {
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

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

View File

@ -217,6 +217,7 @@ const styles = StyleSheet.create({
lineHeight: 17,
fontWeight: "700",
color: Colors.textSecondary,
letterSpacing: 0.15,
textTransform: "uppercase",
letterSpacing: 0.35,
},
});

View File

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

View File

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

View File

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

View File

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

@ -224,7 +224,6 @@ 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");
@ -242,7 +241,7 @@ export function toModuleIndexItem(module: ModuleResponse): ModuleIndexItem {
icon: metadataIcon ?? visual?.icon ?? "folder-outline",
color: metadataColor ?? visual?.color ?? "#4F46E5",
isDefaultFree: metadataIsDefaultFree ?? visual?.isDefaultFree ?? false,
planCode: apiPlanCode ?? metadataPlanCode ?? visual?.planCode ?? "",
planCode: metadataPlanCode ?? visual?.planCode ?? "",
};
}

View File

@ -24,7 +24,6 @@ import {
SORTED_COUNTRY_CODES,
getCountryRuleByName,
validatePhoneNumber,
isValidPhoneNumber,
parsePhoneNumber,
formatE164Phone,
cleanPhoneInput,
@ -91,9 +90,7 @@ export default function EditProfileForm({
const cleaned = cleanPhoneInput(text, activeRule.maxLength + activeRule.code.length + 2);
setPhone(cleaned);
if (phoneError) {
if (!cleaned.trim() || isValidPhoneNumber(cleaned, activeRule.code, country)) {
setPhoneError("");
}
setPhoneError("");
}
};
@ -175,7 +172,13 @@ export default function EditProfileForm({
<BaseTextInput
value={phone}
onChangeText={handlePhoneChange}
placeholder={activeRule.placeholder ? `e.g. ${activeRule.code} ${activeRule.placeholder}` : `e.g. ${activeRule.code} 9876543210`}
placeholder={
activeRule.example
? `e.g. ${activeRule.code} ${activeRule.example}`
: activeRule.placeholder
? `e.g. ${activeRule.code} ${activeRule.placeholder}`
: `e.g. ${activeRule.code} 9876543210`
}
keyboardType="phone-pad"
maxLength={activeRule.maxLength + activeRule.code.length + 2}
textContentType="telephoneNumber"

View File

@ -65,9 +65,8 @@ 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));
}, [modulesQuery.refetch, refreshSession]),
}, [refreshSession]),
);
const unlockedModules = useMemo(() => {

View File

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