acupedia-mobile-ui/src/features/content/renderers/shared/ContentLinkAttributeSection...

83 lines
2.6 KiB
TypeScript

import React, { useMemo } from "react";
import type { AttributeDefinitionResponse } from "../../types/content.types";
import type { TemplateAttributePresentationContract } from "../../types/presentation.types";
import {
createAttributePresentationMap,
getAttributePresentationRule,
shouldRenderAttribute,
} from "../../utils/attribute-presentation";
import { getNavigableContentReferences } from "../../utils/content-reference";
import { ContentValue } from "./ContentValue";
import { SectionCard } from "./SectionCard";
interface ContentLinkAttributeSectionsProps {
data: Record<string, unknown>;
definitions?: readonly AttributeDefinitionResponse[];
presentationAttributes?: readonly TemplateAttributePresentationContract[];
}
function containsNavigableReference(value: unknown): boolean {
if (getNavigableContentReferences(value).length > 0) return true;
if (Array.isArray(value)) return value.some(containsNavigableReference);
if (value && typeof value === "object") {
return Object.values(value as Record<string, unknown>).some(containsNavigableReference);
}
return false;
}
export function ContentLinkAttributeSections({
data,
definitions = [],
presentationAttributes = [],
}: ContentLinkAttributeSectionsProps) {
const rules = useMemo(
() => createAttributePresentationMap(presentationAttributes),
[presentationAttributes],
);
const items = useMemo(() => {
const roots = [...definitions]
.filter((definition) => definition.is_root)
.sort((a, b) => a.sort_order - b.sort_order || a.attribute_key.localeCompare(b.attribute_key));
const orderedKeys = roots.length > 0
? roots.map((definition) => definition.attribute_key)
: Object.keys(data);
const seen = new Set<string>();
const output: Array<{ key: string; label: string; value: unknown }> = [];
for (const key of orderedKeys) {
if (seen.has(key)) continue;
seen.add(key);
const value = data[key];
if (!containsNavigableReference(value)) continue;
const rule = getAttributePresentationRule(key, rules);
if (!shouldRenderAttribute(value, rule)) continue;
const definition = roots.find((item) => item.attribute_key === key);
output.push({
key,
label: definition?.label?.trim() || key.replace(/_/g, " "),
value,
});
}
return output;
}, [data, definitions, rules]);
if (!items.length) return null;
return (
<>
{items.map((item) => (
<SectionCard key={item.key} title={item.label}>
<ContentValue value={item.value} />
</SectionCard>
))}
</>
);
}