formlab-mcp 0.6.82 → 0.6.84

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -30,6 +30,7 @@ Ask Claude (or another MCP client) things like:
30
30
  |---|---|
31
31
  | `list_formulations` | Filtered list of recipes, each with exact `batchCount` / `sampleCount` / `testReportCount`; `sort` (`batches`, `samples`, `test_reports`, `name`, `updated`) ranks every match before the limit — "which formulas have the most batch runs?" in one call |
32
32
  | `get_formulation` | Full record (incl. `versionLabel`, the label the user types, e.g. 1.0) + **version history** (`versionHistory`: one snapshot per save, v1, v2…, newest first, with the label each save had and its note) + flattened wt-% composition (sub-formulas expanded), the ordered **step procedure**, user **custom fields**, any **process-factor values** (DOE inputs — cure temp, mix time, RPM, pH…), the declared **finishedDensity** (g/mL of the mixed product; volume-targeted batches scale by it), and its **theoretical parameters computed** the way the app's Params tab does (Energy kcal/100g, NV %, Cost/kg…: value, unit, formula, spec pass/fail, and a `warning` when ingredients lack a value or carry mixed units) — the app's own engine, vendored in `mcp/vendor/` and run in an isolated `node:vm` context |
33
+ | `get_nutrition_label` | The formula's **Label** tab (Pro, live workspace only): US Nutrition Facts lines per serving with FDA rounding and % Daily Value, the per-container column, whether the simplified format applies, the EU declaration (kJ / kcal, salt) and EU ingredient list with allergens in capitals, the ingredient statement with its Contains line, and which ingredients are missing nutrition data. |
33
34
  | `find_similar_formulations` | Find formulas using a given ingredient ≥ threshold % |
34
35
  | `compare_formulations` | Pairwise side-by-side composition diff |
35
36
  | `list_ingredients` | Filtered list of raw materials. Filters: `family`, `supplier`, `name_contains`, `in_stock_only`, `ingredient_class` (small-molecule / surfactant / polymer / extract / fragrance / pigment / sequence / mixture), `sequence_contains` (e.g. `KTTKS` → Matrixyl), `taxon_contains` (e.g. `Centella`) |
@@ -166,7 +167,7 @@ Or from the unpacked package:
166
167
  }
167
168
  ```
168
169
 
169
- Restart Claude Desktop. You should see a hammer icon indicating tools are available, and FormLab's 44 tools become callable in any conversation.
170
+ Restart Claude Desktop. You should see a hammer icon indicating tools are available, and FormLab's 45 tools become callable in any conversation.
170
171
 
171
172
  ## Wire it up to Claude Code
172
173
 
package/index.js CHANGED
@@ -7,7 +7,7 @@
7
7
  // FORMLAB_EXPORT=/path/to/export.json node index.js
8
8
  // formlab-mcp /path/to/export.json (when installed via npm)
9
9
  //
10
- // Exposes 44 tools (see ./tools/) over stdio. The MCP host (Claude
10
+ // Exposes 45 tools (see ./tools/) over stdio. The MCP host (Claude
11
11
  // Desktop, Claude Code, etc.) handles tool discovery, invocation
12
12
  // and response formatting. We just register handlers and stay out
13
13
  // of the way.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "formlab-mcp",
3
- "version": "0.6.82",
3
+ "version": "0.6.84",
4
4
  "mcpName": "io.github.juliu1980/formlab-mcp",
5
5
  "description": "Read-only Model Context Protocol server for FormLab. Lets Claude and other MCP clients read and analyze your FormLab data, from a local export file or your live cloud workspace.",
6
6
  "homepage": "https://formvix.com/mcp",
package/server.json CHANGED
@@ -2,13 +2,13 @@
2
2
  "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
3
3
  "name": "io.github.juliu1980/formlab-mcp",
4
4
  "description": "Read-only MCP server for FormLab formulation data: a local export file or your live cloud workspace.",
5
- "version": "0.6.82",
5
+ "version": "0.6.84",
6
6
  "websiteUrl": "https://formvix.com/mcp",
7
7
  "packages": [
8
8
  {
9
9
  "registryType": "npm",
10
10
  "identifier": "formlab-mcp",
11
- "version": "0.6.82",
11
+ "version": "0.6.84",
12
12
  "runtimeHint": "npx",
13
13
  "transport": {
14
14
  "type": "stdio"
package/theoretical.js CHANGED
@@ -16,7 +16,7 @@ import { readFileSync } from 'node:fs';
16
16
  import vm from 'node:vm';
17
17
 
18
18
  const VENDOR = new URL('./vendor/', import.meta.url);
19
- const FILES = ['safe-expr.js', 'cost.js', 'nesting.js', 'theoretical-params.js', 'reactive.js']; // reactive.js: ing.epoxy … ing.vinyl for the Reactive presets
19
+ const FILES = ['safe-expr.js', 'cost.js', 'nesting.js', 'theoretical-params.js', 'reactive.js', 'nutrition-label.js']; // reactive.js: ing.epoxy … ing.vinyl for the Reactive presets
20
20
  let _source = null;
21
21
  function source() {
22
22
  if (!_source) _source = FILES.map(f => readFileSync(new URL(f, VENDOR), 'utf8')).join('\n;\n');
@@ -45,6 +45,44 @@ const EPILOGUE = `
45
45
  });
46
46
  return JSON.stringify(out);
47
47
  }
48
+ // The Label tab's numbers (js/views/nutrition-label.js, 0.6.83; the EU ingredient list 0.6.84). The app's allergen roll-up lives in a file that is not
49
+ // vendored; this is the same walk over the flattened leaves.
50
+ // The app's HTML escaper (js/utils.js, not vendored): the EU list builds its bold version with it.
51
+ function esc(v) { return String(v == null ? '' : v).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); }
52
+ function rollupFormulaAllergens(f) {
53
+ var out = new Map();
54
+ (_flattenComposition(f).rows || []).forEach(function (r) {
55
+ if (!(r._weight > 0)) return;
56
+ var ing = (db.ingredients || []).find(function (i) { return i && i.id === r.ingredientId; });
57
+ ((ing && ing.allergens) || []).forEach(function (a) { if (!out.has(a)) out.set(a, []); });
58
+ });
59
+ return out;
60
+ }
61
+ function __nl(id) {
62
+ var f = (db.formulations || []).find(function (x) { return x && x.id === id; });
63
+ if (!f) return 'null';
64
+ var c = flNlCompute(f);
65
+ if (!c.ok) return JSON.stringify({ ok: false, why: c.why || 'nodata', needsDensity: c.needsDensity || [] });
66
+ var st = _nlSettings(f), sv = flNlServing(f), lines = flNlLines(f, c), sim = flNlSimplified(f, lines), s = flNlStatement(f);
67
+ var decl = function (ls) { return ls.map(function (l) { return { nutrient: l.label, declared: l.text + ' ' + l.unit, unrounded: +(+l.raw).toPrecision(4), percentDailyValue: l.pct == null ? null : l.pct }; }); };
68
+ var per100 = {}; FL_NL_NUTRIENTS.forEach(function (n) { per100[n.label + ' (' + n.unit + ')'] = +(+c.per100[n.key]).toPrecision(4); });
69
+ var eu = flNlEu(f, c), eus = flNlEuStatement(f);
70
+ var strip = function (h) { return String(h).replace(/<[^>]+>/g, ''); };
71
+ return JSON.stringify({
72
+ ok: true, region: st.region, format: sim.use,
73
+ serving: { amount: sv.amount, unit: sv.unit, grams: +(+sv.g).toPrecision(5), household: st.household || null, servingsPerContainer: st.servings || null,
74
+ density: sv.density, densitySource: sv.source === 'finished' ? 'finished density' : sv.source === 'ideal' ? 'estimated from the ingredients' : null, noDensity: sv.noDensity },
75
+ cookingYieldPct: c.yield || null,
76
+ per100g: per100,
77
+ nutritionFacts: decl(lines),
78
+ perContainer: sim.servings > 1 ? decl(flNlLines(f, c, sim.servings)) : null,
79
+ simplified: { eligible: sim.eligible, insignificantNutrients: sim.count, statement: sim.eligible ? strip(_nlNotSource(lines, sim)) : null },
80
+ eu: { basis: 'per ' + eu.basis, portion: eu.portion, rows: eu.rows.map(function (r) { return { nutrient: r.label, per: r.per, perPortion: r.portion }; }),
81
+ ingredientList: eus.text, allergens: eus.allergens },
82
+ ingredientStatement: s.text, contains: s.contains,
83
+ coverage: { ingredients: c.rows, withNutrition: c.withData, noData: c.noData, missing: c.missing, energyFromPartialMacros: c.partial },
84
+ });
85
+ }
48
86
  function __theo(kind, id) {
49
87
  var coll = kind === 'batch' ? db.batches : db.formulations;
50
88
  var e = (coll || []).find(function (x) { return x && x.id === id; });
@@ -110,3 +148,13 @@ export function theoreticalParams(db, kind, id) {
110
148
  return [{ name: '(theoretical parameters)', value: null, unit: '', formula: '', error: 'could not compute: ' + ((e && e.message) || e), warning: null, spec: null, pass: null, pinned: false, basis: null }];
111
149
  }
112
150
  }
151
+
152
+ // A formula's nutrition label as the app's Label tab computes it (vendor/nutrition-label.js): null when there is no such
153
+ // formula; { ok: false, why } when it has no label ('nodata', 'empty', or 'density' with the rows that need one).
154
+ export function nutritionLabel(db, id) {
155
+ try {
156
+ const ctx = contextFor(db);
157
+ vm.runInContext('var __nid = ' + JSON.stringify(String(id)) + ';', ctx);
158
+ return JSON.parse(vm.runInContext('__nl(__nid)', ctx, { timeout: 2000 }));
159
+ } catch (e) { return { ok: false, why: 'error', error: 'could not compute: ' + ((e && e.message) || e) }; }
160
+ }
@@ -7,7 +7,7 @@
7
7
  // ============================================================
8
8
 
9
9
  import { getStore, resolveById, flattenComposition } from '../data.js';
10
- import { theoreticalParams } from '../theoretical.js';
10
+ import { theoreticalParams, nutritionLabel } from '../theoretical.js';
11
11
 
12
12
  // Strip db-internal noise (createdAt, updatedAt) for cleaner LLM output
13
13
  // while keeping the human-facing fields the user cares about.
@@ -186,6 +186,39 @@ const get_formulation = {
186
186
  },
187
187
  };
188
188
 
189
+ // 0.6.83: the formula's Label tab (Pro). Jun, 15 Nov: new food features are Pro, so this reads a live workspace only
190
+ // (cloud mode is Pro); an export file gets the reason.
191
+ const get_nutrition_label = {
192
+ definition: {
193
+ name: 'get_nutrition_label',
194
+ description: 'A formulation\'s nutrition label as FormLab\'s Label tab computes it (Pro; live workspace only), from each ingredient\'s per-100 g nutrition fields × the composition (premixes rolled up, units converted). Returns: `serving` (amount in g or mL, its weight in grams, household measure, servings per container, the density used for a mL serving); `cookingYieldPct` when set (numbers are then "as sold" = as mixed ÷ yield); `per100g` unrounded; `nutritionFacts`, the US Nutrition Facts lines per serving with `declared` (FDA rounding, 21 CFR 101.9) and `percentDailyValue`; `perContainer` when servings per container is above 1 (the dual-column second column, rounded from its own total); `simplified` (whether the food qualifies for the simplified format and its "Not a significant source of…" line); `eu`, the EU nutrition declaration per 100 g or 100 ml (kJ and kcal by the EU factors, carbohydrate without fibre, salt = sodium × 2.5) with a per-portion column when a serving is typed, plus `eu.ingredientList`, the EU ingredient list (every ingredient by weight, the 14 EU allergens in CAPITALS, added in brackets where the name does not say it) and `eu.allergens`; `ingredientStatement` (by weight, 2% or less grouped) and `contains` (major US allergens); `coverage` (which ingredients have no nutrition data, which nutrients are missing on which, where calories came from partial macros). `region` / `format` are what the user chose on the tab. A blank field counts as 0: check `coverage` before calling a nutrient absent. Calculated from ingredient data, not a regulatory review.',
195
+ inputSchema: {
196
+ type: 'object',
197
+ properties: {
198
+ id: { type: 'string', description: 'Internal id or UID (FORM-001) of the formulation.' },
199
+ },
200
+ required: ['id'],
201
+ },
202
+ },
203
+ handler: async (args) => {
204
+ const { db, meta } = getStore();
205
+ if (!meta || meta.source !== 'cloud') return { error: 'The nutrition label is a FormLab Pro feature, read from a live workspace (cloud mode). This data source is an export file.' };
206
+ const f = resolveById('formulations', args.id);
207
+ if (!f) return { error: `No formulation found for id "${args.id}".` };
208
+ const r = nutritionLabel(db, f.id);
209
+ if (!r) return { error: `No formulation found for id "${args.id}".` };
210
+ const head = { id: f.id, uid: f.uid || '', name: f.name || '' };
211
+ if (!r.ok) {
212
+ const why = r.why === 'density' ? `No label yet: add a density to ${(r.needsDensity || []).slice(0, 6).join(', ') || 'the rows measured by volume'}.`
213
+ : r.why === 'empty' ? 'No label: the formulation has no ingredient amounts.'
214
+ : r.why === 'error' ? r.error : 'No label: none of its ingredients carry nutrition fields (energy, protein, fat, carb, sodium…).';
215
+ return { ...head, hasLabel: false, reason: why };
216
+ }
217
+ const { ok, ...label } = r;
218
+ return { ...head, hasLabel: true, ...label, note: 'Calculated from ingredient data. Not a regulatory review: check before printing packaging.' };
219
+ },
220
+ };
221
+
189
222
  const find_similar_formulations = {
190
223
  definition: {
191
224
  name: 'find_similar_formulations',
@@ -282,6 +315,7 @@ const compare_formulations = {
282
315
  export const tools = {
283
316
  list_formulations,
284
317
  get_formulation,
318
+ get_nutrition_label,
285
319
  find_similar_formulations,
286
320
  compare_formulations,
287
321
  };
package/vendor/README.md CHANGED
@@ -14,6 +14,7 @@ reach files outside `mcp/`):
14
14
  | `cost.js` | `js/cost.js` |
15
15
  | `nesting.js` | `js/nesting.js` |
16
16
  | `theoretical-params.js` | `js/views/theoretical-params.js` |
17
+ | `nutrition-label.js` | `js/views/nutrition-label.js` (the Label tab's numbers, `get_nutrition_label`) |
17
18
  | `equipment-calibration.js` | `js/equipment-calibration.js` (calibration due state, `mcp/calibration.js`) |
18
19
 
19
20
  Edit the source, then copy it over:
@@ -0,0 +1,667 @@
1
+ // ============================================================
2
+ // Nutrition label — a formula's US Nutrition Facts (Pro; Jun, 15 Nov, phase 3 of food labels)
3
+ // ------------------------------------------------------------
4
+ // A formula whose ingredients carry nutrition (typed, or filled by Look up in USDA) gets a Label tab: the serving,
5
+ // the Nutrition Facts panel with FDA rounding and % Daily Value (21 CFR 101.9), the ingredient statement in
6
+ // descending order by weight, and the "Contains" line from the ingredients' allergens. PNG and print.
7
+ // The numbers are the formula's composition × each ingredient's per-100 g fields, the same rows the Params tab
8
+ // reads (_tpBuildRows), so a premix rolls up and mixed units are converted. Nothing here is a substitute for a
9
+ // regulatory review; the page says so.
10
+ // The serving is saved on the shared formula as f.label = { serving, household, servings }.
11
+ // ============================================================
12
+
13
+ // key → the label line. unit = what the label declares; also = other field names; dv = Daily Value (2016 rule).
14
+ const FL_NL_NUTRIENTS = [
15
+ { key: 'energy', label: 'Calories', unit: 'kcal', also: ['calories', 'kcal'], round: 'cal' },
16
+ { key: 'fat', label: 'Total Fat', unit: 'g', also: ['total fat', 'total_fat', 'lipid'], round: 'fat', dv: 78, bold: true },
17
+ { key: 'sat_fat', label: 'Saturated Fat', unit: 'g', also: ['saturated fat', 'saturated_fat', 'satfat'], round: 'fat', dv: 20, indent: 1 },
18
+ { key: 'trans_fat', label: 'Trans Fat', unit: 'g', also: ['trans fat', 'transfat'], round: 'fat', indent: 1, italicFirst: true },
19
+ { key: 'cholesterol', label: 'Cholesterol', unit: 'mg', also: [], round: 'chol', dv: 300, bold: true },
20
+ { key: 'sodium', label: 'Sodium', unit: 'mg', also: [], round: 'sodium', dv: 2300, bold: true },
21
+ { key: 'carb', label: 'Total Carbohydrate', unit: 'g', also: ['carbs', 'carbohydrate', 'carbohydrates'], round: 'gram', dv: 275, bold: true },
22
+ { key: 'fiber', label: 'Dietary Fiber', unit: 'g', also: ['fibre', 'dietary fiber'], round: 'gram', dv: 28, indent: 1 },
23
+ { key: 'sugar', label: 'Total Sugars', unit: 'g', also: ['sugars', 'total sugars'], round: 'gram', indent: 1 },
24
+ { key: 'added_sugar', label: 'Added Sugars', unit: 'g', also: ['added sugars', 'added sugar'], round: 'gram', dv: 50, indent: 2, includes: true },
25
+ { key: 'protein', label: 'Protein', unit: 'g', also: [], round: 'gram', dvRef: 50, bold: true },
26
+ { key: 'vit_d', label: 'Vitamin D', unit: 'mcg', also: ['vitamin d', 'vitd'], round: 'tenth', dv: 20, micro: true },
27
+ { key: 'calcium', label: 'Calcium', unit: 'mg', also: [], round: 'ten', dv: 1300, micro: true },
28
+ { key: 'iron', label: 'Iron', unit: 'mg', also: [], round: 'tenth', dv: 18, micro: true },
29
+ { key: 'potassium', label: 'Potassium', unit: 'mg', also: [], round: 'ten', dv: 4700, micro: true },
30
+ ];
31
+ // The nine major US food allergens (FALCPA + FASTER Act), by the app's allergen chips.
32
+ const FL_NL_US_ALLERGENS = { milk: 'Milk', eggs: 'Eggs', fish: 'Fish', shellfish: 'Shellfish', 'tree-nuts': 'Tree Nuts', peanuts: 'Peanuts', wheat: 'Wheat', soy: 'Soy', sesame: 'Sesame' };
33
+
34
+ // ── FDA rounding (21 CFR 101.9(c)) ──────────────────────────
35
+ // Returns { n: the declared number, text: as printed, lt: true for "less than" }.
36
+ const _nlStep = (v, s) => Math.round(v / s + 1e-9) * s;
37
+ const _nlNum = (n) => String(+(+n).toFixed(1));
38
+ function flNlRound(kind, v) {
39
+ if (v == null || !Number.isFinite(v) || v < 0) v = 0;
40
+ const out = (n) => ({ n, text: _nlNum(n) });
41
+ switch (kind) {
42
+ case 'cal': return out(v < 5 ? 0 : v <= 50 ? _nlStep(v, 5) : _nlStep(v, 10));
43
+ case 'fat': return out(v < 0.5 ? 0 : v < 5 ? _nlStep(v, 0.5) : _nlStep(v, 1));
44
+ case 'chol': return v < 2 ? out(0) : v <= 5 ? { n: v, text: 'less than 5', lt: true } : out(_nlStep(v, 5));
45
+ case 'sodium': return out(v < 5 ? 0 : v <= 140 ? _nlStep(v, 5) : _nlStep(v, 10));
46
+ case 'gram': return v < 0.5 ? out(0) : v < 1 ? { n: v, text: 'less than 1', lt: true } : out(_nlStep(v, 1));
47
+ case 'tenth': return out(_nlStep(v, 0.1));
48
+ case 'ten': return out(_nlStep(v, 10));
49
+ }
50
+ return out(v);
51
+ }
52
+ // % Daily Value: whole percents for the macros (from the declared amount); vitamins and minerals in steps of
53
+ // 2 up to 10 %, 5 up to 50 %, 10 above (from the amount before rounding).
54
+ function flNlPctDv(n, raw, declared) {
55
+ if (!n.dv) return null;
56
+ if (n.micro) {
57
+ const p = raw / n.dv * 100;
58
+ return p < 2 ? 0 : p <= 10 ? _nlStep(p, 2) : p <= 50 ? _nlStep(p, 5) : _nlStep(p, 10);
59
+ }
60
+ return Math.round(declared / n.dv * 100 + 1e-9);
61
+ }
62
+
63
+ // ── The numbers ─────────────────────────────────────────────
64
+ // One row's value for a nutrient, in the label's unit per 100 g; null when the ingredient has none.
65
+ function _nlRowValue(row, n) {
66
+ const ing = row.ing || {};
67
+ const names = [n.key].concat(n.also);
68
+ for (const name of names) {
69
+ const v = ing[name];
70
+ if (typeof v !== 'number' || !Number.isFinite(v) || v < 0) continue; // a negative amount of a nutrient is a typo: not filled
71
+ const u = (row._cfUnits || {})[name.toLowerCase()] || '';
72
+ const fam = u && typeof _tpUnitFactor === 'function' ? _tpUnitFactor(u) : null;
73
+ if (n.key === 'energy') {
74
+ if (!u) return v;
75
+ if (fam && fam[0] === 'e') return v * fam[1] * 100 / 4.184; // kJ per gram → kcal / 100 g
76
+ break; // a unit that isn't energy per mass: the Atwater energy below
77
+ }
78
+ const per = n.unit === 'g' ? 100 : n.unit === 'mg' ? 1e5 : 1e8; // grams per gram → the label unit per 100 g
79
+ if (!u) return v;
80
+ return fam && fam[0] === 'm' ? v * fam[1] * per : null;
81
+ }
82
+ // No energy field: the ingredient's Atwater energy (its own factors where USDA gave them, 61i).
83
+ if (n.key === 'energy' && typeof ing.atwater === 'number' && Number.isFinite(ing.atwater) && ing.atwater >= 0) return ing.atwater;
84
+ return null;
85
+ }
86
+ // No energy field and not all three macros (61p): the energy of the macros it does have, as the Params tab's Energy
87
+ // counts it, so a blank protein on maltodextrin doesn't drop its carbohydrate calories. null when it has none.
88
+ function _nlPartialEnergy(row) {
89
+ const fx = (row.ing && Array.isArray(row.ing._fxKcal)) ? row.ing._fxKcal : [_TP_GENERAL_FACTORS.protein, _TP_GENERAL_FACTORS.fat, _TP_GENERAL_FACTORS.carb];
90
+ let sum = 0, any = false;
91
+ ['protein', 'fat', 'carb'].forEach((k, i) => {
92
+ const v = _nlRowValue(row, FL_NL_NUTRIENTS.find(n => n.key === k));
93
+ if (v != null) { sum += fx[i] * v; any = true; }
94
+ });
95
+ return any ? sum : null;
96
+ }
97
+ function _nlRowName(row) { const g = row.ing || {}; return g._isSubFormula ? (row._subName || 'sub-formula') : (g.name || '(unnamed)'); }
98
+
99
+ // { ok, per100: {key: value}, missing: {key: [names]}, noData: [names], rows: n, withData: n, why? }
100
+ function flNlCompute(f) {
101
+ const out = { ok: false, per100: {}, missing: {}, partial: [], noData: [], rows: 0, withData: 0 };
102
+ if (!f || typeof _tpBuildRows !== 'function') return out;
103
+ const built = _tpBuildRows(f.composition || []);
104
+ // A volume row with no density leaves every row as typed (mL beside g): no numbers, and the tab says why.
105
+ if (built.needsDensity) { out.why = 'density'; out.needsDensity = [...built.needsDensity]; return out; }
106
+ const rows = built.filter(r => r.amount > 0);
107
+ if (!rows.length) { out.why = 'empty'; return out; }
108
+ const total = rows.reduce((a, r) => a + r.amount, 0);
109
+ if (!(total > 0)) { out.why = 'empty'; return out; }
110
+ const vals = rows.map(r => FL_NL_NUTRIENTS.map(n => _nlRowValue(r, n)));
111
+ const eIdx = FL_NL_NUTRIENTS.findIndex(n => n.key === 'energy');
112
+ rows.forEach((r, i) => {
113
+ if (vals[i][eIdx] != null) return;
114
+ const e = _nlPartialEnergy(r);
115
+ if (e != null) { vals[i][eIdx] = e; out.partial.push(_nlRowName(r)); }
116
+ });
117
+ out.rows = rows.length;
118
+ rows.forEach((r, i) => { if (vals[i].some(v => v != null)) out.withData++; else out.noData.push(_nlRowName(r)); });
119
+ FL_NL_NUTRIENTS.forEach((n, j) => {
120
+ let sum = 0; const miss = [];
121
+ rows.forEach((r, i) => { const v = vals[i][j]; if (v == null) { if (vals[i].some(x => x != null)) miss.push(_nlRowName(r)); } else sum += r.amount * v; });
122
+ out.per100[n.key] = sum / total;
123
+ if (miss.length) out.missing[n.key] = miss;
124
+ });
125
+ out.ok = out.withData > 0;
126
+ if (!out.ok) out.why = 'nodata';
127
+ const y = out.ok ? _nlSettings(f).yield : null;
128
+ if (y) { out.yield = y; FL_NL_NUTRIENTS.forEach(n => { out.per100[n.key] = out.per100[n.key] * 100 / y; }); }
129
+ return out;
130
+ }
131
+ // Does any ingredient of this formula carry nutrition? (Shows the Label tab.)
132
+ function flNlHasFoodData(f) {
133
+ try {
134
+ const c = flNlCompute(f);
135
+ if (c.ok) return true;
136
+ if (c.why !== 'density') return false;
137
+ // Rows it can't weigh yet: still a food formula if an ingredient carries a label nutrient.
138
+ const names = new Set(FL_NL_NUTRIENTS.flatMap(n => [n.key].concat(n.also)));
139
+ return ((typeof _flattenComposition === 'function') ? _flattenComposition(f).rows : (f.composition || [])).some(r => {
140
+ const ing = (db.ingredients || []).find(i => i.id === r.ingredientId);
141
+ return !!ing && (ing.customFields || []).some(cf => cf && names.has(String(cf.name || '').trim().toLowerCase()));
142
+ });
143
+ } catch (_) { return false; }
144
+ }
145
+
146
+ const FL_NL_MAX_SERVING = 5000; // g; a larger serving is a typo
147
+ function _nlSettings(f) {
148
+ const l = (f && f.label) || {};
149
+ const s = parseFloat(l.serving), y = parseFloat(l.yield);
150
+ return { yield: Number.isFinite(y) && y >= FL_NL_YIELD[0] && y <= FL_NL_YIELD[1] && y !== 100 ? y : null, serving: Number.isFinite(s) && s > 0 && s <= FL_NL_MAX_SERVING ? s : null, unit: l.unit === 'mL' ? 'mL' : 'g', region: l.region === 'eu' ? 'eu' : 'us', format: ['simplified', 'tabular', 'linear', 'dual'].includes(l.format) ? l.format : 'standard', household: String(l.household || '').trim(), servings: String(l.servings || '').trim() };
151
+ }
152
+ // A serving in grams. A drink's serving is in mL (61r): grams = mL × the formula's density, the finished density
153
+ // when it has one, else the ideal-mix estimate; with neither, 1 g/mL and `noDensity` so the tab can say so.
154
+ // → { amount, unit, g, density, source: 'finished' | 'ideal' | null, noDensity }
155
+ function flNlServing(f) {
156
+ const st = _nlSettings(f), amount = st.serving || 100;
157
+ if (st.unit !== 'mL') return { amount, unit: 'g', g: amount, density: null, source: null, noDensity: false };
158
+ const pd = (typeof formulaPlanningDensity === 'function') ? formulaPlanningDensity(f) : null;
159
+ const d = pd && Number.isFinite(pd.kgPerL) && pd.kgPerL > 0 ? pd.kgPerL : null;
160
+ return { amount, unit: 'mL', g: amount * (d || 1), density: d, source: d ? pd.source : null, noDensity: !d };
161
+ }
162
+ // The label's lines for a serving: [{ ...nutrient, raw, declared, text, pct }]
163
+ // times (61v): the dual column's second column is the whole container, servings × the serving.
164
+ function flNlLines(f, calc, times) {
165
+ const c = calc || flNlCompute(f);
166
+ const g = flNlServing(f).g * (times > 0 ? times : 1);
167
+ return FL_NL_NUTRIENTS.map(n => {
168
+ const raw = (c.per100[n.key] || 0) * g / 100;
169
+ const r = flNlRound(n.round, raw);
170
+ return { ...n, raw, declared: r.n, text: r.text, lt: !!r.lt, pct: flNlPctDv(n, raw, r.n) };
171
+ });
172
+ }
173
+
174
+ // ── Simplified format (21 CFR 101.9(f); 61s) ────────────────
175
+ // Allowed when eight or more of the fifteen label nutrients are insignificant: an amount declared as zero, or for
176
+ // total carbohydrate, dietary fiber and protein "less than 1 gram". It always prints calories, total fat, sodium,
177
+ // total carbohydrate and protein, then whatever else is significant, and names the rest in "Not a significant
178
+ // source of …". The footnote is not required.
179
+ // → { eligible, count, insignificant: [keys], use: the format the panel prints }
180
+ // Cooking yield (61w): finished weight as a percent of the mixed weight. Baking drives water off (under 100), boiling
181
+ // takes it up (over). Only water moves, so every nutrient per 100 g as sold is the mixed figure ÷ yield.
182
+ const FL_NL_YIELD = [10, 400];
183
+ // A household measure longer than this gets the Serving card's whole row to itself ("1/4 cup dry mix (makes about 2
184
+ // pancakes)"; Jun, 17 Nov). On the panel a serving text too long for the line (nl-flow) runs on as one sentence after
185
+ // "Serving size", its second line back at the left edge under it; a short one stays at the right.
186
+ const FL_NL_HH_LONG = 18;
187
+ // What this formula's completed batches yielded, on average: mass batches only, against what was weighed in (else the
188
+ // target), and only losses (a yield over 100 % of the inputs is a data slip, not cooking). → { pct, n } | null
189
+ function flNlBatchYield(f) {
190
+ const ps = [];
191
+ (db.batches || []).forEach(b => {
192
+ if (!b || b.deleted || b.formulationId !== f.id || b.status !== 'Completed') return;
193
+ const y = parseFloat(b.actualYield);
194
+ if (!(y > 0) || typeof isMassUnit !== 'function' || !isMassUnit(b.unit)) return;
195
+ const inp = typeof _batchWeighedInTotal === 'function' ? _batchWeighedInTotal(b) : null;
196
+ const base = inp ? inp.total : parseFloat(b.targetQuantity);
197
+ const p = base > 0 ? y / base * 100 : NaN;
198
+ if (p >= FL_NL_YIELD[0] && p < 99.5) ps.push(p);
199
+ });
200
+ return ps.length ? { pct: Math.round(ps.reduce((a, x) => a + x, 0) / ps.length), n: ps.length } : null;
201
+ }
202
+ const FL_NL_SIMPLE_CORE = ['energy', 'fat', 'sodium', 'carb', 'protein'];
203
+ function flNlSimplified(f, lines) {
204
+ const ls = lines || flNlLines(f);
205
+ const ins = ls.filter(l => l.declared === 0 || (l.lt && ['carb', 'fiber', 'protein'].includes(l.key))).map(l => l.key);
206
+ const eligible = ins.length >= 8;
207
+ const want = _nlSettings(f).format, n = flNlServingsCount(f);
208
+ const use = want === 'tabular' || want === 'linear' ? want : want === 'dual' && n > 1 ? 'dual' : eligible && want === 'simplified' ? 'simplified' : 'standard';
209
+ return { eligible, count: ins.length, insignificant: ins, servings: n, use };
210
+ }
211
+ // Servings per container as a number ("8", "about 8", "2.5"); 0 when it has none. The dual column needs more than one.
212
+ function flNlServingsCount(f) {
213
+ const m = /(\d+(?:[.,]\d+)?)/.exec(_nlSettings(f).servings);
214
+ const n = m ? parseFloat(m[1].replace(',', '.')) : 0;
215
+ return Number.isFinite(n) && n > 0 && n <= 1000 ? n : 0;
216
+ }
217
+ function _nlNotSource(lines, sim) {
218
+ const names = lines.filter(l => sim.insignificant.includes(l.key) && !FL_NL_SIMPLE_CORE.includes(l.key))
219
+ .map(l => /^Vitamin/.test(l.label) ? l.label.replace(/^V/, 'v') : l.label === 'Trans Fat' ? '<i>trans</i> fat' : l.label.toLowerCase());
220
+ if (!names.length) return '';
221
+ return 'Not a significant source of ' + (names.length > 1 ? names.slice(0, -1).join(', ') + ' and ' + names[names.length - 1] : names[0]) + '.';
222
+ }
223
+
224
+ // ── EU nutrition declaration (Regulation (EU) No 1169/2011, Annex XV; 61z) ──
225
+ // Per 100 g, or per 100 ml when the serving is in mL, with the portion beside it when a serving is typed. What differs
226
+ // from the US panel: energy in kJ and kcal from the regulation's factors (Annex XIV: fat 37 / 9, carbohydrate and
227
+ // protein 17 / 4, fibre 8 / 2), carbohydrate without the fibre (the US "total" includes it), and salt = sodium × 2.5.
228
+ // Rounding follows the Commission's guidance (2012): 1 g at 10 g and over, 0.1 g under, "<0.5" at 0.5 g and under
229
+ // (saturates "<0.1" at 0.1 g; salt 0.1 g at 1 g and over, 0.01 g under, "<0.01" at 0.0125 g).
230
+ function _nlEuRound(kind, v) {
231
+ if (!(v > 0)) return '0';
232
+ if (kind === 'salt') return v <= 0.0125 ? '<0.01' : v < 1 ? v.toFixed(2) : v.toFixed(1);
233
+ const low = kind === 'sat' ? 0.1 : 0.5;
234
+ return v <= low ? '<' + low : v < 10 ? v.toFixed(1) : String(Math.round(v));
235
+ }
236
+ // → { basis: '100 g' | '100 ml', portion: text | null, rows: [{ key, label, indent, per, portion }] } (texts as declared)
237
+ function flNlEu(f, calc) {
238
+ const c = calc || flNlCompute(f), st = _nlSettings(f), sv = flNlServing(f), p = c.per100 || {};
239
+ const ml = sv.unit === 'mL';
240
+ const col = (k) => { // k = grams of food in the column
241
+ const m = (key) => (p[key] || 0) * k / 100;
242
+ const fat = m('fat'), fib = m('fiber'), carb = Math.max(0, m('carb') - fib), prot = m('protein');
243
+ const macros = fat + carb + prot + fib > 0;
244
+ const kcal = macros ? 9 * fat + 4 * carb + 4 * prot + 2 * fib : m('energy');
245
+ const kJ = macros ? 37 * fat + 17 * carb + 17 * prot + 8 * fib : m('energy') * 4.184;
246
+ return { energy: `${Math.round(kJ)} kJ / ${Math.round(kcal)} kcal`, fat: _nlEuRound('g', fat) + ' g', sat_fat: _nlEuRound('sat', m('sat_fat')) + ' g',
247
+ carb: _nlEuRound('g', carb) + ' g', sugar: _nlEuRound('g', m('sugar')) + ' g', fiber: _nlEuRound('g', fib) + ' g', protein: _nlEuRound('g', prot) + ' g',
248
+ salt: _nlEuRound('salt', m('sodium') * 2.5 / 1000) + ' g' };
249
+ };
250
+ const per = col(ml ? 100 * (sv.density || 1) : 100);
251
+ const portion = st.serving != null ? col(sv.g) : null;
252
+ const defs = [['energy', 'Energy'], ['fat', 'Fat'], ['sat_fat', 'of which saturates', 1], ['carb', 'Carbohydrate'], ['sugar', 'of which sugars', 1],
253
+ ...(p.fiber > 0 ? [['fiber', 'Fibre']] : []), ['protein', 'Protein'], ['salt', 'Salt']];
254
+ return { basis: ml ? '100 ml' : '100 g', portion: portion ? `${_nlNum(sv.amount)} ${ml ? 'ml' : 'g'}` : null,
255
+ rows: defs.map(([key, label, indent]) => ({ key, label, indent: indent || 0, per: per[key], portion: portion ? portion[key] : null })) };
256
+ }
257
+ function flNlEuPanelHtml(f, calc) {
258
+ const e = flNlEu(f, calc);
259
+ return `<div class="nl-panel nl-eu" id="nl-panel" translate="no"><table>
260
+ <thead><tr><th>Nutrition declaration</th><th>per ${e.basis}</th>${e.portion ? `<th>per portion (${esc(e.portion)})</th>` : ''}</tr></thead>
261
+ <tbody>${e.rows.map(r => `<tr${r.indent ? ' class="nl-e-in"' : ''}><td>${r.label}</td><td>${r.per}</td>${e.portion ? `<td>${r.portion}</td>` : ''}</tr>`).join('')}</tbody>
262
+ </table></div>`;
263
+ }
264
+
265
+ // ── Ingredient statement and Contains ───────────────────────
266
+ // Leaves in descending order by weight; those at 2 % or less may follow "Contains 2% or less of".
267
+ // The formula's leaves, heaviest first: [{ name (label_name when set), w, allergens }]
268
+ function _nlStatementItems(f) {
269
+ const leaves = (typeof _flattenComposition === 'function') ? _flattenComposition(f).rows : [];
270
+ const by = new Map();
271
+ leaves.forEach(r => { if (r.ingredientId && r._weight > 0) by.set(r.ingredientId, (by.get(r.ingredientId) || 0) + r._weight); });
272
+ return [...by.entries()].map(([id, w]) => {
273
+ const ing = (db.ingredients || []).find(i => i.id === id);
274
+ if (!ing) return null;
275
+ const cf = (ing.customFields || []).find(c => c && /^label[ _]?name$/i.test(String(c.name || '').trim()) && String(c.value || '').trim());
276
+ return { name: cf ? String(cf.value).trim() : (ing.name || ''), w, allergens: Array.isArray(ing.allergens) ? ing.allergens : [] };
277
+ }).filter(x => x && x.name).sort((a, b) => b.w - a.w);
278
+ }
279
+
280
+ // ── EU ingredient list: allergens emphasised (Regulation (EU) No 1169/2011, Art. 21 and Annex II; 62c) ──
281
+ // The app's allergen chip → the word the list must show, and the words in an ingredient's own name that already say
282
+ // it. A name that says it gets that word emphasised ("WHEAT flour"); one that doesn't gets it added ("whey protein
283
+ // (MILK)"). On the page the emphasis is bold; in copied text, capitals. Latex is not a food allergen.
284
+ const FL_NL_EU_ALLERGENS = {
285
+ celery: ['celery', /celery|celeriac/i], eggs: ['egg', /eggs?/i], fish: ['fish', /fish/i],
286
+ gluten: ['gluten', /wheat|rye|barley|oats?|spelt|kamut|gluten/i], wheat: ['wheat', /wheat|spelt|durum/i],
287
+ lupin: ['lupin', /lupine?s?/i], milk: ['milk', /milk/i], molluscs: ['molluscs', /mollusc?ks?|oysters?|mussels?|squid|clams?|octopus/i],
288
+ mustard: ['mustard', /mustard/i], peanuts: ['peanuts', /peanuts?/i], sesame: ['sesame', /sesame/i],
289
+ shellfish: ['crustaceans', /crustaceans?|shrimps?|prawns?|crabs?|lobsters?|crayfish/i], soy: ['soya', /soya|soybeans?|soy/i],
290
+ sulfites: ['sulphites', /sulphites?|sulfites?|sul(?:ph|f)ur dioxide|(?:meta)?bisul(?:ph|f)ite/i],
291
+ 'tree-nuts': ['nuts', /almonds?|hazelnuts?|walnuts?|cashews?|pecans?|pistachios?|macadamias?|brazil nuts?|nuts?/i],
292
+ };
293
+ // → { html, text, allergens: [words], count }: every ingredient in descending order by weight.
294
+ function flNlEuStatement(f) {
295
+ const items = _nlStatementItems(f), found = [];
296
+ const one = (it, mark, safe) => {
297
+ const spans = [], add = [];
298
+ it.allergens.forEach(k => {
299
+ const d = FL_NL_EU_ALLERGENS[k];
300
+ if (!d) return;
301
+ if (!found.includes(d[0])) found.push(d[0]);
302
+ const m = new RegExp('\\b(?:' + d[1].source + ')\\b', 'i').exec(it.name);
303
+ if (m) { if (!spans.some(x => m.index < x[1] && m.index + m[0].length > x[0])) spans.push([m.index, m.index + m[0].length]); }
304
+ else if (!add.includes(d[0])) add.push(d[0]);
305
+ });
306
+ spans.sort((a, b) => a[0] - b[0]);
307
+ let out = '', at = 0;
308
+ spans.forEach(([a, b]) => { out += safe(it.name.slice(at, a)) + mark(it.name.slice(a, b)); at = b; });
309
+ out += safe(it.name.slice(at));
310
+ return out + (add.length ? ' (' + add.map(mark).join(', ') + ')' : '');
311
+ };
312
+ const list = (mark, safe) => items.map(it => one(it, mark, safe)).join(', ');
313
+ const html = list(w => `<b>${esc(w)}</b>`, esc), text = list(w => w.toUpperCase(), x => x);
314
+ return { html: html ? html + '.' : '', text: text ? text + '.' : '', allergens: found, count: items.length };
315
+ }
316
+
317
+ function flNlStatement(f) {
318
+ const items = _nlStatementItems(f);
319
+ const major = items.filter(x => x.w > 0.02), minor = items.filter(x => x.w <= 0.02);
320
+ const cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);
321
+ let text = major.map(x => x.name).join(', ');
322
+ if (minor.length) text += (text ? '. ' : '') + (major.length ? 'Contains 2% or less of: ' : '') + minor.map(x => x.name).join(', ');
323
+ const al = (typeof rollupFormulaAllergens === 'function') ? rollupFormulaAllergens(f) : new Map();
324
+ const contains = Object.keys(FL_NL_US_ALLERGENS).filter(k => al.has(k)).map(k => FL_NL_US_ALLERGENS[k]);
325
+ return { text: text ? cap(text) + '.' : '', contains, count: items.length };
326
+ }
327
+ function _nlStatementText(f) {
328
+ if (_nlSettings(f).region === 'eu') { const e = flNlEuStatement(f); return e.text ? 'INGREDIENTS: ' + e.text : ''; }
329
+ const s = flNlStatement(f);
330
+ return (s.text ? 'INGREDIENTS: ' + s.text : '') + (s.contains.length ? '\nCONTAINS: ' + s.contains.join(', ') + '.' : '');
331
+ }
332
+
333
+ // ── The panel ───────────────────────────────────────────────
334
+ function _nlServingText(st) {
335
+ const g = _nlNum(st.serving || 100) + st.unit;
336
+ return st.household ? `${st.household} (${g})` : g;
337
+ }
338
+ function flNlPanelHtml(f, calc, tease) {
339
+ const st = _nlSettings(f);
340
+ if (st.region === 'eu' && !tease) return flNlEuPanelHtml(f, calc); // the Free teaser keeps the US panel
341
+ const lines = flNlLines(f, calc);
342
+ const L = Object.fromEntries(lines.map(l => [l.key, l]));
343
+ const amt = (l) => `${l.text}${l.unit}`;
344
+ const pct = (l) => l.pct == null ? '' : `<b>${l.pct}%</b>`;
345
+ const row = (l) => {
346
+ const name = l.italicFirst ? l.label.replace(/^(\S+)/, '<i>$1</i>') : l.label;
347
+ const left = l.includes ? `Includes ${amt(l)} ${name}` : `${l.bold ? `<b>${name}</b>` : name} ${amt(l)}`;
348
+ return `<div class="nl-row${l.indent ? ' nl-in' + l.indent : ''}"><span>${left}</span><span>${pct(l)}</span></div>`;
349
+ };
350
+ const sim = flNlSimplified(f, lines), simple = sim.use === 'simplified';
351
+ const shown = (l) => !simple || FL_NL_SIMPLE_CORE.includes(l.key) || !sim.insignificant.includes(l.key);
352
+ const main = lines.filter(l => l.key !== 'energy' && !l.micro && shown(l)).map(row).join('');
353
+ const micro = lines.filter(l => l.micro && shown(l)).map(l => `<div class="nl-row"><span>${l.label} ${amt(l)}</span><span>${l.pct}%</span></div>`).join('');
354
+ // Tabular (21 CFR 101.9(d)(11)(iii); 61u): the same lines side by side, for a package without the height. The Free
355
+ // teaser keeps the standard panel.
356
+ if (sim.use === 'tabular' && !tease) {
357
+ const head = '<div class="nl-t-h"><span>Amount/serving</span><span>% Daily Value*</span></div>';
358
+ const col = (keys) => `<div class="nl-t-col">${head}${lines.filter(l => keys.includes(l.key)).map(row).join('')}</div>`;
359
+ const mic = lines.filter(l => l.micro).map(l => `${l.label} ${amt(l)} ${l.pct}%`).join(' &bull; ');
360
+ return `<div class="nl-panel nl-tab" id="nl-panel" translate="no">
361
+ <div class="nl-t-left">
362
+ <div class="nl-title">Nutrition<br>Facts</div>
363
+ ${st.servings ? `<div class="nl-servings">${esc(st.servings)} ${st.servings === '1' ? 'serving' : 'servings'} per container</div>` : ''}
364
+ <div class="nl-t-serv"><b>Serving size</b><br><b>${esc(_nlServingText(st))}</b></div>
365
+ <div class="nl-bar nl-bar-m"></div>
366
+ <div class="nl-t-cal"><span><b>Calories</b><br>per serving</span><span class="nl-t-num">${L.energy.text}</span></div>
367
+ </div>
368
+ <div class="nl-t-mid">
369
+ <div class="nl-t-cols">${col(['fat', 'sat_fat', 'trans_fat', 'cholesterol', 'sodium'])}${col(['carb', 'fiber', 'sugar', 'added_sugar', 'protein'])}</div>
370
+ <div class="nl-bar nl-bar-m"></div>
371
+ <div class="nl-t-micro">${mic}</div>
372
+ </div>
373
+ <div class="nl-foot nl-t-foot">* The % Daily Value (DV) tells you how much a nutrient in a serving of food contributes to a daily diet. 2,000 calories a day is used for general nutrition advice.</div>
374
+ </div>`;
375
+ }
376
+ // Linear (21 CFR 101.9(j)(13)(ii)(A)(2); 61v): one run of text for a small package, with FDA's abbreviations.
377
+ if (sim.use === 'linear' && !tease) {
378
+ const ab = { sat_fat: 'Sat. Fat', trans_fat: '<i>Trans</i> Fat', cholesterol: 'Cholest.', carb: 'Total Carb.', fiber: 'Fiber', vit_d: 'Vit. D', potassium: 'Potas.' };
379
+ const dv = (l) => l.pct == null ? '' : ` (${l.pct}% DV)`;
380
+ const item = (l) => l.key === 'added_sugar' ? null
381
+ : l.key === 'sugar' ? `Total Sugars ${amt(l)} (Incl. ${amt(L.added_sugar)} Added Sugars, ${L.added_sugar.pct}% DV)`
382
+ : `${l.bold ? `<b>${ab[l.key] || l.label}</b>` : (ab[l.key] || l.label)} ${amt(l)}${dv(l)}`;
383
+ return `<div class="nl-panel nl-lin" id="nl-panel" translate="no"><span class="nl-l-t">Nutrition Facts</span> ${st.servings ? `Servings: ${esc(st.servings)}, ` : ''}<b>Serv. size:</b> ${esc(_nlServingText(st))}, Amount per serving: <b class="nl-l-c">Calories ${L.energy.text}</b>, ${lines.filter(l => l.key !== 'energy').map(item).filter(Boolean).join(', ')}.</div>`;
384
+ }
385
+ // Dual column (21 CFR 101.9(b)(12)(i); 61v): per serving beside the whole container.
386
+ if (sim.use === 'dual' && !tease) {
387
+ const C = Object.fromEntries(flNlLines(f, calc, sim.servings).map(l => [l.key, l]));
388
+ const cell = (l) => `<span class="nl-d-a">${amt(l)}</span><span class="nl-d-p">${l.pct == null ? '' : `<b>${l.pct}%</b>`}</span>`;
389
+ const drow = (l) => {
390
+ const name = l.italicFirst ? l.label.replace(/^(\S+)/, '<i>$1</i>') : l.label;
391
+ return `<div class="nl-d-row${l.indent ? ' nl-in' + l.indent : ''}"><span class="nl-d-n">${l.includes ? 'Includes ' + name : l.bold ? `<b>${name}</b>` : name}</span>${cell(l)}${cell(C[l.key])}</div>`;
392
+ };
393
+ return `<div class="nl-panel nl-dual" id="nl-panel" translate="no">
394
+ <div class="nl-title">Nutrition Facts</div>
395
+ <div class="nl-servings">${esc(st.servings)} servings per container</div>
396
+ <div class="nl-serving${_nlServingText(st).length > 38 ? ' nl-flow' : ''}"><span>Serving size</span> <span>${esc(_nlServingText(st))}</span></div>
397
+ <div class="nl-bar nl-bar-l"></div>
398
+ <div class="nl-d-row nl-d-cal"><span class="nl-d-n"><b>Calories</b></span><span class="nl-d-k"><small>Per serving</small><b>${L.energy.text}</b></span><span class="nl-d-k"><small>Per container</small><b>${C.energy.text}</b></span></div>
399
+ <div class="nl-bar nl-bar-m"></div>
400
+ <div class="nl-d-row nl-d-h"><span class="nl-d-n"></span><span class="nl-d-a"></span><span class="nl-d-p">% DV*</span><span class="nl-d-a"></span><span class="nl-d-p">% DV*</span></div>
401
+ ${lines.filter(l => l.key !== 'energy' && !l.micro).map(drow).join('')}
402
+ <div class="nl-bar nl-bar-l"></div>
403
+ ${lines.filter(l => l.micro).map(drow).join('')}
404
+ <div class="nl-bar nl-bar-m"></div>
405
+ <div class="nl-foot">* The % Daily Value (DV) tells you how much a nutrient in a serving of food contributes to a daily diet. 2,000 calories a day is used for general nutrition advice.</div>
406
+ </div>`;
407
+ }
408
+ // tease (Free): the title and serving stay sharp, the numbers under them are blurred and out of reach.
409
+ return `<div class="nl-panel"${tease ? '' : ' id="nl-panel"'} translate="no">
410
+ <div class="nl-title">Nutrition Facts</div>
411
+ ${st.servings ? `<div class="nl-servings">${esc(st.servings)} ${st.servings === '1' ? 'serving' : 'servings'} per container</div>` : ''}
412
+ <div class="nl-serving${_nlServingText(st).length > 24 ? ' nl-flow' : ''}"><span>Serving size</span> <span>${esc(_nlServingText(st))}</span></div>
413
+ <div class="nl-bar nl-bar-l"></div>
414
+ ${tease ? '<div class="nl-blur" aria-hidden="true" inert>' : ''}
415
+ <div class="nl-aps">Amount per serving</div>
416
+ <div class="nl-cal"><span>Calories</span><span>${L.energy.text}</span></div>
417
+ <div class="nl-bar nl-bar-m"></div>
418
+ <div class="nl-dvh">% Daily Value${simple ? '' : '*'}</div>
419
+ ${main}
420
+ ${simple ? `${micro ? `<div class="nl-bar nl-bar-l"></div>${micro}` : ''}<div class="nl-bar nl-bar-m"></div><div class="nl-foot nl-notsrc">${_nlNotSource(lines, sim)}</div>` : `<div class="nl-bar nl-bar-l"></div>
421
+ ${micro}
422
+ <div class="nl-bar nl-bar-m"></div>
423
+ <div class="nl-foot">* The % Daily Value (DV) tells you how much a nutrient in a serving of food contributes to a daily diet. 2,000 calories a day is used for general nutrition advice.</div>`}
424
+ ${tease ? '</div>' : ''}
425
+ </div>`;
426
+ }
427
+
428
+ // ── The tab ─────────────────────────────────────────────────
429
+ function flNlTabButtonHtml(f) {
430
+ if (!f || !flNlHasFoodData(f)) return '';
431
+ const pro = typeof hasFeature !== 'function' || hasFeature('formulations.nutritionLabel');
432
+ return `<div class="tab" data-tab="label" onclick="switchFormTab('label')" title="Nutrition Facts, ingredient statement and allergens for this formula">Label${pro ? '' : ' <span class="asm-designer-pro-badge usda-pro">Pro</span>'}</div>`;
433
+ }
434
+ function _nlFmt(v) {
435
+ if (v == null || !Number.isFinite(v)) return '—';
436
+ const a = Math.abs(v);
437
+ return a === 0 ? '0' : a >= 100 ? String(Math.round(v)) : a >= 10 ? String(Math.round(v * 10) / 10) : a >= 1 ? String(Math.round(v * 100) / 100) : String(+v.toPrecision(2));
438
+ }
439
+ function flNlTabHtml(f) {
440
+ if (!f || !flNlHasFoodData(f)) return '';
441
+ if (typeof hasFeature === 'function' && !hasFeature('formulations.nutritionLabel')) {
442
+ // Their own label, blurred under the offer (Jun, 15 Nov). Only a formula it can weigh has one to show.
443
+ const tc = flNlCompute(f);
444
+ const offer = `<div class="nl-tease-card">
445
+ <div class="nl-tease-t">Nutrition label <span class="asm-designer-pro-badge usda-pro">Pro</span></div>
446
+ <div class="nl-tease-s">This formula’s label is ready.</div>
447
+ <button class="btn btn-primary btn-sm" onclick="proUpsell('formulations.nutritionLabel')">See what Pro adds</button>
448
+ </div>`;
449
+ if (!tc.ok) return `<div class="card nl-tease"><div class="card-body">${offer}</div></div>`;
450
+ return `<div class="card nl-tease"><div class="card-body nl-stage nl-tease-stage"><style>${FL_NL_PANEL_CSS}</style>
451
+ <div class="nl-tease-wrap">${flNlPanelHtml(f, tc, true)}${offer}</div>
452
+ </div></div>`;
453
+ }
454
+ const c = flNlCompute(f);
455
+ if (!c.ok) {
456
+ const who = (c.needsDensity || []).slice(0, 6).join(', ');
457
+ return `<div class="card"><div class="card-body"><div class="nl-note warn">No label yet. Add a density to ${esc(who) || 'the rows measured by volume'}.</div></div></div>`;
458
+ }
459
+ const st = _nlSettings(f);
460
+ const lines = flNlLines(f, c);
461
+ const s = flNlStatement(f);
462
+ const id = esc(f.id);
463
+ const sv = flNlServing(f), g = sv.g, per = `${_nlNum(sv.amount)} ${sv.unit}`;
464
+ const seg = (u) => `<button type="button" class="fl-seg${sv.unit === u ? ' on' : ''}" aria-pressed="${sv.unit === u}" onclick="flNlSet('${id}','unit','${u}')">${u}</button>`;
465
+ const dens = sv.unit !== 'mL' ? '' : sv.noDensity
466
+ ? `<div class="nl-note warn nl-dens" data-tip="Set Finished Density on the formula (Edit), or a density on every ingredient.">No density on this formula. Counted as 1 g/mL.</div>`
467
+ : `<div class="nl-dim nl-dens"${sv.source === 'ideal' ? ' data-tip="Estimated from the ingredients’ densities. Set Finished Density on the formula (Edit) to use a measured one."' : ''}>${_nlNum(sv.amount)} mL = ${_nlFmt(sv.g)} g at ${+sv.density.toFixed(4)} g/mL (${sv.source === 'finished' ? 'finished density' : 'estimated'}).</div>`;
468
+ const sim = flNlSimplified(f, lines);
469
+ // Insignificant only because no ingredient has the field: say so before anyone prints a simplified label on it.
470
+ const blank = lines.filter(l => sim.insignificant.includes(l.key) && (c.missing[l.key] || []).length >= c.withData).map(l => l.label);
471
+ const fseg = (k, t, tip) => `<button type="button" class="fl-seg${sim.use === k ? ' on' : ''}" aria-pressed="${sim.use === k}" data-tip="${tip}" onclick="flNlSet('${id}','format','${k}')">${t}</button>`;
472
+ // Simplified is offered only to a food that qualifies. Dual needs more than one serving per container: without it
473
+ // the choice is greyed, says what it needs, and a click goes to that field (Jun, 17 Nov: "show it greyed").
474
+ const eu = st.region === 'eu';
475
+ const rseg = (k, t, tip) => `<button type="button" class="fl-seg${st.region === k ? ' on' : ''}" aria-pressed="${st.region === k}" data-tip="${tip}" onclick="flNlSet('${id}','region','${k}')">${t}</button>`;
476
+ const region = `<span class="fl-seg-group sm" role="group" aria-label="Label region">${rseg('us', 'US', 'Nutrition Facts (FDA).')}${rseg('eu', 'EU', 'Nutrition declaration per 100 g: kJ and kcal, salt.')}</span>`;
477
+ const fmt = eu ? `<div class="nl-fmt">${region}<span id="nl-fmt-saved" class="fl-saved-tick" role="status"></span></div>` : `<div class="nl-fmt">${region}<span class="fl-seg-group sm" role="group" aria-label="Label format">${fseg('standard', 'Standard', 'The vertical panel.')}${fseg('tabular', 'Tabular', 'Horizontal, for a package without the height.')}${fseg('linear', 'Linear', 'One paragraph, for a small package where Tabular won’t fit.')}${sim.servings > 1 ? fseg('dual', 'Dual', 'Per serving beside the whole container.') : `<button type="button" class="fl-seg nl-seg-off" aria-disabled="true" data-tip="Needs Servings per container above 1." onclick="var e=document.getElementById('nl-servings-in');if(e)e.focus()">Dual</button>`}${sim.eligible ? fseg('simplified', 'Simplified', sim.count + ' of 15 nutrients are insignificant here; 8 or more allow it.') : ''}</span><span id="nl-fmt-saved" class="fl-saved-tick" role="status"></span></div>${blank.length && sim.use === 'simplified' ? `<div class="nl-note warn nl-fmt-warn" data-tip="${esc(blank.join(', '))}">${blank.length === sim.count ? 'All ' + sim.count : blank.length + ' of the ' + sim.count} have no data. Blank is not zero.</div>` : ''}`;
478
+ const by = c.yield ? null : flNlBatchYield(f);
479
+ const yld = c.yield
480
+ ? `<div class="nl-dim nl-dens" data-tip="Only water is lost or gained in cooking, so each nutrient per 100 g is the mixed figure ÷ yield. The Params tab stays as mixed.">As sold: ${_nlNum(c.yield)}% of the mixed weight. Nutrients × ${+(100 / c.yield).toFixed(2)}.</div>`
481
+ : by ? `<div class="nl-dim nl-dens">${by.n === 1 ? '1 batch' : by.n + ' batches'} yielded ${by.pct}%. <a href="#" onclick="flNlSet('${id}','yield',${by.pct});return false">Use ${by.pct}%</a></div>` : '';
482
+ const tipList = (a) => esc(a.slice(0, 12).join(', ') + (a.length > 12 ? ` +${a.length - 12} more` : ''));
483
+ const cover = c.noData.length
484
+ ? `<div class="nl-note warn" data-tip="${tipList(c.noData)}">${c.withData} of ${c.rows} ingredients have nutrition. The rest count as 0.</div>`
485
+ : `<div class="nl-note ok">All ${c.rows} ingredients have nutrition.</div>`;
486
+ const E = eu ? flNlEu(f, c) : null;
487
+ const tbl = eu ? '' : lines.map(l => {
488
+ const miss = c.missing[l.key];
489
+ const part = l.key === 'energy' && c.partial.length ? ` <span class="nl-miss" data-tip="From the macros filled, the blank ones as 0: ${tipList(c.partial)}">${c.partial.length} partial</span>` : '';
490
+ return `<tr><td class="${l.indent ? 'nl-t-in' + l.indent : ''}">${esc(l.label)}${part}${miss ? ` <span class="nl-miss" data-tip="Not filled on: ${tipList(miss)}">${miss.length >= c.withData ? 'no data' : miss.length + ' missing'}</span>` : ''}</td>
491
+ <td class="num">${_nlFmt(c.per100[l.key])} <span class="u">${esc(l.unit)}</span></td>
492
+ <td class="num">${_nlFmt(l.raw)} <span class="u">${esc(l.unit)}</span></td>
493
+ <td class="num"><strong>${l.text}</strong> <span class="u">${esc(l.unit)}</span></td>
494
+ <td class="num">${l.pct == null ? '' : l.pct + '%'}</td></tr>`;
495
+ }).join('');
496
+ return `<div class="nl-wrap${!eu && ['tabular', 'linear', 'dual'].includes(sim.use) ? ' nl-wide' : ''}">
497
+ <div class="nl-side">
498
+ <div class="card">
499
+ <div class="card-header"><h2>Serving</h2><span id="nl-saved" class="fl-saved-tick" role="status"></span></div>
500
+ <div class="card-body nl-form">
501
+ <label>Serving size<span class="nl-unit"><input type="number" min="0" step="any" value="${st.serving != null ? esc(String(st.serving)) : ''}" placeholder="100" onchange="flNlSet('${id}','serving',this.value)"><span class="fl-seg-group sm" role="group" aria-label="Serving unit">${seg('g')}${seg('mL')}</span></span></label>
502
+ <label class="nl-hh${st.household.length > FL_NL_HH_LONG ? ' nl-long' : ''}">Household measure<input type="text" maxlength="80" oninput="this.parentElement.classList.toggle('nl-long', this.value.length > ${FL_NL_HH_LONG})" value="${esc(st.household)}" placeholder="2/3 cup" onchange="flNlSet('${id}','household',this.value)"></label>
503
+ <label>Servings per container<input id="nl-servings-in" type="text" maxlength="20" value="${esc(st.servings)}" placeholder="8, or about 8" onchange="flNlSet('${id}','servings',this.value)"></label>
504
+ <label data-tip="Finished weight ÷ mixed weight. Under 100 when baking or drying drives water off.">Cooking yield<span class="nl-unit"><input type="number" min="${FL_NL_YIELD[0]}" max="${FL_NL_YIELD[1]}" step="any" value="${st.yield != null ? esc(String(st.yield)) : ''}" placeholder="100" onchange="flNlSet('${id}','yield',this.value)"><em>%</em></span></label>
505
+ ${dens}${yld}
506
+ </div>
507
+ </div>
508
+ <div class="card">
509
+ <div class="card-header"><h2>Ingredient statement</h2>
510
+ <button class="btn btn-secondary btn-sm" onclick="flNlCopyStatement('${id}')">Copy</button></div>
511
+ <div class="card-body nl-stmt">
512
+ ${eu ? (() => { const es = flNlEuStatement(f); return `<div class="nl-eu-stmt"><strong>INGREDIENTS:</strong> ${es.html || '<span class="nl-dim">No ingredients yet.</span>'}</div>
513
+ ${es.allergens.length ? '' : '<div class="nl-dim">No EU allergens on the ingredients.</div>'}
514
+ <div class="nl-dim nl-hint" data-tip="The 14 EU allergens, from each ingredient’s allergen chips. A name that doesn’t say the allergen gets it added in brackets. Copy gives them in CAPITALS. Add a custom field named label_name to an ingredient to print another name.">By weight, most first. Allergens in bold.</div>`; })() : `<div><strong>INGREDIENTS:</strong> ${esc(s.text) || '<span class="nl-dim">No ingredients yet.</span>'}</div>
515
+ ${s.contains.length ? `<div class="nl-contains"><strong>CONTAINS:</strong> ${esc(s.contains.join(', '))}.</div>` : '<div class="nl-dim">No major US allergens on the ingredients.</div>'}
516
+ <div class="nl-dim nl-hint" data-tip="Add a custom field named label_name to an ingredient to print another name here.">By weight, most first. 2% or less grouped.</div>`}
517
+ </div>
518
+ </div>
519
+ <div class="card">
520
+ <div class="card-header"><h2>Numbers</h2></div>
521
+ <div class="card-body">
522
+ ${cover}
523
+ ${eu ? `<div class="table-wrapper"><table class="nl-table"><thead><tr><th>Nutrient</th><th class="num">Per ${E.basis}</th>${E.portion ? `<th class="num">Per portion (${esc(E.portion)})</th>` : ''}</tr></thead><tbody>${E.rows.map(r => `<tr><td class="${r.indent ? 'nl-t-in1' : ''}">${r.label}</td><td class="num"><strong>${r.per}</strong></td>${E.portion ? `<td class="num"><strong>${r.portion}</strong></td>` : ''}</tr>`).join('')}</tbody></table></div>
524
+ <div class="nl-dim nl-hint" data-tip="Energy from the EU factors (fat 37 kJ / 9 kcal, carbohydrate and protein 17 / 4, fibre 8 / 2). Carbohydrate leaves the fibre out. Salt = sodium × 2.5.">As declared. Carbohydrate without fibre; salt from sodium.</div>` : `<div class="table-wrapper"><table class="nl-table"><thead><tr><th>Nutrient</th><th class="num">Per 100 g${c.yield ? ' sold' : ''}</th><th class="num">Per ${per}</th><th class="num">On label</th><th class="num">% DV</th></tr></thead><tbody>${tbl}</tbody></table></div>`}
525
+ </div>
526
+ </div>
527
+ </div>
528
+ <div class="nl-main">
529
+ <div class="card">
530
+ <div class="card-header"><h2>${eu ? 'Nutrition' : 'Nutrition Facts'} <span class="nl-sub">${eu ? 'EU' : 'US'}</span></h2>
531
+ <div class="nl-actions">
532
+ <button class="btn btn-secondary btn-sm" onclick="flNlSavePng('${id}')">Save PNG</button>
533
+ <button class="btn btn-secondary btn-sm" onclick="flNlPrint('${id}')">Print</button>
534
+ </div></div>
535
+ <div class="card-body nl-stage"><style>${FL_NL_PANEL_CSS}</style>${fmt}${flNlPanelHtml(f, c)}
536
+ ${eu ? '' : `<div class="nl-per100" data-tip="The Params tab's Energy is per 100 g. The label is per serving, rounded.">Unrounded: ${_nlFmt(c.per100.energy)} kcal / 100 g${c.yield ? ' as sold' : ''}${g === 100 && sv.unit === 'g' ? '' : ` · ${_nlFmt(c.per100.energy * g / 100)} kcal / ${per}`}</div>
537
+ `}
538
+ <div class="nl-dim nl-legal">Calculated from ingredient data. Check before you print packaging.</div>
539
+ </div>
540
+ </div>
541
+ </div>
542
+ </div>`;
543
+ }
544
+
545
+ // Save one serving field on the formula, then redraw the tab.
546
+ function flNlSet(fid, key, value) {
547
+ const f = (db.formulations || []).find(x => x.id === fid);
548
+ if (!f || !['serving', 'unit', 'format', 'region', 'yield', 'household', 'servings'].includes(key)) return;
549
+ const l = { ...(f.label || {}) };
550
+ if (key === 'serving') { const n = parseFloat(String(value).replace(',', '.')); if (Number.isFinite(n) && n > 0 && n <= FL_NL_MAX_SERVING) l.serving = n; else { delete l.serving; if (String(value).trim() && typeof toast === 'function') toast('Serving size: 0 to ' + FL_NL_MAX_SERVING + '.'); } }
551
+ else if (key === 'format') { if (['simplified', 'tabular', 'linear', 'dual'].includes(value)) l.format = value; else delete l.format; }
552
+ else if (key === 'yield') { const n = parseFloat(String(value).replace(',', '.')); if (Number.isFinite(n) && n >= FL_NL_YIELD[0] && n <= FL_NL_YIELD[1] && n !== 100) l.yield = n; else { delete l.yield; if (String(value).trim() && n !== 100 && typeof toast === 'function') toast('Cooking yield: ' + FL_NL_YIELD[0] + ' to ' + FL_NL_YIELD[1] + ' %.'); } }
553
+ else if (key === 'region') { if (value === 'eu') l.region = 'eu'; else delete l.region; }
554
+ else if (key === 'unit') { if (value === 'mL') l.unit = 'mL'; else delete l.unit; }
555
+ else { const t = String(value || '').trim().slice(0, key === 'household' ? 80 : 40); if (t) l[key] = t; else delete l[key]; }
556
+ f.label = l;
557
+ const saved = typeof _fmlSyncSave === 'function' && _fmlSyncSave(f, ['label']);
558
+ const el = document.getElementById('tab-label');
559
+ if (el) el.innerHTML = flNlTabHtml(f);
560
+ // The redraw makes new buttons: grey the ones this person can't use now, not a frame later (Save PNG / Print with
561
+ // member exports off flashed enabled on every serving change; Jun, 17 Nov).
562
+ try { if (window.__flViewerGate && typeof window.__flViewerGate.refresh === 'function') window.__flViewerGate.refresh(); } catch (_) {}
563
+ if (saved && typeof flSavedTick === 'function') flSavedTick(key === 'format' || key === 'region' ? 'nl-fmt-saved' : 'nl-saved');
564
+ }
565
+
566
+ function _nlFile(f) { return 'nutrition-facts-' + String(f.uid || f.name || 'formula').replace(/[^\w.-]+/g, '-').replace(/^-+|-+$/g, '').toLowerCase(); }
567
+ function _nlGate() {
568
+ if (typeof hasFeature === 'function' && !hasFeature('formulations.nutritionLabel')) { if (typeof proUpsell === 'function') proUpsell('formulations.nutritionLabel'); return false; }
569
+ return true;
570
+ }
571
+ function flNlCopyStatement(fid) {
572
+ if (!_nlGate()) return;
573
+ if (typeof flExportAllowed === 'function' && !flExportAllowed('single', 'an ingredient statement')) return; // what members can take out (0114)
574
+ const f = (db.formulations || []).find(x => x.id === fid);
575
+ if (!f) return;
576
+ const text = _nlStatementText(f);
577
+ const done = () => { if (typeof toast === 'function') toast('Ingredient statement copied.'); };
578
+ if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(text).then(done, () => { if (typeof toast === 'function') toast('Couldn’t copy. Select the text instead.'); });
579
+ }
580
+ function flNlSavePng(fid) {
581
+ if (!_nlGate()) return;
582
+ if (typeof flExportAllowed === 'function' && !flExportAllowed('image', 'a nutrition label image')) return; // what members can take out (0114)
583
+ const f = (db.formulations || []).find(x => x.id === fid);
584
+ const el = document.getElementById('nl-panel');
585
+ if (!f || !el) return;
586
+ if (typeof html2canvas !== 'function') { if (typeof toast === 'function') toast('PNG export needs the html2canvas library, which didn’t load.'); return; }
587
+ html2canvas(el, { backgroundColor: 'white', scale: 4, useCORS: true }).then(canvas => {
588
+ canvas.toBlob(blob => {
589
+ if (!blob) { if (typeof toast === 'function') toast('Couldn’t generate PNG.'); return; }
590
+ const url = URL.createObjectURL(blob);
591
+ const a = document.createElement('a');
592
+ a.href = url; a.download = _nlFile(f) + '.png';
593
+ document.body.appendChild(a); a.click(); a.remove();
594
+ URL.revokeObjectURL(url);
595
+ }, 'image/png');
596
+ }).catch(() => { if (typeof toast === 'function') toast('Couldn’t generate PNG.'); });
597
+ }
598
+ // The panel's own look, shared by the page and the print window (always black on white, whatever the theme).
599
+ // The thick rules are borders, not background fills: a browser leaves backgrounds off paper unless "Background
600
+ // graphics" is ticked, and the bars went missing from prints (Jun, 17 Nov).
601
+ const FL_NL_PANEL_CSS = `.nl-panel{box-sizing:border-box;width:280px;padding:4px 7px 6px;border:1.5px solid #000;background:rgb(255,255,255);color:#000;font:400 11.5px/1.25 Helvetica,Arial,sans-serif;text-align:left}
602
+ .nl-panel *{box-sizing:border-box}.nl-panel b{font-weight:800}
603
+ .nl-title{font-weight:900;font-size:35px;line-height:1.02;letter-spacing:-.6px;border-bottom:1px solid #000;padding-bottom:2px;white-space:nowrap}
604
+ .nl-servings{font-size:13px;padding-top:3px}
605
+ .nl-serving{display:flex;justify-content:space-between;gap:10px;font-weight:800;font-size:13.5px;line-height:1.15;padding-bottom:2px}
606
+ .nl-serving span:first-child{flex:none;white-space:nowrap}.nl-serving span:last-child{min-width:0;text-align:left;overflow-wrap:anywhere}
607
+ .nl-t-serv,.nl-lin,.nl-eu th{overflow-wrap:anywhere}
608
+ .nl-serving.nl-flow{display:block;overflow-wrap:anywhere}
609
+ .nl-bar{height:0;border-top:0 solid #000}.nl-bar-l{border-top-width:9px}.nl-bar-m{border-top-width:4px}
610
+ .nl-aps{font-weight:800;font-size:10.5px;line-height:1.35;padding:3px 0 2px}
611
+ .nl-cal{display:flex;justify-content:space-between;align-items:flex-end;font-weight:900;font-size:26px;line-height:1.1;padding-bottom:1px}
612
+ .nl-cal span:last-child{font-size:38px;line-height:1;margin-top:-14px}
613
+ .nl-dvh{text-align:right;font-weight:800;font-size:10.5px;padding:2px 0;border-bottom:1px solid #000}
614
+ .nl-row{display:flex;justify-content:space-between;gap:8px;padding:2px 0;border-bottom:1px solid #000}
615
+ .nl-row.nl-in1{padding-left:14px}.nl-row.nl-in2{padding-left:28px;margin-left:0}
616
+ .nl-panel .nl-bar + .nl-row{border-top:0}.nl-panel .nl-row:has(+ .nl-bar){border-bottom:0}
617
+ .nl-foot{font-size:9px;line-height:1.2;padding-top:4px}
618
+ .nl-panel.nl-tab{width:740px;display:grid;grid-template-columns:154px minmax(0,1fr) 104px;column-gap:10px;padding:5px 8px 6px;align-items:start}
619
+ .nl-tab .nl-title{font-size:31px;line-height:.98;border-bottom:0;padding-bottom:3px;white-space:normal}
620
+ .nl-tab .nl-servings{font-size:11.5px;padding-top:0}.nl-t-serv{font-size:12px;line-height:1.2;padding:1px 0 3px}
621
+ .nl-t-cal{display:flex;justify-content:space-between;align-items:flex-end;gap:6px;font-size:11px;line-height:1.15;padding-top:3px}
622
+ .nl-t-cal b{font-weight:900;font-size:19px}.nl-t-num{font-weight:900;font-size:36px;line-height:.9}
623
+ .nl-t-cols{display:grid;grid-template-columns:1fr 1fr;column-gap:12px}
624
+ .nl-t-h{display:flex;justify-content:space-between;gap:6px;font-weight:800;font-size:9.5px;padding:1px 0 2px;border-bottom:4px solid #000}
625
+ .nl-t-col .nl-row:last-child{border-bottom:0}
626
+ .nl-t-micro{font-size:10.5px;padding-top:3px;white-space:nowrap}
627
+ .nl-tab .nl-row{white-space:nowrap}.nl-tab .nl-row.nl-in1{padding-left:10px}.nl-tab .nl-row.nl-in2{padding-left:20px}
628
+ .nl-tab .nl-t-foot{padding-top:2px;align-self:center}
629
+ .nl-panel.nl-lin{width:430px;padding:5px 8px 6px;font-size:11px;line-height:1.3}
630
+ .nl-l-t{font-weight:900;font-size:19px;line-height:1;letter-spacing:-.3px;margin-right:2px}.nl-l-c{font-weight:900;font-size:13px}
631
+ .nl-panel.nl-dual{width:380px}
632
+ .nl-d-row{display:grid;grid-template-columns:minmax(0,1fr) 46px 40px 52px 40px;align-items:end;padding:2px 0;border-bottom:1px solid #000}
633
+ .nl-d-row.nl-in1 .nl-d-n{padding-left:12px}.nl-d-row.nl-in2 .nl-d-n{padding-left:24px}
634
+ .nl-d-a,.nl-d-p{text-align:right;white-space:nowrap}.nl-d-a{border-left:1px solid #000;margin:-2px 0;padding:2px 0}.nl-d-p{padding-right:3px}
635
+ .nl-d-row .nl-d-p:last-child{padding-right:0}
636
+ .nl-d-h{font-weight:800;font-size:10px}
637
+ .nl-d-cal{grid-template-columns:minmax(0,1fr) 86px 92px;border-bottom:0;padding-bottom:1px}
638
+ .nl-d-cal .nl-d-n b{font-weight:900;font-size:24px;line-height:1}
639
+ .nl-d-k{display:flex;flex-direction:column;align-items:flex-end;border-left:1px solid #000;padding-right:3px}.nl-d-k:last-child{padding-right:0}
640
+ .nl-d-k small{font-weight:800;font-size:9.5px}.nl-d-k b{font-weight:900;font-size:30px;line-height:1}
641
+ .nl-panel .nl-bar + .nl-d-row{border-top:0}.nl-panel .nl-d-row:has(+ .nl-bar){border-bottom:0}
642
+ .nl-panel.nl-eu{width:316px;padding:0;border-width:1px}
643
+ .nl-eu table{width:100%;table-layout:fixed;border-collapse:collapse;margin:0;background:none;font:400 11.5px/1.25 Helvetica,Arial,sans-serif}
644
+ .nl-eu th,.nl-eu td{padding:3px 5px;border:0;border-bottom:1px solid #000;background:none;color:#000;font:400 11.5px/1.25 Helvetica,Arial,sans-serif;text-align:right;vertical-align:bottom;text-transform:none;letter-spacing:0;white-space:nowrap}
645
+ .nl-eu th{font-weight:700;border-bottom-width:1.5px;white-space:normal}.nl-eu th:first-child{width:38%}.nl-eu th:first-child,.nl-eu td:first-child{text-align:left}
646
+ .nl-eu th + th,.nl-eu td + td{border-left:1px solid #000}
647
+ .nl-eu tr:last-child td{border-bottom:0}.nl-eu .nl-e-in td:first-child{padding-left:16px}`;
648
+ function flNlPrint(fid) {
649
+ if (!_nlGate()) return;
650
+ if (typeof flExportAllowed === 'function' && !flExportAllowed('single', 'a nutrition label print')) return; // what members can take out (0114)
651
+ const f = (db.formulations || []).find(x => x.id === fid);
652
+ if (!f) return;
653
+ const s = flNlStatement(f);
654
+ const win = typeof flOpenPrintWindow === 'function' ? flOpenPrintWindow('width=720,height=820') : null;
655
+ if (!win) { if (typeof toast === 'function') toast('Couldn’t open the print view. Try again.'); return; }
656
+ const css = `body{font:12px Helvetica,Arial,sans-serif;color:#000;margin:28px}h1{font-size:15px;margin:0 0 2px}.meta{font-size:11px;opacity:.65;margin-bottom:16px}
657
+ .stmt{max-width:420px;margin-top:16px;font-size:11.5px;line-height:1.4}.stmt div{margin-bottom:4px}
658
+ ${FL_NL_PANEL_CSS}
659
+ ${typeof flPrintPageCss === 'function' ? flPrintPageCss() : ''}`;
660
+ win.document.write(`<!DOCTYPE html><html><head><meta charset="utf-8"><title>${esc(f.name || 'Nutrition Facts')}</title><style>${css}</style></head><body>
661
+ <h1>${esc(f.name || '')}</h1><div class="meta">${esc([f.uid, 'calculated from ingredient data', 'printed ' + new Date().toLocaleDateString()].filter(Boolean).join(' · '))}</div>
662
+ ${flNlPanelHtml(f)}
663
+ <div class="stmt">${_nlSettings(f).region === 'eu' ? (() => { const es = flNlEuStatement(f); return es.html ? `<div><b>INGREDIENTS:</b> ${es.html}</div>` : ''; })() : `${s.text ? `<div><b>INGREDIENTS:</b> ${esc(s.text)}</div>` : ''}${s.contains.length ? `<div><b>CONTAINS:</b> ${esc(s.contains.join(', '))}.</div>` : ''}`}</div>
664
+ <script>window.onload=()=>setTimeout(()=>window.print(),250)<\/script></body></html>`);
665
+ win.document.close();
666
+ if (typeof flPreparePrintWindow === 'function') flPreparePrintWindow(win);
667
+ }