acupedia-mobile-ui/src/features/content/renderers/shared/ObjectSections.tsx

70 lines
1.7 KiB
TypeScript

import React from "react";
import { StyleSheet, Text, View } from "react-native";
import { humanizeKey } from "../helpers/value";
import { ContentValue } from "./ContentValue";
/**
* Render arbitrary JSON objects without flattening or stringifying nested
* content references. ContentValue recursively handles arrays, objects and
* hydrated content/template references.
*/
export function ObjectSections({
value,
withTopDivider = false,
}: {
value: Record<string, unknown>;
withTopDivider?: boolean;
}) {
const entries = Object.entries(value).filter(([, child]) =>
isPresent(child),
);
if (!entries.length) return null;
return (
<View style={styles.root}>
{entries.map(([key, child], index) => (
<View
key={key}
style={[
styles.section,
(index > 0 || withTopDivider) && styles.divider,
]}
>
<Text style={styles.label}>{humanizeKey(key)}</Text>
<ContentValue value={child} />
</View>
))}
</View>
);
}
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({
root: { gap: 16 },
section: {
gap: 7,
},
divider: {
paddingTop: 12,
borderTopWidth: StyleSheet.hairlineWidth,
borderTopColor: "#E8ECEF",
},
label: {
fontWeight: "700",
fontSize: 13,
lineHeight: 18,
color: "#536F61",
letterSpacing: 0.15,
},
});