nutritionFactsLayout.ts
8.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
/**
* US Nutrition Facts 面板布局:三列(名称 / 含量 / %DV)、粗细分隔线、可选 "<" 前缀。
*/
export type NutritionDivider = 'none' | 'thin' | 'double';
export type NutritionLayoutRowDef = {
key: string;
label: string;
defaultUnit: string;
labelBold?: boolean;
indent?: boolean;
dividerAfter?: NutritionDivider;
};
/** 模板固定营养成分行(图2顺序与文案;大类 dividerAfter=double,其他=thin) */
export const NUTRITION_FACTS_LAYOUT_ROWS: readonly NutritionLayoutRowDef[] = [
{ key: 'fat', label: 'Total Fat', defaultUnit: 'g', labelBold: true, dividerAfter: 'double' },
{ key: 'transFat', label: 'Trans Fat', defaultUnit: 'g', dividerAfter: 'thin' },
{ key: 'cholesterol', label: 'Cholesterol', defaultUnit: 'mg', labelBold: true, dividerAfter: 'double' },
{ key: 'sodium', label: 'Sodium', defaultUnit: 'mg', labelBold: true, dividerAfter: 'double' },
{ key: 'carbs', label: 'Total Carbo.', defaultUnit: 'g', labelBold: true, dividerAfter: 'double' },
{ key: 'totalSugar', label: 'Sugars', defaultUnit: 'g', dividerAfter: 'thin' },
{ key: 'dietaryFiber', label: 'Dietary Fiber', defaultUnit: 'g', dividerAfter: 'thin' },
{ key: 'protein', label: 'Protein', defaultUnit: 'g', labelBold: true, dividerAfter: 'double' },
{ key: 'calcium', label: 'Calcium', defaultUnit: 'mg', dividerAfter: 'thin' },
{ key: 'potassium', label: 'Potassium', defaultUnit: 'mg', dividerAfter: 'thin' },
{ key: 'vitaminA', label: 'Vitamin A', defaultUnit: 'mg', dividerAfter: 'thin' },
{ key: 'vitaminD', label: 'Vitamin D', defaultUnit: 'mg', dividerAfter: 'thin' },
{ key: 'iron', label: 'Iron', defaultUnit: 'mg', dividerAfter: 'none' },
] as const;
/** 含量 / %DV 列固定宽度(全表共用,保证各行垂直对齐) */
export const NUTRITION_AMOUNT_COL_WIDTH = '4rem';
export const NUTRITION_PCT_COL_WIDTH = '2.75rem';
/** 图2 正文区字号(Servings ~ 底部维生素行) */
export const NUTRITION_BODY_FONT_SIZE = 12;
export const DEFAULT_NUTRITION_FOOTER_NOTE =
'* Percent Daily Values are based on a 2000 calorie diet';
export type NutritionFactsRowView = {
key: string;
label: string;
amountText: string;
dailyValueText: string;
labelBold: boolean;
indent: boolean;
dividerAfter: NutritionDivider;
};
export type NutritionFactsViewModel = {
titleFontSize: number;
servingsLabel: string;
servingsValue: string;
servingSizeLabel: string;
servingSizeValue: string;
caloriesLabel: string;
caloriesValue: string;
caloriesAmountText: string;
rows: NutritionFactsRowView[];
footerNote: string;
ingredientsText: string;
};
function cfgStr(cfg: Record<string, unknown>, keys: string[], fallback = ''): string {
for (const k of keys) {
const v = cfg[k];
if (v != null && String(v).trim() !== '') return String(v).trim();
}
return fallback;
}
function cfgBool(cfg: Record<string, unknown>, keys: string[]): boolean {
for (const k of keys) {
const v = cfg[k];
if (v === true || v === 'true' || v === 1 || v === '1') return true;
if (v === false || v === 'false' || v === 0 || v === '0') return false;
}
return false;
}
function fixedRows(cfg: Record<string, unknown>): Record<string, unknown>[] {
return Array.isArray(cfg.fixedNutrients) ? (cfg.fixedNutrients as Record<string, unknown>[]) : [];
}
function rowFromFixed(cfg: Record<string, unknown>, key: string): Record<string, unknown> | undefined {
return fixedRows(cfg).find((r) => String(r.key ?? '').trim() === key);
}
export function readNutritionLessThan(cfg: Record<string, unknown>, key: string): boolean {
const row = rowFromFixed(cfg, key);
if (row && row.lessThan != null) return cfgBool({ lessThan: row.lessThan }, ['lessThan']);
return cfgBool(cfg, [`${key}LessThan`, `${key}UseLessThan`]);
}
export function nutritionFixedField(
cfg: Record<string, unknown>,
key: string,
field: 'value' | 'unit' | 'dailyValuePercent',
): string {
const row = rowFromFixed(cfg, key);
if (field === 'dailyValuePercent') {
const fromRow = row?.dailyValuePercent ?? row?.percent ?? row?.Percent;
if (fromRow != null && String(fromRow).trim() !== '') return String(fromRow).trim();
return cfgStr(cfg, [`${key}Percent`, `${key}DailyValue`, `${key}DailyValuePercent`], '');
}
if (field === 'unit') {
const fromRow = row?.unit;
if (fromRow != null && String(fromRow).trim() !== '') return String(fromRow).trim();
const def = NUTRITION_FACTS_LAYOUT_ROWS.find((r) => r.key === key);
return cfgStr(cfg, [`${key}Unit`], def?.defaultUnit ?? '');
}
const fromRow = row?.value;
if (fromRow != null && String(fromRow).trim() !== '') return String(fromRow).trim();
return cfgStr(cfg, [key, key.charAt(0).toUpperCase() + key.slice(1)], '');
}
/** 格式化含量:仅 optional "<" 前缀;单位由录入时在 amount 中自行填写,不自动拼接 */
export function formatNutritionAmount(
value: string,
_unit?: string,
lessThan?: boolean,
): string {
const v = String(value ?? '').trim();
if (!v) return '';
const prefix = lessThan ? '<' : '';
return `${prefix}${v}`;
}
export function formatNutritionDailyValue(raw: string): string {
const v = String(raw ?? '').trim();
if (!v) return '';
return v.endsWith('%') ? v : `${v}%`;
}
function nutritionExtraRows(cfg: Record<string, unknown>): Array<{
id: string;
name: string;
value: string;
unit: string;
}> {
const raw = cfg.extraNutrients;
if (!Array.isArray(raw)) return [];
return raw.map((item, idx) => {
const row = item as Record<string, unknown>;
return {
id: String(row.id ?? `extra-${idx}`),
name: String(row.name ?? ''),
value: String(row.value ?? ''),
unit: String(row.unit ?? ''),
};
});
}
/** 从 config 构建渲染模型(Web 画布 / App canvas 共用逻辑) */
export function buildNutritionFactsViewModel(cfg: Record<string, unknown>): NutritionFactsViewModel {
const titleFontSize = Number(cfg.nutritionTitleFontSize ?? cfg.NutritionTitleFontSize ?? 16) || 16;
const servingsValue = cfgStr(cfg, ['servings', 'servingsPerContainer', 'ServingsPerContainer']);
const servingSizeValue = cfgStr(cfg, ['servingSize', 'ServingSize']);
const caloriesRaw = nutritionFixedField(cfg, 'calories', 'value') || cfgStr(cfg, ['calories', 'Calories']);
const caloriesLessThan = readNutritionLessThan(cfg, 'calories');
const layoutByKey = new Map(NUTRITION_FACTS_LAYOUT_ROWS.map((r) => [r.key, r]));
const rows: NutritionFactsRowView[] = [];
const seen = new Set<string>();
for (const def of NUTRITION_FACTS_LAYOUT_ROWS) {
seen.add(def.key);
const value = nutritionFixedField(cfg, def.key, 'value');
const lessThan = readNutritionLessThan(cfg, def.key);
const pct = nutritionFixedField(cfg, def.key, 'dailyValuePercent');
rows.push({
key: def.key,
label: String(rowFromFixed(cfg, def.key)?.label ?? def.label),
amountText: formatNutritionAmount(value, '', lessThan),
dailyValueText: formatNutritionDailyValue(pct),
labelBold: def.labelBold ?? false,
indent: def.indent ?? false,
dividerAfter: def.dividerAfter ?? 'none',
});
}
for (const ex of nutritionExtraRows(cfg)) {
const key = `extra:${ex.id}`;
if (seen.has(key)) continue;
const lessThan = cfgBool(cfg, [`extra:${ex.id}:lessThan`]);
rows.push({
key,
label: ex.name.trim() || 'Other',
amountText: formatNutritionAmount(ex.value, '', lessThan),
dailyValueText: formatNutritionDailyValue(
cfgStr(cfg, [`extra:${ex.id}:percent`, `extra:${ex.id}:dailyValuePercent`]),
),
labelBold: false,
indent: false,
dividerAfter: 'thin',
});
}
for (const fr of fixedRows(cfg)) {
const key = String(fr.key ?? '').trim();
if (!key || seen.has(key)) continue;
const def = layoutByKey.get(key);
const value = String(fr.value ?? '').trim();
const lessThan = cfgBool({ lessThan: fr.lessThan }, ['lessThan']);
rows.push({
key,
label: String(fr.label ?? def?.label ?? key),
amountText: formatNutritionAmount(value, '', lessThan),
dailyValueText: formatNutritionDailyValue(String(fr.dailyValuePercent ?? fr.percent ?? '')),
labelBold: def?.labelBold ?? false,
indent: def?.indent ?? false,
dividerAfter: def?.dividerAfter ?? 'thin',
});
}
return {
titleFontSize,
servingsLabel: cfgStr(cfg, ['servingsLabel'], 'Servings'),
servingsValue,
servingSizeLabel: cfgStr(cfg, ['servingSizeLabel'], 'Serve size'),
servingSizeValue,
caloriesLabel: cfgStr(cfg, ['caloriesLabel'], 'Calories'),
caloriesValue: caloriesRaw,
caloriesAmountText: formatNutritionAmount(caloriesRaw, '', caloriesLessThan),
rows,
footerNote: cfgStr(cfg, ['nutritionFooterNote', 'footerNote'], DEFAULT_NUTRITION_FOOTER_NOTE),
ingredientsText: cfgStr(cfg, ['ingredientsText', 'ingredients', 'IngredientsText']),
};
}