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

285 lines
8.9 KiB
TypeScript

import React, { useMemo } from "react";
import { ScrollView, StyleSheet, Text, View } from "react-native";
import type { DetailRendererProps } from "../../types/renderer.types";
import {
bareAttributeKey,
findAttributePresentationRule,
getEmptyDisplayText,
presentationDisplayOrder,
shouldRenderAttribute,
} from "../../utils/attribute-presentation";
import { asRecord, asString, asStringArray, humanizeKey } from "../helpers/value";
import { BulletList } from "../shared/BulletList";
import { ContentValue } from "../shared/ContentValue";
import { Hero } from "../shared/Hero";
import { ImageGallery } from "../shared/ImageGallery";
import { ObjectSections } from "../shared/ObjectSections";
import { SectionCard } from "../shared/SectionCard";
const RESERVED_KEYS = new Set([
"name",
"title",
"code",
"sort_order",
"link",
"images",
"luo_connecting_vessel",
"point_categories",
"specific_points_according_to_functions",
"five_shu_transporting_points",
]);
export function MeridianDetailRenderer({
content,
data,
definitions,
presentationAttributes,
}: DetailRendererProps) {
const pointCategories = asRecord(data.point_categories);
const specificPoints = asRecord(data.specific_points_according_to_functions);
const topLevelFiveShu = asRecord(data.five_shu_transporting_points);
const mergedSpecificPoints = useMemo(
() => removeExactRelationshipDuplicates(specificPoints, pointCategories),
[pointCategories, specificPoints],
);
const mergedFiveShu = useMemo(() => {
const nestedFiveShu = asRecord(pointCategories.five_shu_transporting_points);
return removeExactRelationshipDuplicates(topLevelFiveShu, nestedFiveShu);
}, [pointCategories, topLevelFiveShu]);
const hasMeridianPoints =
isPresent(data.meeting_points) ||
isPresent(pointCategories) ||
isPresent(mergedSpecificPoints) ||
isPresent(mergedFiveShu);
const orderedAttributes = useMemo(() => {
const rootDefinitions = definitions.filter((definition) => definition.is_root);
const definitionByBareKey = new Map(
rootDefinitions.map((definition) => [
definition.code || bareAttributeKey(definition.attribute_key),
definition,
]),
);
const contractIndex = new Map(
presentationAttributes.map((rule, index) => [rule.attribute_key, index]),
);
const keys: string[] = [];
const seen = new Set<string>();
for (const definition of rootDefinitions) {
const key = definition.code || bareAttributeKey(definition.attribute_key);
if (!key || seen.has(key)) continue;
seen.add(key);
keys.push(key);
}
// Backward-compatible fallback when definitions are incomplete: add only
// contract attributes that correspond to reconstructed root data keys.
for (const rule of presentationAttributes) {
const key = bareAttributeKey(rule.attribute_key);
if (!key || seen.has(key) || !Object.prototype.hasOwnProperty.call(data, key)) continue;
seen.add(key);
keys.push(key);
}
return keys
.flatMap((key) => {
if (RESERVED_KEYS.has(key)) return [];
const value = data[key];
const isMeetingPointsKey = key === "meeting_points";
// For meeting_points (Meridian Points), check if any point grouping exists
if (isMeetingPointsKey && !hasMeridianPoints) return [];
const definition = definitionByBareKey.get(key);
const rule = findAttributePresentationRule(
definition?.attribute_key ?? key,
presentationAttributes,
);
// If it's meeting_points and we have meridian points, ensure it's not discarded as empty
const effectiveValue =
isMeetingPointsKey && hasMeridianPoints
? isPresent(value)
? value
: ["__meridian_points__"]
: value;
if (!shouldRenderAttribute(effectiveValue, rule)) return [];
const label =
isMeetingPointsKey
? "Meridian Points"
: key === "indications_clinical_manifestations"
? "Clinical Manifestations"
: definition?.label?.trim() || humanizeKey(key);
const emptyText = getEmptyDisplayText(effectiveValue, rule);
const index = rule ? contractIndex.get(rule.attribute_key) ?? 0 : 0;
const order = presentationDisplayOrder(rule, definition?.sort_order, index);
return [{ key, label, value, emptyText, order }];
})
.sort((a, b) => a.order - b.order || a.label.localeCompare(b.label));
}, [data, definitions, hasMeridianPoints, presentationAttributes]);
const renderAttributeValue = (key: string, value: unknown, emptyText: string | null) => {
if (key === "meeting_points") {
return (
<View style={styles.groupStack}>
<PointGroup label="Meeting Points" value={data.meeting_points} />
<PointGroup label="Point Categories" value={pointCategories} />
<PointGroup label="Specific Points" value={mergedSpecificPoints} />
<PointGroup label="Five-Shu Transporting Points" value={mergedFiveShu} />
</View>
);
}
if (key === "luo_connecting_channel") {
return (
<>
<BulletList items={asStringArray(value)} />
{isPresent(data.luo_connecting_vessel) ? (
<ObjectSections
value={asRecord(data.luo_connecting_vessel)}
withTopDivider
/>
) : null}
</>
);
}
if (Array.isArray(value) && value.every((item) => typeof item === "string")) {
return <BulletList items={asStringArray(value)} />;
}
if (value !== null && typeof value === "object" && !Array.isArray(value)) {
return <ObjectSections value={asRecord(value)} />;
}
// Specialized-field fallback: any unexpected runtime shape is still
// rendered through the generic reference-aware value renderer.
return <ContentValue value={value} emptyText={emptyText ?? undefined} />;
};
return (
<ScrollView
contentContainerStyle={{
paddingHorizontal: 18,
paddingTop: 16,
paddingBottom: 40,
gap: 14,
}}
showsVerticalScrollIndicator={false}
>
<Hero title={asString(data.title) || content.title} subtitle={asString(data.name)} />
<ImageGallery images={[]} />
{orderedAttributes.map((attribute) => (
<SectionCard key={attribute.key} title={attribute.label}>
{renderAttributeValue(attribute.key, attribute.value, attribute.emptyText)}
</SectionCard>
))}
</ScrollView>
);
}
function PointGroup({ label, value }: { label: string; value: unknown }) {
if (!isPresent(value)) return null;
return (
<View style={styles.group}>
<Text style={styles.groupLabel}>{label}</Text>
<ContentValue value={value} />
</View>
);
}
function removeExactRelationshipDuplicates(
source: Record<string, unknown>,
canonical: Record<string, unknown>,
): Record<string, unknown> {
const output: Record<string, unknown> = {};
for (const [key, value] of Object.entries(source)) {
if (!isPresent(value)) continue;
const canonicalValue = canonical[key];
if (isPresent(canonicalValue) && sameRelationshipValue(value, canonicalValue)) {
continue;
}
output[key] = value;
}
return output;
}
function sameRelationshipValue(a: unknown, b: unknown): boolean {
return stableRelationshipValue(a) === stableRelationshipValue(b);
}
function stableRelationshipValue(value: unknown): string {
if (Array.isArray(value)) {
return JSON.stringify(value.map(stableRelationshipValue));
}
if (value && typeof value === "object") {
const record = value as Record<string, unknown>;
const target = asRecord(record.target);
const contentId = asString(target.content_id);
const sourceKey = asString(target.source_key);
const sourceCode = asString(target.source_code);
const moduleCode = asString(target.module_code);
const templateCode = asString(target.template_code);
if (asString(record.type) === "content_ref") {
return [
"content_ref",
moduleCode,
templateCode,
contentId || sourceKey || sourceCode,
].join(":");
}
const entries = Object.entries(record)
.filter(([, child]) => isPresent(child))
.sort(([aKey], [bKey]) => aKey.localeCompare(bKey))
.map(([key, child]) => [key, stableRelationshipValue(child)]);
return JSON.stringify(entries);
}
return JSON.stringify(value);
}
function isPresent(value: unknown): boolean {
if (value === null || value === undefined || value === "") return false;
if (Array.isArray(value)) return value.some(isPresent);
if (typeof value === "object") {
return Object.values(value as Record<string, unknown>).some(isPresent);
}
return true;
}
const styles = StyleSheet.create({
groupStack: {
gap: 18,
},
group: {
gap: 8,
},
groupLabel: {
fontSize: 13,
lineHeight: 18,
fontWeight: "700",
color: "#536F61",
textTransform: "uppercase",
letterSpacing: 0.35,
},
});