display order fix for m0001

This commit is contained in:
Amit Salunke 2026-09-28 07:48:09 +05:30
parent 76d1382143
commit 33a407cee2
18 changed files with 562 additions and 81 deletions

4
.env
View File

@ -19,7 +19,9 @@
# Production Dev
# EXPO_PUBLIC_API_URL=https://api.acupedia.in/api
# EXPO_PUBLIC_STOREFRONT_URL=https://acupedia.in/store
# EXPO_PUBLIC_CONTENT_PREVIEW_ENABLED=false
# Local Dev
EXPO_PUBLIC_API_URL=http://localhost:8000/api
EXPO_PUBLIC_STOREFRONT_URL=http://localhost:3000
EXPO_PUBLIC_CONTENT_PREVIEW_ENABLED=true

View File

@ -16,11 +16,15 @@ export class ContentPresentationApi {
});
}
searchContents(payload: ContentSearchRequest): Promise<ContentSearchResponse> {
searchContents(
payload: ContentSearchRequest,
preview = false,
): Promise<ContentSearchResponse> {
return request(this.client, {
method: "POST",
url: "/contents/search",
data: payload,
params: { preview },
});
}
}

View File

@ -25,11 +25,12 @@ export const contentPresentationQueryKeys = {
templateContract: (templateCode: string) =>
["content", "presentation", "template", templateCode, "contract"] as const,
search: (request: Omit<ContentSearchRequest, "page">) =>
search: (request: Omit<ContentSearchRequest, "page">, preview: boolean) =>
[
"content",
"presentation",
"search",
{ preview },
request.module_id ?? null,
request.module_code ?? null,
request.template_code,

View File

@ -16,56 +16,65 @@ import {
export class ContentApi {
constructor(private readonly client: AxiosInstance) {}
getModules(): Promise<ModuleListResponse> {
getModules(preview = false): Promise<ModuleListResponse> {
return request(this.client, {
method: "GET",
url: "/contents/modules",
params: { preview },
});
}
getModuleContents(payload: ModuleRequest): Promise<ModuleContentListResponse> {
getModuleContents(payload: ModuleRequest, preview = false): Promise<ModuleContentListResponse> {
return request(this.client, {
method: "POST",
url: "/contents/module-contents",
data: payload,
params: { preview },
});
}
getModuleTemplateContents(
payload: ModuleTemplateContentRequest,
preview = false,
): Promise<ModuleTemplateContentResponse> {
return request(this.client, {
method: "POST",
url: "/contents/module-template-contents",
data: payload,
params: { preview },
});
}
getModuleTemplateContentDetails(
payload: ModuleTemplateContentRequest,
preview = false,
): Promise<ModuleTemplateContentDetailResponse> {
return request(this.client, {
method: "POST",
url: "/contents/module-template-content-details",
data: payload,
params: { preview },
});
}
getContent(contentId: string): Promise<ReconstructedContentResponse> {
getContent(contentId: string, preview = false): Promise<ReconstructedContentResponse> {
return request(this.client, {
method: "GET",
url: `/contents/${encodeURIComponent(contentId)}`,
params: { preview },
});
}
getModuleContentDetail(
payload: ModuleRequest,
contentId: string,
preview = false,
): Promise<ContentDetailResponse> {
return request(this.client, {
method: "POST",
url: `/contents/module-contents/${encodeURIComponent(contentId)}`,
data: payload,
params: { preview },
});
}

View File

@ -8,17 +8,17 @@ function moduleIdentity(request: ModuleRequest): string {
export const contentQueryKeys = {
root: ["content"] as const,
modules: () => ["content", "modules"] as const,
moduleContents: (request: ModuleRequest) =>
["content", "module", moduleIdentity(request), "contents"] as const,
moduleTemplateContents: (request: ModuleRequest, templateCode: string) =>
["content", "module", moduleIdentity(request), "template", templateCode, "contents"] as const,
moduleTemplateDetails: (request: ModuleRequest, templateCode: string) =>
["content", "module", moduleIdentity(request), "template", templateCode, "details"] as const,
contentDetail: (contentId: string) =>
["content", "detail", contentId] as const,
moduleContentDetail: (request: ModuleRequest, contentId: string) =>
["content", "module", moduleIdentity(request), "content", contentId] as const,
modules: (preview: boolean) => ["content", "modules", { preview }] as const,
moduleContents: (request: ModuleRequest, preview: boolean) =>
["content", "module", moduleIdentity(request), "contents", { preview }] as const,
moduleTemplateContents: (request: ModuleRequest, templateCode: string, preview: boolean) =>
["content", "module", moduleIdentity(request), "template", templateCode, "contents", { preview }] as const,
moduleTemplateDetails: (request: ModuleRequest, templateCode: string, preview: boolean) =>
["content", "module", moduleIdentity(request), "template", templateCode, "details", { preview }] as const,
contentDetail: (contentId: string, preview: boolean) =>
["content", "detail", contentId, { preview }] as const,
moduleContentDetail: (request: ModuleRequest, contentId: string, preview: boolean) =>
["content", "module", moduleIdentity(request), "content", contentId, { preview }] as const,
templateDefinitions: (templateCode: string) =>
["content", "template", templateCode, "definitions"] as const,
};

View File

@ -0,0 +1,9 @@
import { createContext } from "react";
export interface BackActionContextType {
setCustomBackAction: (action: (() => void) | null) => void;
}
export const BackActionContext = createContext<BackActionContextType>({
setCustomBackAction: () => {},
});

View File

@ -1,6 +1,7 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { contentApi } from "../api/content.client";
import { contentQueryKeys } from "../api/content.query-keys";
import { useSettingsStore } from "@/store/settings.store";
import {
ModuleRequest,
ModuleTemplateContentRequest,
@ -10,17 +11,19 @@ const hasModuleIdentity = (request: ModuleRequest) =>
Boolean(request.module_id || request.module_code);
export function useModulesQuery() {
const preview = useSettingsStore((state) => state.contentPreviewEnabled);
return useQuery({
queryKey: contentQueryKeys.modules(),
queryFn: () => contentApi.getModules(),
queryKey: contentQueryKeys.modules(preview),
queryFn: () => contentApi.getModules(preview),
staleTime: 10 * 60 * 1000,
});
}
export function useModuleContentsQuery(request: ModuleRequest) {
const preview = useSettingsStore((state) => state.contentPreviewEnabled);
return useQuery({
queryKey: contentQueryKeys.moduleContents(request),
queryFn: () => contentApi.getModuleContents(request),
queryKey: contentQueryKeys.moduleContents(request, preview),
queryFn: () => contentApi.getModuleContents(request, preview),
enabled: hasModuleIdentity(request),
});
}
@ -28,6 +31,7 @@ export function useModuleContentsQuery(request: ModuleRequest) {
export function useModuleTemplateContentsQuery(
request: ModuleTemplateContentRequest,
) {
const preview = useSettingsStore((state) => state.contentPreviewEnabled);
const moduleRequest: ModuleRequest = {
module_id: request.module_id,
module_code: request.module_code,
@ -37,8 +41,9 @@ export function useModuleTemplateContentsQuery(
queryKey: contentQueryKeys.moduleTemplateContents(
moduleRequest,
request.template_code,
preview,
),
queryFn: () => contentApi.getModuleTemplateContents(request),
queryFn: () => contentApi.getModuleTemplateContents(request, preview),
enabled: hasModuleIdentity(moduleRequest) && Boolean(request.template_code),
});
}
@ -46,6 +51,7 @@ export function useModuleTemplateContentsQuery(
export function useModuleTemplateContentDetailsQuery(
request: ModuleTemplateContentRequest,
) {
const preview = useSettingsStore((state) => state.contentPreviewEnabled);
const moduleRequest: ModuleRequest = {
module_id: request.module_id,
module_code: request.module_code,
@ -55,19 +61,21 @@ export function useModuleTemplateContentDetailsQuery(
queryKey: contentQueryKeys.moduleTemplateDetails(
moduleRequest,
request.template_code,
preview,
),
queryFn: () => contentApi.getModuleTemplateContentDetails(request),
queryFn: () => contentApi.getModuleTemplateContentDetails(request, preview),
enabled: hasModuleIdentity(moduleRequest) && Boolean(request.template_code),
staleTime: 10 * 60 * 1000,
});
}
export function useContentQuery(contentId?: string | null) {
const preview = useSettingsStore((state) => state.contentPreviewEnabled);
const id = contentId?.trim() ?? "";
return useQuery({
queryKey: contentQueryKeys.contentDetail(id),
queryFn: () => contentApi.getContent(id),
queryKey: contentQueryKeys.contentDetail(id, preview),
queryFn: () => contentApi.getContent(id, preview),
enabled: Boolean(id),
staleTime: 15 * 60 * 1000,
});
@ -77,11 +85,12 @@ export function useModuleContentDetailQuery(
request: ModuleRequest,
contentId?: string | null,
) {
const preview = useSettingsStore((state) => state.contentPreviewEnabled);
const id = contentId?.trim() ?? "";
return useQuery({
queryKey: contentQueryKeys.moduleContentDetail(request, id),
queryFn: () => contentApi.getModuleContentDetail(request, id),
queryKey: contentQueryKeys.moduleContentDetail(request, id, preview),
queryFn: () => contentApi.getModuleContentDetail(request, id, preview),
enabled: hasModuleIdentity(request) && Boolean(id),
});
}
@ -113,9 +122,6 @@ export function usePublishContentMutation() {
onSuccess: async (_data, variables) => {
await Promise.all([
queryClient.invalidateQueries({
queryKey: contentQueryKeys.contentDetail(variables.contentId),
}),
queryClient.invalidateQueries({
queryKey: contentQueryKeys.root,
}),

View File

@ -1,4 +1,5 @@
import { useInfiniteQuery } from "@tanstack/react-query";
import { useSettingsStore } from "@/store/settings.store";
import { contentPresentationApi } from "../api/content-presentation.client";
import { contentPresentationQueryKeys } from "../api/content-presentation.query-keys";
import type { ContentSearchRequest } from "../types/presentation.types";
@ -13,23 +14,27 @@ export function useContentSearchInfiniteQuery(
request: ContentSearchInfiniteRequest,
options?: { enabled?: boolean },
) {
const preview = useSettingsStore((state) => state.contentPreviewEnabled);
const enabled =
(options?.enabled ?? true) &&
hasModuleIdentity(request) &&
Boolean(request.template_code.trim());
return useInfiniteQuery({
queryKey: contentPresentationQueryKeys.search(request),
queryKey: contentPresentationQueryKeys.search(request, preview),
initialPageParam: 1,
enabled,
queryFn: ({ pageParam, signal }) => {
// Axios 1.x cancellation is already propagated by TanStack Query only if
// your request wrapper accepts signal. The API call remains valid without it.
void signal;
return contentPresentationApi.searchContents({
...request,
page: pageParam,
});
return contentPresentationApi.searchContents(
{
...request,
page: pageParam,
},
preview,
);
},
getNextPageParam: (lastPage) => {
const loadedThrough = lastPage.page * lastPage.page_size;

View File

@ -1,7 +1,204 @@
import React from "react";
import { ScrollView, Text } from "react-native";
import { ScrollView, StyleSheet, Text, View } from "react-native";
import type { DetailRendererProps } from "../../types/renderer.types";
import { ContentLinkAttributeSections } from "../shared/ContentLinkAttributeSections";
import {
findAttributePresentationRule,
isEmptyValue,
presentationDisplayOrder,
} from "../../utils/attribute-presentation";
import { asRecordArray, asString, asStringArray } from "../helpers/value";
import { Hero } from "../shared/Hero"; import { SectionCard } from "../shared/SectionCard"; import { ChipList } from "../shared/ChipList"; import { BulletList } from "../shared/BulletList"; import { KeyValueGrid } from "../shared/KeyValueGrid"; import { ImageGallery } from "../shared/ImageGallery";
export function EovDetailRenderer({content,data,definitions,presentationAttributes}:DetailRendererProps){ return <ScrollView contentContainerStyle={{paddingHorizontal:18,paddingTop:16,paddingBottom:40,gap:14}}><Hero title={asString(data.name)||content.title} subtitle={asStringArray(data.alt_name).join(" · ")}/><ImageGallery images={asRecordArray(data.images)}/><SectionCard title="Point Relationships"><KeyValueGrid rows={[{label:"Master Point",value:asString(data.master_point)},{label:"Coupled Point",value:asString(data.coupled_point)},{label:"Luo Point",value:asString(data.luo_point)},{label:"Xi-Cleft Point",value:asString(data.xi_cleft_point)},{label:"Paired Meridian",value:asString(data.paired_meridian)}]}/><ChipList items={asStringArray(data.intersection_points)}/></SectionCard><SectionCard title="Areas of Effect"><ChipList items={asStringArray(data.areas_of_effect)}/></SectionCard><SectionCard title="Functions"><BulletList items={asStringArray(data.functions)}/></SectionCard><SectionCard title="Pathway"><Text style={{fontSize:16,lineHeight:26,color:"#334155"}}>{asString(data.pathway)}</Text></SectionCard><ContentLinkAttributeSections data={data} definitions={definitions} presentationAttributes={presentationAttributes}/></ScrollView>; }
import { BulletList } from "../shared/BulletList";
import { ChipList } from "../shared/ChipList";
import { ContentLinkAttributeSections } from "../shared/ContentLinkAttributeSections";
import { ContentValue } from "../shared/ContentValue";
import { Hero } from "../shared/Hero";
import { ImageGallery } from "../shared/ImageGallery";
import { ReferenceChipList } from "../shared/ReferenceChipList";
import { SectionCard } from "../shared/SectionCard";
const POINT_RELATIONSHIP_KEYS = [
"master_point",
"coupled_point",
"luo_point",
"xi_cleft_point",
"intersection_points",
"paired_meridian",
] as const;
interface RelationshipRowProps {
label: string;
value: unknown;
chips?: boolean;
}
function RelationshipRow({ label, value, chips = false }: RelationshipRowProps) {
if (isEmptyValue(value)) return null;
return (
<View style={styles.relationshipRow}>
<Text style={styles.relationshipLabel}>{label}</Text>
{chips ? <ReferenceChipList value={value} /> : <ContentValue value={value} />}
</View>
);
}
export function EovDetailRenderer({
content,
data,
definitions,
presentationAttributes,
}: DetailRendererProps) {
const definitionByKey = React.useMemo(() => {
const map = new Map<string, (typeof definitions)[number]>();
for (const definition of definitions) {
map.set(definition.attribute_key, definition);
map.set(definition.code, definition);
}
return map;
}, [definitions]);
const orderFor = React.useCallback(
(key: string, fallbackIndex = 0) => {
const rule = findAttributePresentationRule(key, presentationAttributes);
const definition = definitionByKey.get(key);
return presentationDisplayOrder(rule, definition?.sort_order, fallbackIndex);
},
[definitionByKey, presentationAttributes],
);
const relationshipRows = React.useMemo(
() => [
{ key: "master_point", label: "Master Point", value: data.master_point },
{ key: "coupled_point", label: "Coupled Point", value: data.coupled_point },
{ key: "luo_point", label: "Luo Point", value: data.luo_point },
{ key: "xi_cleft_point", label: "Xi-Cleft Point", value: data.xi_cleft_point },
{
key: "intersection_points",
label: "Intersection Points",
value: data.intersection_points,
chips: true,
},
{ key: "paired_meridian", label: "Paired Meridian", value: data.paired_meridian },
]
.filter((row) => !isEmptyValue(row.value))
.sort((a, b) => orderFor(a.key) - orderFor(b.key)),
[data, orderFor],
);
const sections = React.useMemo(() => {
const items: Array<{
key: string;
order: number;
render: () => React.ReactNode;
}> = [];
if (relationshipRows.length > 0) {
items.push({
key: "point_relationships",
order: Math.min(...relationshipRows.map((row) => orderFor(row.key))),
render: () => (
<SectionCard title="Point Relationships">
{relationshipRows.map((row) => (
<RelationshipRow
key={row.key}
label={row.label}
value={row.value}
chips={row.chips}
/>
))}
</SectionCard>
),
});
}
if (!isEmptyValue(data.areas_of_effect)) {
items.push({
key: "areas_of_effect",
order: orderFor("areas_of_effect", 100),
render: () => (
<SectionCard title="Areas of Effect">
<ChipList items={asStringArray(data.areas_of_effect)} />
</SectionCard>
),
});
}
if (!isEmptyValue(data.functions)) {
items.push({
key: "functions",
order: orderFor("functions", 110),
render: () => (
<SectionCard title="Functions">
<BulletList items={asStringArray(data.functions)} />
</SectionCard>
),
});
}
if (!isEmptyValue(data.pathway)) {
items.push({
key: "pathway",
order: orderFor("pathway", 120),
render: () => (
<SectionCard title="Pathway">
<Text style={styles.pathway}>{asString(data.pathway)}</Text>
</SectionCard>
),
});
}
return items.sort((a, b) => a.order - b.order || a.key.localeCompare(b.key));
}, [data, orderFor, relationshipRows]);
return (
<ScrollView
contentContainerStyle={{
paddingHorizontal: 18,
paddingTop: 16,
paddingBottom: 40,
gap: 14,
}}
>
<Hero
title={asString(data.name) || content.title}
subtitle={asStringArray(data.alt_name).join(" · ")}
/>
<ImageGallery images={asRecordArray(data.images)} />
{sections.map((section) => (
<React.Fragment key={section.key}>{section.render()}</React.Fragment>
))}
<ContentLinkAttributeSections
data={data}
definitions={definitions}
presentationAttributes={presentationAttributes}
excludeAttributeKeys={POINT_RELATIONSHIP_KEYS}
/>
</ScrollView>
);
}
const styles = StyleSheet.create({
relationshipRow: {
gap: 5,
paddingBottom: 10,
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: "#E8ECEF",
},
relationshipLabel: {
fontSize: 12,
lineHeight: 17,
fontWeight: "700",
color: "#597064",
textTransform: "uppercase",
letterSpacing: 0.4,
},
pathway: {
fontSize: 16,
lineHeight: 26,
color: "#334155",
},
});

View File

@ -1,5 +1,5 @@
import React from "react";
import { ScrollView } from "react-native";
import React, { useMemo } from "react";
import { ScrollView, StyleSheet, Text, View } from "react-native";
import type { DetailRendererProps } from "../../types/renderer.types";
import { asRecord, asString, asStringArray } from "../helpers/value";
@ -11,12 +11,45 @@ import { SectionCard } from "../shared/SectionCard";
import { BulletList } from "../shared/BulletList";
import { ObjectSections } from "../shared/ObjectSections";
const GROUPED_POINT_ATTRIBUTE_KEYS = [
"meeting_points",
"point_categories",
"specific_points_according_to_functions",
"five_shu_transporting_points",
] as const;
const RENDERED_REFERENCE_ATTRIBUTE_KEYS = [
...GROUPED_POINT_ATTRIBUTE_KEYS,
"luo_connecting_vessel",
"link",
] as const;
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);
return (
<ScrollView
contentContainerStyle={{
@ -54,31 +87,121 @@ export function MeridianDetailRenderer({
<ObjectSections value={asRecord(data.symptoms)} />
</SectionCard>
<SectionCard title="Meeting Points">
<ContentValue value={data.meeting_points} />
</SectionCard>
<SectionCard title="Point Categories">
<ObjectSections value={asRecord(data.point_categories)} />
</SectionCard>
{hasMeridianPoints ? (
<SectionCard title="Meridian Points">
<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>
</SectionCard>
) : null}
<SectionCard title="Clinical Manifestations">
<BulletList items={asStringArray(data.indications_clinical_manifestations)} />
</SectionCard>
<SectionCard title="Specific Points">
<ObjectSections value={asRecord(data.specific_points_according_to_functions)} />
</SectionCard>
<SectionCard title="Five-Shu Transporting Points">
<ObjectSections value={asRecord(data.five_shu_transporting_points)} />
</SectionCard>
<ContentLinkAttributeSections
data={data}
definitions={definitions}
presentationAttributes={presentationAttributes}
excludeAttributeKeys={RENDERED_REFERENCE_ATTRIBUTE_KEYS}
/>
</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,
},
});

View File

@ -5,7 +5,7 @@ import { moderateScale, verticalScale } from "react-native-size-matters";
import { Colors } from "@/theme";
import type { DetailRendererProps } from "../../types/renderer.types";
import { BackActionContext } from "../../screens/SingleTemplateScreen";
import { BackActionContext } from "../../context/BackActionContext";
import { ContentLinkAttributeSections } from "../shared/ContentLinkAttributeSections";
import { Hero } from "../shared/Hero";
import { SectionCard } from "../shared/SectionCard";

View File

@ -5,7 +5,7 @@ import { moderateScale, verticalScale } from "react-native-size-matters";
import { Colors } from "@/theme";
import type { DetailRendererProps } from "../../types/renderer.types";
import { BackActionContext } from "../../screens/SingleTemplateScreen";
import { BackActionContext } from "../../context/BackActionContext";
import { Hero } from "../shared/Hero";
import { SectionCard } from "../shared/SectionCard";
import { Paragraphs } from "../shared/Paragraphs";

View File

@ -5,7 +5,7 @@ import { moderateScale, verticalScale } from "react-native-size-matters";
import { Colors } from "@/theme";
import type { DetailRendererProps } from "../../types/renderer.types";
import { BackActionContext } from "../../screens/SingleTemplateScreen";
import { BackActionContext } from "../../context/BackActionContext";
import { Hero } from "../shared/Hero";
import { SectionCard } from "../shared/SectionCard";
import { Paragraphs } from "../shared/Paragraphs";

View File

@ -6,6 +6,7 @@ import {
bareAttributeKey,
createAttributePresentationMap,
getAttributePresentationRule,
presentationDisplayOrder,
shouldRenderAttribute,
} from "../../utils/attribute-presentation";
import { getNavigableContentReferences } from "../../utils/content-reference";
@ -16,6 +17,7 @@ interface ContentLinkAttributeSectionsProps {
data: Record<string, unknown>;
definitions?: readonly AttributeDefinitionResponse[];
presentationAttributes?: readonly TemplateAttributePresentationContract[];
excludeAttributeKeys?: readonly string[];
}
function containsNavigableReference(value: unknown): boolean {
@ -31,12 +33,18 @@ export function ContentLinkAttributeSections({
data,
definitions = [],
presentationAttributes = [],
excludeAttributeKeys = [],
}: ContentLinkAttributeSectionsProps) {
const rules = useMemo(
() => createAttributePresentationMap(presentationAttributes),
[presentationAttributes],
);
const excluded = useMemo(
() => new Set(excludeAttributeKeys.map((key) => bareAttributeKey(key))),
[excludeAttributeKeys],
);
const items = useMemo(() => {
const roots = [...definitions]
.filter((definition) => definition.is_root)
@ -47,13 +55,19 @@ export function ContentLinkAttributeSections({
: Object.keys(data);
const seen = new Set<string>();
const output: Array<{ key: string; label: string; value: unknown }> = [];
const output: Array<{
key: string;
label: string;
value: unknown;
order: number;
}> = [];
for (const key of orderedKeys) {
if (seen.has(key)) continue;
seen.add(key);
const definition = roots.find((item) => item.attribute_key === key);
const dataKey = definition?.code || bareAttributeKey(key);
if (excluded.has(bareAttributeKey(key)) || excluded.has(dataKey)) continue;
const value = data[dataKey] !== undefined ? data[dataKey] : data[key];
if (!containsNavigableReference(value)) continue;
@ -64,11 +78,18 @@ export function ContentLinkAttributeSections({
key,
label: definition?.label?.trim() || dataKey.replace(/_/g, " "),
value,
order: presentationDisplayOrder(
rule,
definition?.sort_order,
output.length,
),
});
}
return output;
}, [data, definitions, rules]);
return output.sort(
(a, b) => a.order - b.order || a.key.localeCompare(b.key),
);
}, [data, definitions, excluded, rules]);
if (!items.length) return null;

View File

@ -1,4 +1,4 @@
import React, { createContext, useMemo, useState } from "react";
import React, { useMemo, useState } from "react";
import { ContentMediaProvider } from "../media/ContentMediaContext";
import { ScreenEmpty, ScreenError, ScreenLoading } from "../components/ContentScreenState";
import { useSingleTemplateContentQuery } from "../hooks/use-single-template-content-query";
@ -8,14 +8,7 @@ import { RendererFallbackBoundary } from "../renderers/shared/RendererFallbackBo
import { DetailPageShell } from "../renderers/shared/DetailPageShell";
import { applyPresentationContractToData } from "../utils/attribute-presentation";
import type { TemplateContractResponse } from "../types/presentation.types";
export interface BackActionContextType {
setCustomBackAction: (action: (() => void) | null) => void;
}
export const BackActionContext = createContext<BackActionContextType>({
setCustomBackAction: () => {},
});
import { BackActionContext } from "../context/BackActionContext";
export function SingleTemplateScreen({
moduleCode,

View File

@ -14,6 +14,7 @@ import { moderateScale, verticalScale } from "react-native-size-matters";
import { Colors } from "@/theme";
import { useAuthStore } from "@/store/auth.store";
import { useSettingsStore } from "@/store/settings.store";
import { useModulesQuery } from "@/features/content/hooks/use-content-queries";
import { buildContentReferenceRoute } from "@/features/content/utils/content-reference";
import { isModuleUnlockedByAccess } from "@/features/access/module-access";
@ -27,11 +28,29 @@ export default function ModulesIndexScreen() {
const {
access,
accessToken,
user,
refreshAccess,
setModules,
setLastViewedModule,
} = useAuthStore();
const preview = useSettingsStore((state) => state.contentPreviewEnabled);
const previewFeatureEnabled =
process.env.EXPO_PUBLIC_CONTENT_PREVIEW_ENABLED === "true";
const setContentPreviewEnabled = useSettingsStore(
(state) => state.setContentPreviewEnabled,
);
const isPreviewAdmin = Boolean(
previewFeatureEnabled &&
user?.roles?.some((role) => role === "admin" || role === "super_admin"),
);
useEffect(() => {
if (!isPreviewAdmin && preview) {
setContentPreviewEnabled(false);
}
}, [isPreviewAdmin, preview, setContentPreviewEnabled]);
const modulesQuery = useModulesQuery();
const modules = useMemo(
() => normalizeModuleListResponse(modulesQuery.data),
@ -75,9 +94,10 @@ export default function ModulesIndexScreen() {
const isUnlocked = useCallback(
(item: ModuleIndexItem) => {
if (!accessToken) return false;
if (isPreviewAdmin && preview) return true;
return isModuleUnlockedByAccess(item.module, access);
},
[access, accessToken],
[access, accessToken, isPreviewAdmin, preview],
);
const handleModulePress = useCallback(
@ -132,14 +152,35 @@ export default function ModulesIndexScreen() {
<Ionicons name="chevron-back" size={24} color={Colors.textPrimary} />
</TouchableOpacity>
<Text style={styles.headerTitle}>All Modules</Text>
<TouchableOpacity
onPress={() => router.push("/search")}
style={styles.searchButton}
accessibilityRole="button"
accessibilityLabel="Search all content"
>
<Ionicons name="search" size={22} color={Colors.primaryDark} />
</TouchableOpacity>
<View style={styles.headerActions}>
{isPreviewAdmin ? (
<TouchableOpacity
onPress={() => setContentPreviewEnabled(!preview)}
style={[
styles.previewButton,
preview && styles.previewButtonActive,
]}
accessibilityRole="button"
accessibilityLabel={
preview ? "Disable content preview" : "Enable content preview"
}
>
<Ionicons
name={preview ? "eye" : "eye-outline"}
size={21}
color={preview ? "#FFFFFF" : Colors.primaryDark}
/>
</TouchableOpacity>
) : null}
<TouchableOpacity
onPress={() => router.push("/search")}
style={styles.searchButton}
accessibilityRole="button"
accessibilityLabel="Search all content"
>
<Ionicons name="search" size={22} color={Colors.primaryDark} />
</TouchableOpacity>
</View>
</View>
<ScrollView
@ -150,6 +191,15 @@ export default function ModulesIndexScreen() {
Explore all modules. Unlock to access complete content.
</Text>
{preview && isPreviewAdmin ? (
<View style={styles.previewBanner}>
<Ionicons name="eye" size={16} color={Colors.primaryDark} />
<Text style={styles.previewBannerText}>
Draft content preview is enabled.
</Text>
</View>
) : null}
{modulesQuery.isError ? (
<View style={styles.errorCard}>
<Ionicons
@ -197,7 +247,14 @@ export default function ModulesIndexScreen() {
</View>
<View style={styles.textContainer}>
<Text style={styles.moduleTitle}>{item.title}</Text>
<View style={styles.moduleTitleRow}>
<Text style={styles.moduleTitle}>{item.title}</Text>
{preview && item.module.status === "draft" ? (
<View style={styles.draftBadge}>
<Text style={styles.draftBadgeText}>Draft</Text>
</View>
) : null}
</View>
<Text style={styles.moduleDesc} numberOfLines={1}>
{item.description}
</Text>
@ -274,6 +331,22 @@ const styles = StyleSheet.create({
fontWeight: "700",
color: Colors.textPrimary,
},
headerActions: {
flexDirection: "row",
alignItems: "center",
gap: 8,
},
previewButton: {
width: 32,
height: 32,
borderRadius: 16,
alignItems: "center",
justifyContent: "center",
backgroundColor: "#EEF2FF",
},
previewButtonActive: {
backgroundColor: Colors.primary,
},
searchButton: {
width: 32,
height: 32,
@ -292,6 +365,22 @@ const styles = StyleSheet.create({
marginBottom: verticalScale(24),
lineHeight: 20,
},
previewBanner: {
flexDirection: "row",
alignItems: "center",
gap: 8,
marginTop: -12,
marginBottom: verticalScale(18),
paddingHorizontal: moderateScale(12),
paddingVertical: verticalScale(8),
borderRadius: moderateScale(10),
backgroundColor: "#EEF2FF",
},
previewBannerText: {
color: Colors.primaryDark,
fontSize: moderateScale(12),
fontWeight: "600",
},
card: {
backgroundColor: "#FFFFFF",
borderRadius: moderateScale(16),
@ -316,12 +405,28 @@ const styles = StyleSheet.create({
marginLeft: moderateScale(12),
marginRight: moderateScale(12),
},
moduleTitleRow: {
flexDirection: "row",
alignItems: "center",
gap: 8,
},
moduleTitle: {
fontSize: moderateScale(15),
fontWeight: "600",
color: Colors.textPrimary,
marginBottom: 2,
},
draftBadge: {
paddingHorizontal: moderateScale(7),
paddingVertical: 2,
borderRadius: moderateScale(8),
backgroundColor: "#FEF3C7",
},
draftBadgeText: {
fontSize: moderateScale(10),
fontWeight: "700",
color: "#92400E",
},
moduleDesc: {
fontSize: moderateScale(12),
color: Colors.textSecondary,

View File

@ -4,13 +4,18 @@ import { SettingsState } from "./types";
interface SettingsStore extends SettingsState {
setTheme: (theme: "light" | "dark") => void;
setContentPreviewEnabled: (enabled: boolean) => void;
}
export const useSettingsStore = create<SettingsStore>((set) => ({
theme: "light",
contentPreviewEnabled: false,
setTheme: (theme) =>
set({
theme,
}),
setContentPreviewEnabled: (contentPreviewEnabled) =>
set({ contentPreviewEnabled }),
}));

View File

@ -110,4 +110,5 @@ export interface AppState {
export interface SettingsState {
theme: "light" | "dark";
contentPreviewEnabled: boolean;
}