import type { TemplateAttributePresentationContract, TemplatePresentationContract, } from "../types/presentation.types"; /** * Default required by the backend/frontend presentation contract. * A missing rule must never make an empty attribute visible implicitly. */ export const DEFAULT_EMPTY_BEHAVIOR = "hide" as const; export const DEFAULT_ATTRIBUTE_VISIBILITY = "show" as const; export type AttributePresentationMap = ReadonlyMap< string, TemplateAttributePresentationContract >; /** Returns the data-facing key from a canonical contract key. */ export function bareAttributeKey(attributeKey: string): string { const normalized = attributeKey.trim(); const index = normalized.lastIndexOf("."); return index >= 0 ? normalized.slice(index + 1) : normalized; } /** * Resolves a presentation rule for either a canonical key * (`M0001_CT0003.location`) or the reconstructed API key (`location`). */ export function findAttributePresentationRule( attributeKey: string, rules: readonly TemplateAttributePresentationContract[] | null | undefined, ): TemplateAttributePresentationContract | undefined { const normalized = attributeKey.trim(); if (!normalized) return undefined; const bare = bareAttributeKey(normalized); return (rules ?? []).find((rule) => { const ruleKey = rule.attribute_key.trim(); return ruleKey === normalized || bareAttributeKey(ruleKey) === bare; }); } export function presentationDisplayOrder( rule: TemplateAttributePresentationContract | null | undefined, definitionSortOrder?: number | null, contractIndex?: number, ): number { if (typeof rule?.display_order === "number" && Number.isFinite(rule.display_order)) { return rule.display_order; } if (typeof definitionSortOrder === "number" && Number.isFinite(definitionSortOrder)) { return definitionSortOrder; } return 1_000_000 + (contractIndex ?? 0); } function isPlainObject(value: unknown): value is Record { if (value === null || typeof value !== "object") { return false; } const prototype = Object.getPrototypeOf(value); return prototype === Object.prototype || prototype === null; } /** * Determines whether a content value is semantically empty for presentation. * * Empty: * - null / undefined * - empty or whitespace-only strings * - arrays whose elements are all empty * - plain objects whose values are all empty * * Not empty: * - 0 * - false * - non-empty strings * - numbers, including NaN/Infinity if they reached the presentation layer * - non-plain objects (they are treated as concrete values) */ export function isEmptyValue(value: unknown): boolean { if (value === null || value === undefined) { return true; } if (typeof value === "string") { return value.trim().length === 0; } if (Array.isArray(value)) { return value.length === 0 || value.every(isEmptyValue); } if (isPlainObject(value)) { const values = Object.values(value); return values.length === 0 || values.every(isEmptyValue); } return false; } /** * Builds an immutable, O(1)-lookup index for a template contract's attribute * presentation rules. Duplicate keys indicate a broken backend contract and * are rejected rather than silently allowing the last value to win. */ export function createAttributePresentationMap( attributes: readonly TemplateAttributePresentationContract[] | null | undefined, ): AttributePresentationMap { const map = new Map(); for (const rule of attributes ?? []) { const key = rule.attribute_key.trim(); if (!key) { throw new Error("Attribute presentation rule contains a blank attribute_key."); } if (map.has(key)) { throw new Error(`Duplicate attribute presentation rule: ${key}`); } map.set(key, rule); } return map; } /** Convenience overload for callers holding the complete presentation contract. */ export function createPresentationAttributeMap( presentation: | Pick | null | undefined, ): AttributePresentationMap { return createAttributePresentationMap(presentation?.attributes); } /** * Returns the effective presentation rule for a canonical attribute key. * * The backend normally sends an effective rule for every active definition. * The fallback remains `hide` defensively for older/cached contracts. */ export function getAttributePresentationRule( attributeKey: string, rules: AttributePresentationMap | readonly TemplateAttributePresentationContract[] | null | undefined, ): TemplateAttributePresentationContract { const normalizedKey = attributeKey.trim(); if (!normalizedKey) { throw new Error("attributeKey is required."); } const rule = rules instanceof Map ? rules.get(normalizedKey) ?? Array.from(rules.values()).find( (item) => bareAttributeKey(item.attribute_key) === bareAttributeKey(normalizedKey), ) : findAttributePresentationRule(normalizedKey, rules); return rule ?? { attribute_key: normalizedKey, visibility: DEFAULT_ATTRIBUTE_VISIBILITY, empty_behavior: DEFAULT_EMPTY_BEHAVIOR, empty_text: null, }; } /** * Determines whether an attribute should be rendered. * Non-empty values always render. Empty values render only when explicitly * configured with `empty_behavior: "show"`. */ export function shouldRenderAttribute( value: unknown, rule?: Pick | null, ): boolean { if (rule?.visibility === "hide") return false; if (!isEmptyValue(value)) return true; return rule?.empty_behavior === "show"; } /** * Returns display text for an empty value when the rule explicitly permits * rendering it. A null result means no placeholder text should be displayed. * * This helper intentionally returns null for non-empty values: formatting real * values is the semantic renderer's responsibility. */ export function getEmptyDisplayText( value: unknown, rule?: Pick< TemplateAttributePresentationContract, "empty_behavior" | "empty_text" > | null, ): string | null { if (!isEmptyValue(value) || rule?.empty_behavior !== "show") { return null; } const text = rule.empty_text?.trim(); return text ? text : null; } /** * Applies the effective presentation contract before semantic renderers receive * attribute data. This keeps visibility and empty behavior consistent even for * legacy/specialized renderers that read fields directly. * * `code` is presentation-only noise in the mobile reading UI and is removed at * this boundary. Domain-specific values such as `point_code` remain available. */ export function applyPresentationContractToData( data: Record, attributes: readonly TemplateAttributePresentationContract[] | null | undefined, ): Record { const output: Record = {}; for (const [key, value] of Object.entries(data)) { if (key === "code") continue; const rule = findAttributePresentationRule(key, attributes); if (rule?.visibility === "hide") continue; if (!isEmptyValue(value)) { output[key] = value; continue; } if (rule?.empty_behavior !== "show") continue; output[key] = rule.empty_text?.trim() || "—"; } // Empty-show rules can refer to canonical keys while reconstructed data uses // bare keys. Materialize the bare key so semantic renderers can consume it. for (const rule of attributes ?? []) { const key = bareAttributeKey(rule.attribute_key); if (!key || key === "code" || Object.prototype.hasOwnProperty.call(output, key)) continue; if (rule.visibility === "hide" || rule.empty_behavior !== "show") continue; output[key] = rule.empty_text?.trim() || "—"; } return output; }