acupedia-mobile-ui/src/features/content/renderers/details/QiBloodDetailRenderer.tsx

418 lines
12 KiB
TypeScript

import React, { useContext, useEffect, useState } from "react";
import { Pressable, ScrollView, 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 type { DetailRendererProps } from "../../types/renderer.types";
import { BackActionContext } from "../../context/BackActionContext";
import { ContentLinkAttributeSections } from "../shared/ContentLinkAttributeSections";
import { Hero } from "../shared/Hero";
import { SectionCard } from "../shared/SectionCard";
import { Paragraphs } from "../shared/Paragraphs";
import { asString, humanizeKey } from "../helpers/value";
const RESERVED_METADATA_KEYS = new Set([
"name",
"title",
"code",
"sort_order",
"content_count",
"content_label",
"default_image",
"default_image_id",
"default image",
"point_images",
"image",
"images",
"link",
]);
interface PatternItem {
key: string;
title: string;
data: Record<string, unknown>;
}
interface ParsedNode {
overview?: string;
clinical?: string;
analysis?: string;
subItems: PatternItem[];
otherTextEntries: Array<{ key: string; text: string }>;
}
function extractCategoryOverview(data: Record<string, unknown>, categoryCode: string): string {
const normalizedCode = categoryCode.toLowerCase().replace(/[^a-z0-9_]/g, "_");
// Check matching category key (e.g. data.qi, data.blood, data.qi_and_blood, data.body_fluids, data.identification)
for (const [k, v] of Object.entries(data)) {
const normK = k.toLowerCase().replace(/[^a-z0-9_]/g, "_");
if (
normK === normalizedCode ||
normK === "identification" ||
normK === "qi" ||
normK === "blood" ||
normK === "qi_and_blood" ||
normK === "body_fluids"
) {
if (v && typeof v === "object" && !Array.isArray(v)) {
const content = asString((v as Record<string, unknown>).content);
if (content) return content;
}
}
}
// Direct string keys
if (typeof data.overview === "string" && data.overview.trim().length > 0) {
return data.overview.trim();
}
if (typeof data.content === "string" && data.content.trim().length > 0) {
return data.content.trim();
}
return "";
}
function extractRootPatterns(data: Record<string, unknown>, categoryCode: string): PatternItem[] {
const normalizedCode = categoryCode.toLowerCase().replace(/[^a-z0-9_]/g, "_");
const patterns: PatternItem[] = [];
for (const [key, value] of Object.entries(data)) {
const normKey = key.toLowerCase().replace(/[^a-z0-9_]/g, "_");
// Skip metadata and category overview container
if (RESERVED_METADATA_KEYS.has(key.toLowerCase())) continue;
if (
normKey === normalizedCode ||
normKey === "identification" ||
normKey === "qi" ||
normKey === "blood" ||
normKey === "qi_and_blood" ||
normKey === "body_fluids"
) {
continue;
}
if (value && typeof value === "object" && !Array.isArray(value)) {
const record = value as Record<string, unknown>;
const itemTitle = asString(record.title) || asString(record.name) || humanizeKey(key);
patterns.push({
key,
title: itemTitle,
data: record,
});
}
}
return patterns;
}
function parseNode(raw: Record<string, unknown>): ParsedNode {
const contentTarget =
raw.content && typeof raw.content === "object" && !Array.isArray(raw.content)
? (raw.content as Record<string, unknown>)
: raw;
const overview =
asString(contentTarget.Overview) ||
asString(contentTarget.overview) ||
(typeof raw.content === "string" ? raw.content.trim() : undefined) ||
(typeof raw.overview === "string" ? raw.overview.trim() : undefined);
const clinical =
asString(contentTarget["Clinical manifestations"]) ||
asString(contentTarget.clinical_manifestations) ||
asString(contentTarget.clinical_manifestation) ||
asString(raw["Clinical manifestations"]) ||
asString(raw.clinical_manifestations);
const analysis =
asString(contentTarget.Analysis) ||
asString(contentTarget.analysis) ||
asString(raw.Analysis) ||
asString(raw.analysis);
const subItems: PatternItem[] = [];
const otherTextEntries: Array<{ key: string; text: string }> = [];
for (const [key, value] of Object.entries(contentTarget)) {
const lowerKey = key.toLowerCase();
if (RESERVED_METADATA_KEYS.has(lowerKey)) continue;
if (lowerKey === "overview" || lowerKey === "analysis") continue;
if (lowerKey.includes("clinical")) continue;
if (value && typeof value === "object" && !Array.isArray(value)) {
const rec = value as Record<string, unknown>;
const itemTitle = asString(rec.title) || asString(rec.name) || humanizeKey(key);
subItems.push({
key,
title: itemTitle,
data: rec,
});
} else if (typeof value === "string" && value.trim().length > 0) {
otherTextEntries.push({
key,
text: value.trim(),
});
}
}
return {
overview: overview || undefined,
clinical: clinical || undefined,
analysis: analysis || undefined,
subItems,
otherTextEntries,
};
}
export function QiBloodDetailRenderer({
moduleCode,
templateCode,
content,
data,
definitions,
presentationAttributes,
}: DetailRendererProps) {
// Navigation stack: empty means Screen 2 (category root); items represent drilldown levels
const [navStack, setNavStack] = useState<PatternItem[]>([]);
const { setCustomBackAction } = useContext(BackActionContext);
const categoryTitle =
asString(data.title) ||
asString(data.name) ||
content.title ||
"Qi-Blood";
const categoryCode = asString(data.code) || templateCode || "";
const categoryOverview = extractCategoryOverview(data, categoryCode);
const rootPatterns = extractRootPatterns(data, categoryCode);
const handlePush = (item: PatternItem) => {
setNavStack((prev) => [...prev, item]);
};
// Connect navigation stack to the top-header back button (standard across all modules)
useEffect(() => {
if (navStack.length > 0) {
setCustomBackAction(() => () => setNavStack((prev) => prev.slice(0, -1)));
return () => {
setCustomBackAction(null);
};
}
setCustomBackAction(null);
}, [navStack.length, setCustomBackAction]);
// ----------------------------------------------------
// SCREEN 3+ : Drilldown Item Screen (Leaf or Sub-group)
// ----------------------------------------------------
if (navStack.length > 0) {
const currentItem = navStack[navStack.length - 1];
const parsed = parseNode(currentItem.data);
return (
<ScrollView
contentContainerStyle={styles.container}
showsVerticalScrollIndicator={false}
>
<Hero title={currentItem.title} />
{/* 1. Overview Card */}
{parsed.overview ? (
<SectionCard title="Overview">
<Paragraphs items={[parsed.overview]} />
</SectionCard>
) : null}
{/* 2. Clinical Manifestations Card */}
{parsed.clinical ? (
<SectionCard title="Clinical Manifestations">
<Paragraphs items={[parsed.clinical]} />
</SectionCard>
) : null}
{/* 3. Analysis Card */}
{parsed.analysis ? (
<SectionCard title="Analysis">
<Paragraphs items={[parsed.analysis]} />
</SectionCard>
) : null}
{/* 4. Sub-patterns list if this node has nested items (e.g. Edema, Phlegm, Fluid retention) */}
{parsed.subItems.length > 0 ? (
<View style={styles.patternsContainer}>
<Text style={styles.sectionHeading}>Patterns</Text>
{parsed.subItems.map((item, idx) => (
<Pressable
key={item.key}
accessibilityRole="button"
accessibilityLabel={`Open ${item.title}`}
onPress={() => handlePush(item)}
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}>{item.title}</Text>
</View>
<Ionicons name="chevron-forward" size={20} color="#9CA3AF" />
</Pressable>
))}
</View>
) : null}
{/* 5. Any other text sections */}
{parsed.otherTextEntries.map(({ key, text }) => (
<SectionCard key={key} title={humanizeKey(key)}>
<Paragraphs items={[text]} />
</SectionCard>
))}
<ContentLinkAttributeSections
data={data}
definitions={definitions}
presentationAttributes={presentationAttributes}
/>
</ScrollView>
);
}
// ----------------------------------------------------
// SCREEN 2: Category Screen (Category Overview + Root Patterns)
// ----------------------------------------------------
return (
<ScrollView
contentContainerStyle={styles.container}
showsVerticalScrollIndicator={false}
>
<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}
{/* Numbered Patterns List */}
{rootPatterns.length > 0 ? (
<View style={styles.patternsContainer}>
<Text style={styles.sectionHeading}>Patterns</Text>
{rootPatterns.map((item, idx) => (
<Pressable
key={item.key}
accessibilityRole="button"
accessibilityLabel={`Open ${item.title}`}
onPress={() => handlePush(item)}
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}>{item.title}</Text>
</View>
<Ionicons name="chevron-forward" size={20} color="#9CA3AF" />
</Pressable>
))}
</View>
) : null}
<ContentLinkAttributeSections
data={data}
definitions={definitions}
presentationAttributes={presentationAttributes}
/>
</ScrollView>
);
}
const styles = StyleSheet.create({
container: {
paddingHorizontal: moderateScale(16),
paddingTop: verticalScale(14),
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),
},
sectionHeading: {
fontSize: moderateScale(15),
fontWeight: "700",
color: Colors.textPrimary,
marginLeft: moderateScale(4),
marginBottom: verticalScale(2),
},
patternRow: {
minHeight: moderateScale(60),
flexDirection: "row",
alignItems: "center",
padding: moderateScale(14),
backgroundColor: "#FFFFFF",
borderRadius: moderateScale(14),
borderWidth: 1,
borderColor: "#E2EAE5",
},
pressed: {
opacity: 0.72,
},
numberBadge: {
width: moderateScale(36),
height: moderateScale(36),
borderRadius: moderateScale(18),
backgroundColor: "#E8F5E9",
alignItems: "center",
justifyContent: "center",
},
numberText: {
fontSize: moderateScale(15),
fontWeight: "800",
color: Colors.primaryDark,
},
patternTitleContainer: {
flex: 1,
marginLeft: moderateScale(12),
marginRight: moderateScale(8),
},
patternTitle: {
fontSize: moderateScale(15),
fontWeight: "600",
color: Colors.textPrimary,
},
});