formlab-mcp 0.6.61 → 0.6.62

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.
@@ -0,0 +1,613 @@
1
+ // ============================================================
2
+ // REACTIVE CHEMISTRY: equivalents, index and Solve (docs/REACTIVE_CHEMISTRY_PLAN.md)
3
+ // ------------------------------------------------------------
4
+ // Jun, 26 Oct: "at least half of the customers will come from coatings, adhesive background … having some sort of
5
+ // reactive chemistry representation will go a long way". Decided 27 Oct: an index everywhere (epoxy 98, never
6
+ // 0.98 : 1); no target, no color; a polyol's acid counts toward the NCO demand; water is a later preset.
7
+ //
8
+ // • An ingredient carries reactiveGroups = [{ group: 'epoxy', basis: 'eew', value: 187 }], the value as the
9
+ // datasheet quotes it. meq/g is derived every time, never stored, so a corrected datasheet value can't leave a
10
+ // stale number behind.
11
+ // • The theoretical-parameter view (js/views/theoretical-params.js) exposes each group as ing.epoxy … ing.vinyl
12
+ // in meq/g (0 when absent, so a solvent adds nothing), plus the datasheet terms (ing.eew, ing.ohv …, null when
13
+ // absent, so `eew < 200` in Smart search skips ingredients without one).
14
+ // • The formula's Composition tab shows a balance strip per reacting pair, with a target from the chip and Solve
15
+ // (Pro: reactive.solve); a batch shows the same from what was weighed, and Pro sets it against the plan.
16
+ // Everything here reads the composition through _tpBuildRows, the same rows the Reactive presets evaluate, so the
17
+ // strip and the Params tab always agree.
18
+ // ============================================================
19
+
20
+ // How a datasheet quotes a group, and its meq/g. `f` (groups per molecule) needs the ingredient's MW.
21
+ const FL_RX_BASES = {
22
+ eew: { label: 'EEW, g/eq', short: 'EEW', unit: 'g/eq', toMeq: v => 1000 / v, fromMeq: m => 1000 / m },
23
+ ahew: { label: 'AHEW, g/eq', short: 'AHEW', unit: 'g/eq', toMeq: v => 1000 / v, fromMeq: m => 1000 / m },
24
+ eqw: { label: 'Equivalent weight, g/eq', short: 'Eq. wt', unit: 'g/eq', toMeq: v => 1000 / v, fromMeq: m => 1000 / m },
25
+ ohv: { label: 'OH number, mg KOH/g', short: 'OHV', unit: '', toMeq: v => v / 56.1, fromMeq: m => m * 56.1 },
26
+ av: { label: 'Acid value, mg KOH/g', short: 'AV', unit: '', toMeq: v => v / 56.1, fromMeq: m => m * 56.1 },
27
+ amv: { label: 'Amine value, mg KOH/g', short: 'Amine value', unit: '', toMeq: v => v / 56.1, fromMeq: m => m * 56.1 },
28
+ ncopct: { label: 'NCO, %', short: 'NCO', unit: '%', toMeq: v => v * 10 / 42.02, fromMeq: m => m * 4.202 },
29
+ // Water: H2O + 2 NCO → urea + CO2, so 18.02 / 2 = 9.008 g/eq; 1 % water = 1.11 meq/g.
30
+ wpct: { label: 'Water content, %', short: 'Water', unit: '%', toMeq: v => v * 10 / 9.008, fromMeq: m => m * 0.9008 },
31
+ mmol: { label: 'mmol/g', short: '', unit: 'mmol/g', toMeq: v => v, fromMeq: m => m },
32
+ f: { label: 'MW + groups / molecule', short: '', unit: 'per molecule', toMeq: (v, mw) => (mw > 0 ? v * 1000 / mw : null) },
33
+ };
34
+ // The groups, the bases each offers (the first is the datasheet's usual one) and the term its chip uses.
35
+ const FL_RX_GROUPS = {
36
+ epoxy: { label: 'Epoxy', bases: ['eew', 'mmol', 'f'], term: 'eew' },
37
+ amineH: { label: 'Amine H (active H)', bases: ['ahew', 'mmol', 'f'], term: 'ahew' },
38
+ oh: { label: 'Hydroxyl', bases: ['ohv', 'eqw', 'mmol', 'f'], term: 'ohv' },
39
+ nco: { label: 'Isocyanate', bases: ['ncopct', 'eqw', 'mmol', 'f'], term: 'ncopct' },
40
+ cooh: { label: 'Carboxyl', bases: ['av', 'mmol', 'f'], term: 'av' },
41
+ amine: { label: 'Amine (basic N)', bases: ['amv', 'mmol', 'f'], term: 'amv' },
42
+ sih: { label: 'Si-H', bases: ['mmol', 'eqw', 'f'], term: 'mmol' },
43
+ vinyl: { label: 'Vinyl', bases: ['mmol', 'eqw', 'f'], term: 'mmol' },
44
+ // Water reacts with NCO (foams, moisture cure; Jun 27 Oct: "later preset", built 28 Oct). `h2o`, not `water`: food
45
+ // workspaces keep a custom field called water.
46
+ h2o: { label: 'Water (reacts with NCO)', bases: ['wpct', 'mmol'], term: 'wpct' },
47
+ };
48
+ const FL_RX_GROUP_KEYS = Object.keys(FL_RX_GROUPS);
49
+ // The datasheet terms the ingredient view and Smart search expose (null when the ingredient has none).
50
+ const FL_RX_TERMS = { eew: 'epoxy', ahew: 'amineH', ohv: 'oh', ncoPct: 'nco', av: 'cooh', amineValue: 'amine' };
51
+
52
+ // The pairs that react. index = 100 × Σ num eq / Σ den eq. `preset` names the Params preset with the same formula.
53
+ const FL_RX_PAIRS = [
54
+ { key: 'epoxy:amineH', label: 'Amine H : epoxy', num: ['amineH'], den: ['epoxy'], numLabel: 'amine H', denLabel: 'epoxy', preset: 'Amine H : epoxy index' },
55
+ { key: 'nco:oh', label: 'Isocyanate index', num: ['nco'], den: ['oh', 'amineH', 'cooh'], numLabel: 'NCO', denLabel: 'OH + NH + COOH', preset: 'Isocyanate index' },
56
+ { key: 'sih:vinyl', label: 'Si-H : vinyl', num: ['sih'], den: ['vinyl'], numLabel: 'Si-H', denLabel: 'vinyl', preset: 'Si-H : vinyl index' },
57
+ // Shown only when the formula holds water: the index foams and moisture-cure systems are set by.
58
+ { key: 'nco:ohw', label: 'Isocyanate index (with water)', num: ['nco'], den: ['oh', 'amineH', 'cooh', 'h2o'], needs: ['h2o'], numLabel: 'NCO', denLabel: 'OH + NH + COOH + water', preset: 'Isocyanate index (with water)' },
59
+ { key: 'amine:cooh', label: 'Neutralization', num: ['amine'], den: ['cooh'], numLabel: 'amine', denLabel: 'COOH', preset: 'Degree of neutralization', unit: '%' },
60
+ ];
61
+
62
+ // ---- Numbers ----
63
+ function _flRxNum(v) { const n = typeof v === 'number' ? v : parseFloat(v); return Number.isFinite(n) ? n : null; }
64
+ // 187 · 42.6 · 5.35 · 0.0267: three significant figures, whole numbers from 100 up.
65
+ function flRxFmt(v) {
66
+ if (v == null || !Number.isFinite(v)) return '—';
67
+ if (Math.abs(v) >= 100) return String(Math.round(v));
68
+ return String(+v.toPrecision(3));
69
+ }
70
+ function flRxFmtIndex(v) { return (v == null || !Number.isFinite(v)) ? '—' : String(Math.round(v * 10) / 10); }
71
+
72
+ // meq/g of one stored group row, or null when it can't be worked out (no value, or `f` without an MW).
73
+ function flRxMeq(entry, mw) {
74
+ if (!entry) return null;
75
+ const b = FL_RX_BASES[entry.basis], v = _flRxNum(entry.value);
76
+ if (!b || v == null || v <= 0) return null;
77
+ const m = b.toMeq(v, _flRxNum(mw));
78
+ return (m != null && Number.isFinite(m) && m > 0) ? m : null;
79
+ }
80
+ // Every group of an ingredient in meq/g (absent groups left out). One row per group; a second is ignored.
81
+ const FL_RX_WATER_CAS = '7732-18-5';
82
+ function flRxIngMeq(ing) {
83
+ const out = {};
84
+ // Water itself counts without being told (a foam's blowing water); a stored h2o row still wins.
85
+ if (ing && String(ing.cas || '').trim() === FL_RX_WATER_CAS && !((ing.reactiveGroups || []).some(g => g && g.group === 'h2o'))) out.h2o = FL_RX_BASES.wpct.toMeq(100);
86
+ ((ing && ing.reactiveGroups) || []).forEach(g => {
87
+ if (!g || !FL_RX_GROUPS[g.group] || out[g.group] != null) return;
88
+ const m = flRxMeq(g, ing.mw);
89
+ if (m != null) out[g.group] = m;
90
+ });
91
+ return out;
92
+ }
93
+ // The group in its datasheet's own terms: EEW 187 g/eq, OHV 112, NCO 21.8 %, Si-H 7.5 mmol/g.
94
+ function flRxTermText(group, meq) {
95
+ const g = FL_RX_GROUPS[group], b = g && FL_RX_BASES[g.term];
96
+ if (!b || meq == null) return '';
97
+ const v = flRxFmt(b.fromMeq(meq));
98
+ if (g.term === 'mmol') return `${g.label} ${flRxFmt(meq)} mmol/g`;
99
+ return `${b.short} ${v}${b.unit ? ' ' + b.unit : ''}`;
100
+ }
101
+ // For the ingredient view: the meq/g fields (0 when absent) and the datasheet terms (null when absent).
102
+ function flRxViewFields(ing) { return _flRxFieldsFromMeq(flRxIngMeq(ing)); }
103
+ function _flRxFieldsFromMeq(meq) {
104
+ const out = {};
105
+ FL_RX_GROUP_KEYS.forEach(k => { out[k] = meq[k] || 0; });
106
+ Object.entries(FL_RX_TERMS).forEach(([t, grp]) => {
107
+ const b = FL_RX_BASES[FL_RX_GROUPS[grp].term];
108
+ out[t] = meq[grp] != null ? +b.fromMeq(meq[grp]).toPrecision(4) : null;
109
+ });
110
+ return out;
111
+ }
112
+ // A sub-formula row's groups (step 4, Jun 28 Oct): its own composition's meq/g, weighted by mass, so a premix or a
113
+ // kit's Part A / Part B counts. Nested premixes roll up through _tpBuildRows; a cycle reads as no groups. Cached for
114
+ // the current task only (a Solve re-reads the same premix 80 times; the next edit is a new task).
115
+ const _flRxSubStack = new Set();
116
+ let _flRxSubCache = null;
117
+ function flRxSubViewFields(sub) {
118
+ if (!sub || !sub.id || _flRxSubStack.has(sub.id)) return _flRxFieldsFromMeq({});
119
+ if (!_flRxSubCache) { _flRxSubCache = new Map(); Promise.resolve().then(() => { _flRxSubCache = null; }); }
120
+ if (_flRxSubCache.has(sub.id)) return { ..._flRxSubCache.get(sub.id) };
121
+ _flRxSubStack.add(sub.id);
122
+ try {
123
+ const rows = _flRxRows(sub.composition);
124
+ const total = rows.reduce((t, r) => t + (r.amount > 0 ? r.amount : 0), 0);
125
+ const meq = {};
126
+ if (total > 0) FL_RX_GROUP_KEYS.forEach(g => {
127
+ let t = 0;
128
+ rows.forEach(r => { const m = r && r.ing ? _flRxNum(r.ing[g]) : null; if (m) t += r.amount * m; });
129
+ if (t > 0) meq[g] = t / total;
130
+ });
131
+ const out = _flRxFieldsFromMeq(meq);
132
+ _flRxSubCache.set(sub.id, out);
133
+ return { ...out };
134
+ } finally { _flRxSubStack.delete(sub.id); }
135
+ }
136
+
137
+ // ---- The ingredient's chips (detail page, list column) ----
138
+ function flRxChipsHtml(ing) {
139
+ const meq = flRxIngMeq(ing);
140
+ const rows = ((ing && ing.reactiveGroups) || []).filter(g => g && meq[g.group] != null);
141
+ if (!rows.length) return '';
142
+ return rows.map(g => {
143
+ const how = g.basis === 'f' ? `MW ${_flRxNum(ing.mw)} × ${_flRxNum(g.value)} per molecule · ` : ''; // the MW as recorded (170.3), not rounded
144
+ return `<span class="fl-rx-chip" title="${esc(FL_RX_GROUPS[g.group].label)}: ${esc(how)}${flRxFmt(meq[g.group])} meq/g">${esc(flRxTermText(g.group, meq[g.group]))}</span>`;
145
+ }).join('');
146
+ }
147
+ function flRxListText(ing) {
148
+ const meq = flRxIngMeq(ing);
149
+ return Object.keys(meq).map(k => flRxTermText(k, meq[k])).join(' · ');
150
+ }
151
+
152
+ // ---- A composition's pairs and index ----
153
+ // Rows as the Reactive presets see them (a sub-formula row carries its own composition's groups: flRxSubViewFields).
154
+ function _flRxRows(comp) { return typeof _tpBuildRows === 'function' ? _tpBuildRows(comp || []) : []; }
155
+ function _flRxSum(rows, groups) {
156
+ let s = 0;
157
+ rows.forEach(r => { if (!r || !r.ing) return; groups.forEach(g => { const m = _flRxNum(r.ing[g]); if (m) s += r.amount * m; }); });
158
+ return s / 1000; // eq per Σ amount (per 100 g when the rows are wt%)
159
+ }
160
+ function flRxEval(pair, rows) {
161
+ const num = _flRxSum(rows, pair.num), den = _flRxSum(rows, pair.den);
162
+ return { num, den, index: den > 0 ? 100 * num / den : null };
163
+ }
164
+ // One basis or the index means nothing: % rows next to grams, or mL without a density, don't share a unit.
165
+ function _flRxUnitBasis(u) { u = String(u || '').trim().toLowerCase(); return /^(wt\s*%|%|w\/w|%\s*w\/w|w\/w\s*%)$/.test(u) ? '%' : u; }
166
+ // Two checks: the rows as typed (% beside g, which _tpBuildRows turns into one wt% set), and as built (mL it couldn't
167
+ // convert for want of a density). A row with no unit takes any.
168
+ function flRxMixedUnits(comp) {
169
+ const abs = u => (typeof isMassUnit === 'function' && isMassUnit(u)) || (typeof isVolUnit === 'function' && isVolUnit(u));
170
+ const typed = new Set((comp || []).filter(c => c && (c.ingredientId || c.formulationId) && _flRxNum(c.amount) > 0)
171
+ .map(c => (abs(c.unit) ? 'abs' : _flRxUnitBasis(c.unit))).filter(Boolean));
172
+ if (typed.size > 1) return true;
173
+ return new Set(_flRxRows(comp).filter(r => r && r.amount > 0).map(r => _flRxUnitBasis(r.unit)).filter(Boolean)).size > 1;
174
+ }
175
+ // The pairs a composition holds: both sides present.
176
+ function flRxPairsFor(comp) {
177
+ const rows = _flRxRows(comp);
178
+ return FL_RX_PAIRS.map(p => ({ pair: p, ...flRxEval(p, rows) })).filter(x => x.num > 0 && x.den > 0 && (!x.pair.needs || _flRxSum(rows, x.pair.needs) > 0));
179
+ }
180
+ function flRxFormulaOn(f) { return !!flRxEqGroups(f); } // the eq column
181
+ function flRxTarget(f, key) { return ((f && f.reactiveTargets) || []).find(t => t && t.pair === key) || null; }
182
+ // 'ok' inside the band, 'off' outside, '' with no target (no color, Jun 27 Oct).
183
+ function flRxBand(index, t) {
184
+ if (!t || index == null || !Number.isFinite(_flRxNum(t.index))) return '';
185
+ return Math.abs(index - t.index) <= (_flRxNum(t.tol) || 0) + 1e-9 ? 'ok' : 'off';
186
+ }
187
+ function _flRxTargetText(t) { return t ? `target ${flRxFmtIndex(+t.index)}${_flRxNum(t.tol) ? ' ± ' + flRxFmtIndex(+t.tol) : ''}` : ''; }
188
+ // A 2K kit: a formula whose rows are all sub-formulas (Part A, Part B …). Its mix ratio, the first part = 100: by
189
+ // weight, and by volume when every part has a density (the parts' planning densities).
190
+ function flRxKitRatio(comp) {
191
+ const parts = (comp || []).filter(c => c && (c.ingredientId || c.formulationId));
192
+ if (parts.length < 2 || !parts.every(c => c.formulationId)) return null;
193
+ const rows = _flRxRows(comp).filter(r => r && r.ing && r.ing._isSubFormula);
194
+ if (rows.length !== parts.length || !(rows[0].amount > 0)) return null;
195
+ const subs = parts.map(c => (db.formulations || []).find(g => g.id === c.formulationId));
196
+ const dens = subs.map(g => (g && typeof _rolledUpDensity === 'function') ? _rolledUpDensity(g) : null);
197
+ const vol = dens.every(d => d > 0) ? rows.map((r, i) => r.amount / dens[i]) : null;
198
+ return {
199
+ names: subs.map((g, i) => (g && (g.name || g.uid)) || `Part ${String.fromCharCode(65 + i)}`),
200
+ weight: rows.map(r => 100 * r.amount / rows[0].amount),
201
+ volume: vol ? vol.map(v => 100 * v / vol[0]) : null,
202
+ };
203
+ }
204
+ function _flRxRatioText(list) { return list.map((x, i) => (i ? flRxFmtIndex(x) : '100')).join(' : '); }
205
+ function flRxKitHtml(comp, prefix) {
206
+ const k = flRxKitRatio(comp);
207
+ if (!k) return '';
208
+ return `<span class="fl-rx-kit" title="${esc(k.names.join(' : '))}"><span class="fl-rx-name">${esc(prefix || 'Mix ratio')}</span> <b>${_flRxRatioText(k.weight)}</b> by weight${k.volume ? ` <span class="fl-rx-dim">· ${_flRxRatioText(k.volume)} by volume</span>` : ''}</span>`;
209
+ }
210
+
211
+ // The groups taking part in a composition's reacting pairs (IPDA's amine value is no part of an epoxy balance).
212
+ function flRxActiveGroups(comp) { return new Set(flRxPairsFor(comp).flatMap(x => [...x.pair.num, ...x.pair.den])); }
213
+ // The eq column's groups, or null for none. A reacting pair: its groups. A part on its own (Part A, a hardener): the
214
+ // groups its kits react, or else every group it holds bar water (Jun, 29 Oct).
215
+ const _FL_RX_PAIR_GROUPS = new Set(FL_RX_PAIRS.flatMap(p => [...p.num, ...p.den]).filter(g => g !== 'h2o'));
216
+ function flRxEqGroups(f) {
217
+ if (!f || flRxMixedUnits(f.composition)) return null;
218
+ const active = flRxActiveGroups(f.composition);
219
+ if (active.size) return active;
220
+ const held = new Set();
221
+ _flRxRows(f.composition).forEach(r => { if (r && r.ing) _FL_RX_PAIR_GROUPS.forEach(g => { if (_flRxNum(r.ing[g]) > 0) held.add(g); }); });
222
+ if (!held.size) return null;
223
+ const kit = new Set();
224
+ if (f.id) (db.formulations || []).forEach(p => {
225
+ if (p && p.id !== f.id && (p.composition || []).some(c => c && c.formulationId === f.id))
226
+ flRxActiveGroups(p.composition).forEach(g => { if (held.has(g)) kit.add(g); });
227
+ });
228
+ return kit.size ? kit : held;
229
+ }
230
+ // Each composition row's equivalents, by its index in the composition: [{ eq, group }] (the eq column),
231
+ // only for `groups` when given.
232
+ function flRxRowEq(comp, groups) {
233
+ const rows = _flRxRows(comp), out = new Map();
234
+ let k = 0;
235
+ (comp || []).forEach((c, i) => {
236
+ if (!c || !(c.ingredientId || c.formulationId)) return;
237
+ const r = rows[k++];
238
+ if (!r || !r.ing) return;
239
+ const list = FL_RX_GROUP_KEYS.filter(g => !groups || groups.has(g))
240
+ .map(g => { const meq = _flRxNum(r.ing[g]) || 0; return { group: g, eq: r.amount * meq / 1000, amount: r.amount, meq }; }).filter(x => x.eq > 0 && Number.isFinite(x.eq));
241
+ if (list.length) out.set(i, list);
242
+ });
243
+ return out;
244
+ }
245
+ // A sub-formula's rows under its parent row (the expand): each row's share of the parent row's eq, by composition
246
+ // index. `parentAmount` is the parent row as the eq column counts it (g, or wt% of the parent).
247
+ function flRxSubRowEq(sub, parentAmount, groups) {
248
+ const out = new Map();
249
+ const total = sub ? _flRxRows(sub.composition).reduce((t, r) => t + (r && r.amount > 0 ? r.amount : 0), 0) : 0;
250
+ if (!(parentAmount > 0) || !(total > 0)) return out;
251
+ const k = parentAmount / total;
252
+ flRxRowEq(sub.composition, groups).forEach((list, i) => out.set(i, list.map(x => ({ ...x, eq: x.eq * k, amount: x.amount * k }))));
253
+ return out;
254
+ }
255
+ const _FL_RX_SHORT = { epoxy: 'epoxy', amineH: 'amine H', oh: 'OH', nco: 'NCO', cooh: 'COOH', amine: 'amine', sih: 'Si-H', vinyl: 'vinyl', h2o: 'water' };
256
+ function flRxEqCellHtml(list) {
257
+ if (!list || !list.length) return '<span class="fl-rx-dim">—</span>';
258
+ // The arithmetic on hover (Jun, 28 Oct): 14.6 g × 23.5 meq/g = 0.343 eq (AHEW 42.6 g/eq). The TOTAL cell has no amount.
259
+ const tip = x => (x.amount != null ? `${flRxFmt(x.amount)} g × ${flRxFmt(x.meq)} meq/g = ${x.eq.toFixed(3)} eq (${flRxTermText(x.group, x.meq)})` : `Σ ${_FL_RX_SHORT[x.group]} = ${x.eq.toFixed(3)} eq per 100 g`);
260
+ // Two columns (Jun, 28 Oct: "epoxy and amine H should align by the number"): the numbers right-aligned, the group
261
+ // in a fixed-width column after them, so every row's numbers line up whatever the group's name.
262
+ return `<span class="fl-rx-eqs">${list.map(x => `<span class="fl-rx-eq" title="${esc(tip(x))}">${x.eq.toFixed(3)}</span><i title="${esc(tip(x))}">${esc(_FL_RX_SHORT[x.group])}</i>`).join('')}</span>`;
263
+ }
264
+
265
+ // ---- The formula's balance strip (Composition tab) ----
266
+ const _flRxSolveOpen = {}; // fId → { pair, row: composition index, tag }
267
+ function flRxStripHtml(f) {
268
+ if (!f) return '';
269
+ const found = flRxPairsFor(f.composition);
270
+ if (!found.length) return '';
271
+ const pro = typeof hasFeature !== 'function' || hasFeature('reactive.solve');
272
+ const kit = flRxKitHtml(f.composition, '');
273
+ if (flRxMixedUnits(f.composition)) return `<div class="fl-rx-strip" id="fl-rx-strip-${esc(f.id)}"><span class="fl-rx-kicker">Reactive balance</span><span class="fl-rx-warn">Rows in different units (% and g, or mL without a density): put them on one basis for an index.</span></div>`;
274
+ const chips = found.map(({ pair, num, den, index }) => {
275
+ const t = flRxTarget(f, pair.key), band = flRxBand(index, t);
276
+ return `<div class="fl-rx-pair${band ? ' is-' + band : ''}" data-rx-pair="${esc(pair.key)}">
277
+ <span class="fl-rx-name">${esc(pair.label)}</span>
278
+ <span class="fl-rx-idx">${/^nco:/.test(pair.key) ? '' : 'index '}<b>${flRxFmtIndex(index)}</b>${pair.unit ? ' ' + pair.unit : ''}</span>
279
+ <span class="fl-rx-dim" title="Equivalents per 100 g of formula: ${esc(pair.numLabel)} / ${esc(pair.denLabel)}">${num.toFixed(3)} / ${den.toFixed(3)} eq</span>
280
+ <button type="button" class="fl-rx-target${t ? ' is-set' : ''}" onclick="flRxOpenTarget('${escJsAttr(f.id)}','${escJsAttr(pair.key)}')" title="${t ? 'Change or clear the target' : 'Set a target index; the strip turns green inside it, amber outside'}">${t ? esc(_flRxTargetText(t)) : '+ target'}</button>
281
+ <button type="button" class="btn btn-secondary btn-sm fl-rx-solve-btn" onclick="${pro ? `flRxOpenSolve('${escJsAttr(f.id)}','${escJsAttr(pair.key)}')` : `proUpsell('reactive.solve')`}" title="Work out the amount that hits a target index">Solve…${pro ? '' : ' <span class="fl-pro" aria-hidden="true"></span>'}</button>
282
+ </div>`;
283
+ }).join('');
284
+ const open = _flRxSolveOpen[f.id];
285
+ const solve = open && found.some(x => x.pair.key === open.pair) ? _flRxSolveRowHtml(f, open) : '';
286
+ return `<div class="fl-rx-strip" id="fl-rx-strip-${esc(f.id)}"><span class="fl-rx-kicker">Reactive balance</span>${chips}${kit}</div>${solve}`;
287
+ }
288
+ // formulations.js holds the strip in #fl-rx-wrap-<id>; a target or the Solve row redraws only that.
289
+ function flRxStripWrapHtml(f) { return f ? `<div class="fl-rx-wrap" id="fl-rx-wrap-${esc(f.id)}">${flRxStripHtml(f)}</div>` : ''; }
290
+ function _flRxRefreshStrip(fId) {
291
+ const el = document.getElementById('fl-rx-wrap-' + fId), f = typeof getFormulation === 'function' ? getFormulation(fId) : null;
292
+ if (el && f) el.innerHTML = flRxStripHtml(f);
293
+ }
294
+
295
+ // ---- Target (from the chip) ----
296
+ function flRxOpenTarget(fId, key) {
297
+ const f = getFormulation(fId), pair = FL_RX_PAIRS.find(p => p.key === key);
298
+ if (!f || !pair) return;
299
+ const t = flRxTarget(f, key);
300
+ showModal(`Target · ${pair.label}`, `
301
+ <div class="form-grid" style="grid-template-columns:1fr 1fr;gap:12px">
302
+ <div class="form-group"><label for="fl-rx-t-index">Index</label><input id="fl-rx-t-index" type="number" step="any" min="0" value="${esc(t ? String(t.index) : '100')}"></div>
303
+ <div class="form-group"><label for="fl-rx-t-tol">± band</label><input id="fl-rx-t-tol" type="number" step="any" min="0" value="${esc(t && t.tol != null ? String(t.tol) : '5')}"></div>
304
+ </div>
305
+ <p class="fl-rx-note">Green inside the band, amber outside. Batches of this formula use it too.</p>
306
+ ${t ? `<button type="button" class="btn btn-secondary btn-sm" onclick="flRxSaveTarget('${escJsAttr(fId)}','${escJsAttr(key)}',true)">Clear target</button>` : ''}`,
307
+ () => flRxSaveTarget(fId, key, false), false, null, 'Save target');
308
+ }
309
+ function flRxSaveTarget(fId, key, clear) {
310
+ const f = getFormulation(fId);
311
+ if (!f) return false;
312
+ let list = ((f.reactiveTargets || []).filter(t => t && t.pair !== key));
313
+ if (!clear) {
314
+ const idx = _flRxNum((document.getElementById('fl-rx-t-index') || {}).value), tol = _flRxNum((document.getElementById('fl-rx-t-tol') || {}).value);
315
+ if (idx == null || idx <= 0) { toast('Enter a target index above 0.'); return false; }
316
+ list = list.concat([{ pair: key, index: idx, tol: tol != null && tol >= 0 ? tol : 0 }]);
317
+ }
318
+ const pair = FL_RX_PAIRS.find(p => p.key === key);
319
+ updateFormulation(fId, { reactiveTargets: list.length ? list : undefined, versionNote: `${clear ? 'Cleared' : 'Set'} the ${pair ? pair.label : 'reactive'} target` });
320
+ if (clear && typeof closeModal === 'function') closeModal();
321
+ _flRxRefreshStrip(fId);
322
+ return true;
323
+ }
324
+
325
+ // ---- Solve (Pro): the amount of one row that hits a target index ----
326
+ // The rows that carry the pair's groups can be solved for.
327
+ function _flRxSolvableRows(f, pair) {
328
+ const eq = flRxRowEq(f.composition), want = new Set([...pair.num, ...pair.den]);
329
+ return [...eq.entries()].filter(([, list]) => list.some(x => want.has(x.group))).map(([i]) => i);
330
+ }
331
+ function _flRxQsIdx(comp) { const qs = typeof QS_ROLE !== 'undefined' ? QS_ROLE : 'Balance (q.s.)'; return (comp || []).findIndex(c => c && c.role === qs); }
332
+ // "Keep the total" moves the q.s. row by the same amount, so only when both rows are in one unit.
333
+ function _flRxQsFor(comp, row) { const qi = _flRxQsIdx(comp); return qi >= 0 && qi !== row && String((comp[qi] || {}).unit || '') === String((comp[row] || {}).unit || '') ? qi : -1; }
334
+ function _flRxIndexWith(comp, pair) { return flRxEval(pair, _flRxRows(comp)).index; }
335
+ // Pure: the amount of comp[rowIdx] (and the q.s. row's, when keepQs) at which the index is `target`.
336
+ // The index is a ratio, so it moves one way as one row's amount grows: a bisection finds it, through the same rows
337
+ // (units, densities, wt% basis) the strip reads.
338
+ function flRxSolve(comp, pairKey, rowIdx, target, keepQs) {
339
+ const run = () => _flRxSolveCalc(comp, pairKey, rowIdx, target, keepQs);
340
+ return typeof _tpWithSubMemo === 'function' ? _tpWithSubMemo(run) : run();
341
+ }
342
+ function _flRxSolveCalc(comp, pairKey, rowIdx, target, keepQs) {
343
+ const pair = FL_RX_PAIRS.find(p => p.key === pairKey), row = (comp || [])[rowIdx];
344
+ if (!pair || !row || !(target > 0)) return { error: 'bad' };
345
+ const a0 = _flRxNum(row.amount) || 0, qi = keepQs ? _flRxQsFor(comp, rowIdx) : -1;
346
+ const q0 = qi >= 0 ? (_flRxNum(comp[qi].amount) || 0) : 0;
347
+ const withA = a => comp.map((c, i) => (i === rowIdx ? { ...c, amount: a } : (i === qi && qi !== rowIdx ? { ...c, amount: q0 - (a - a0) } : c)));
348
+ const g = a => { const v = _flRxIndexWith(withA(a), pair); return v == null ? NaN : v - target; };
349
+ let lo = 0, hi = Math.max(a0, 1) * 2, glo = g(lo), ghi = g(hi);
350
+ if (!Number.isFinite(glo)) { lo = Math.max(a0, 1) * 1e-6; glo = g(lo); }
351
+ let grow = 0, qsOut = false;
352
+ while (Number.isFinite(glo) && Number.isFinite(ghi) && glo * ghi > 0 && grow++ < 40) { hi *= 2; ghi = g(hi); if (qi >= 0 && q0 - (hi - a0) < 0) { qsOut = true; break; } }
353
+ if (!(Number.isFinite(glo) && Number.isFinite(ghi)) || glo * ghi > 0) return { error: qsOut ? 'qs' : 'unreachable' };
354
+ for (let i = 0; i < 80; i++) { const mid = (lo + hi) / 2, gm = g(mid); if (!Number.isFinite(gm)) break; if (gm * glo > 0) { lo = mid; glo = gm; } else hi = mid; }
355
+ // As many decimals as typed (at least 2), and enough for 3 significant figures: 0.178 g, not 0.18 (index 101).
356
+ const mid = (lo + hi) / 2, sig = mid > 0 ? Math.min(6, Math.ceil(-Math.log10(mid)) + 2) : 0;
357
+ const dec = Math.max(2, ((String(row.amount).split('.')[1]) || '').length, sig);
358
+ const a = +mid.toFixed(dec);
359
+ const qs = qi >= 0 && qi !== rowIdx ? +(q0 - (a - a0)).toFixed(dec) : null;
360
+ if (qs != null && qs < 0) return { error: 'qs' };
361
+ return { amount: a, from: a0, qsIdx: qi >= 0 && qi !== rowIdx ? qi : -1, qsAmount: qs, qsFrom: q0, index: _flRxIndexWith(withA(a), pair) };
362
+ }
363
+ function flRxOpenSolve(fId, key) {
364
+ const f = getFormulation(fId), pair = FL_RX_PAIRS.find(p => p.key === key);
365
+ if (!f || !pair) return;
366
+ if (_flRxSolveOpen[fId] && _flRxSolveOpen[fId].pair === key) { delete _flRxSolveOpen[fId]; _flRxRefreshStrip(fId); return; }
367
+ const rows = _flRxSolvableRows(f, pair);
368
+ // Default: the hardener / isocyanate side (the row people usually adjust), else the first.
369
+ const num = rows.find(i => (flRxRowEq(f.composition).get(i) || []).some(x => pair.num.includes(x.group)));
370
+ const row = num != null ? num : rows[0];
371
+ const t = flRxTarget(f, key);
372
+ _flRxSolveOpen[fId] = { pair: key, row, tag: typeof flRowTag === 'function' ? flRowTag(f.composition, row) : '', target: t ? +t.index : 100, keepQs: _flRxQsIdx(f.composition) >= 0 };
373
+ _flRxRefreshStrip(fId);
374
+ }
375
+ function _flRxRowName(c) {
376
+ if (!c) return 'a row';
377
+ const r = c.formulationId ? (db.formulations || []).find(x => x.id === c.formulationId) : (db.ingredients || []).find(x => x.id === c.ingredientId);
378
+ return r ? (r.name || r.uid) : 'a row'; // a kit's Part A / Part B is a sub-formula row
379
+ }
380
+ function _flRxSolveRowHtml(f, st) {
381
+ const pair = FL_RX_PAIRS.find(p => p.key === st.pair), comp = f.composition || [];
382
+ const rows = _flRxSolvableRows(f, pair), qi = _flRxQsFor(comp, st.row);
383
+ const r = flRxSolve(comp, st.pair, st.row, st.target, st.keepQs && qi >= 0);
384
+ const c = comp[st.row] || {}, unit = esc(c.unit || '');
385
+ let out, ok = false;
386
+ if (r.error === 'unreachable') out = `<span class="fl-rx-warn">${esc(_flRxRowName(c))} alone can’t reach ${flRxFmtIndex(st.target)}.</span>`;
387
+ else if (r.error === 'qs') out = '<span class="fl-rx-warn">The q.s. row would go below 0.</span>';
388
+ else if (r.error) out = '<span class="fl-rx-warn">Enter a target above 0.</span>';
389
+ else {
390
+ const d = r.amount - r.from, lo = _flRxNum(c.minAmount), hi = _flRxNum(c.maxAmount);
391
+ const outRange = (lo != null && r.amount < lo) || (hi != null && r.amount > hi);
392
+ const total = comp.reduce((s, x, i) => s + (i === st.row ? r.amount : i === r.qsIdx ? r.qsAmount : (_flRxNum(x.amount) || 0)), 0);
393
+ // The amounts as typed (18.05 → 20.06), not rounded to three figures: both sides of the arrow read alike.
394
+ out = `${esc(_flRxRowName(c))} ${+r.from} → <b>${r.amount}</b> ${unit} <span class="fl-rx-dim">(${d >= 0 ? '+' : ''}${+d.toFixed(4)})</span>`
395
+ + (r.qsIdx >= 0 ? ` <span class="fl-rx-dim">· ${esc(_flRxRowName(comp[r.qsIdx]))} ${+r.qsFrom} → ${r.qsAmount}</span>` : '')
396
+ + ` <span class="fl-rx-dim">· total ${+total.toFixed(2)}</span>`
397
+ + (() => { const k = flRxKitRatio(comp.map((x, i) => (i === st.row ? { ...x, amount: r.amount } : i === r.qsIdx ? { ...x, amount: r.qsAmount } : x))); return k ? ` <span class="fl-rx-dim">· mix ${_flRxRatioText(k.weight)}</span>` : ''; })()
398
+ + (outRange ? ` <span class="fl-rx-warn">outside its range (${lo ?? '…'}–${hi ?? '…'})</span>` : '');
399
+ ok = !outRange;
400
+ }
401
+ const opt = i => `<option value="${i}"${i === st.row ? ' selected' : ''}>${esc(_flRxRowName(comp[i]))}</option>`;
402
+ return `<div class="fl-rx-solve" id="fl-rx-solve-${esc(f.id)}">
403
+ <b>Solve</b>
404
+ <label>index <input type="number" step="any" min="0" value="${esc(String(st.target))}" oninput="_flRxSolveSet('${escJsAttr(f.id)}','target',this.value)" onkeydown="if(event.key==='Enter'&&!event.isComposing)flRxApplySolve('${escJsAttr(f.id)}')"></label>
405
+ <label>by changing <select onchange="_flRxSolveSet('${escJsAttr(f.id)}','row',this.value)">${rows.map(opt).join('')}</select></label>
406
+ <span class="fl-rx-result" id="fl-rx-result-${esc(f.id)}">${out}</span>
407
+ ${qi >= 0 ? `<label class="fl-rx-check"><input type="checkbox"${st.keepQs ? ' checked' : ''} onchange="_flRxSolveSet('${escJsAttr(f.id)}','keepQs',this.checked)"> keep the total (from the q.s. row)</label>` : ''}
408
+ <span class="fl-rx-solve-act">
409
+ <button type="button" class="btn btn-secondary btn-sm" onclick="flRxOpenSolve('${escJsAttr(f.id)}','${escJsAttr(st.pair)}')">Cancel</button>
410
+ <button type="button" class="btn btn-primary btn-sm" onclick="flRxApplySolve('${escJsAttr(f.id)}')"${ok ? '' : ' disabled'}>Apply</button>
411
+ </span>
412
+ </div>`;
413
+ }
414
+ function _flRxSolveSet(fId, k, v) {
415
+ const st = _flRxSolveOpen[fId], f = getFormulation(fId);
416
+ if (!st || !f) return;
417
+ if (k === 'target') st.target = _flRxNum(v) || 0;
418
+ else if (k === 'row') { st.row = +v; st.tag = typeof flRowTag === 'function' ? flRowTag(f.composition, st.row) : ''; }
419
+ else st.keepQs = !!v;
420
+ if (k === 'target') {
421
+ // Typing: redraw only the result and Apply, so the field keeps its caret.
422
+ const tmp = document.createElement('div');
423
+ tmp.innerHTML = _flRxSolveRowHtml(f, st);
424
+ const res = document.getElementById('fl-rx-result-' + fId), btn = document.querySelector(`#fl-rx-solve-${CSS.escape(fId)} .btn-primary`);
425
+ if (res) res.innerHTML = tmp.querySelector('.fl-rx-result').innerHTML;
426
+ if (btn) btn.disabled = tmp.querySelector('.btn-primary').disabled;
427
+ return;
428
+ }
429
+ _flRxRefreshStrip(fId);
430
+ }
431
+ // Apply = a normal composition edit: a version, the undo toast and ↶ ↷ (formulations.js _fmCompUndoToast).
432
+ function flRxApplySolve(fId) {
433
+ const st = _flRxSolveOpen[fId], f = getFormulation(fId);
434
+ if (!st || !f) return;
435
+ const at = typeof flRowAt === 'function' ? flRowAt(f.composition, st.row, st.tag, () => renderFormulationDetail(fId)) : st.row;
436
+ if (at < 0) return;
437
+ const r = flRxSolve(f.composition, st.pair, at, st.target, st.keepQs && _flRxQsFor(f.composition, at) >= 0);
438
+ if (r.error) return;
439
+ const pair = FL_RX_PAIRS.find(p => p.key === st.pair);
440
+ const prev = JSON.parse(JSON.stringify(f.composition || []));
441
+ const comp = f.composition.map((c, i) => (i === at ? { ...c, amount: r.amount } : i === r.qsIdx ? { ...c, amount: r.qsAmount } : c));
442
+ const label = `Solved ${pair.label} ${flRxFmtIndex(st.target)}: ${_flRxRowName(f.composition[at])} ${+r.from} → ${r.amount}`;
443
+ delete _flRxSolveOpen[fId];
444
+ updateFormulation(fId, { composition: comp, versionNote: label });
445
+ renderFormulationDetail(fId);
446
+ if (typeof switchFormTab === 'function') switchFormTab('composition');
447
+ if (typeof _fmCompUndoToast === 'function') _fmCompUndoToast(fId, prev, label);
448
+ }
449
+
450
+ // ---- A batch: as weighed, and (Pro) against the plan ----
451
+ function flRxBatchStripHtml(b) {
452
+ if (!b) return '';
453
+ const f = (db.formulations || []).find(x => x.id === b.formulationId);
454
+ const hasActual = Array.isArray(b.actualComposition) && b.actualComposition.length;
455
+ const comp = hasActual ? b.actualComposition : (f ? f.composition : []);
456
+ const found = flRxPairsFor(comp);
457
+ if (!found.length) return '';
458
+ if (flRxMixedUnits(comp)) return `<div class="fl-rx-strip" id="fl-rx-bstrip-${esc(b.id)}"><span class="fl-rx-kicker">Reactive balance</span><span class="fl-rx-warn">Rows in different units: put them on one basis for an index.</span></div>`;
459
+ const pro = typeof hasFeature !== 'function' || hasFeature('reactive.solve');
460
+ const planned = f && hasActual && !flRxMixedUnits(f.composition) ? flRxPairsFor(f.composition) : [];
461
+ const chips = found.map(({ pair, index }) => {
462
+ const t = flRxTarget(f, pair.key), band = flRxBand(index, t);
463
+ const p = planned.find(x => x.pair.key === pair.key), d = p && p.index != null && index != null ? +flRxFmtIndex(index) - +flRxFmtIndex(p.index) : null; // the difference of the two numbers shown
464
+ const vs = !hasActual ? '<span class="fl-rx-dim">planned (nothing weighed yet)</span>'
465
+ : pro ? (p ? `<span class="fl-rx-dim">planned ${flRxFmtIndex(p.index)}</span> · as weighed <b>${flRxFmtIndex(index)}</b>${d != null && Math.abs(d) >= 0.05 ? ` <span class="fl-rx-delta">${d < 0 ? '▼' : '▲'}${flRxFmtIndex(Math.abs(d))}</span>` : ''}` : `as weighed <b>${flRxFmtIndex(index)}</b>`)
466
+ : `as weighed <b>${flRxFmtIndex(index)}</b> <button type="button" class="fl-rx-target" onclick="proUpsell('reactive.solve')" title="Set it against the plan">vs planned <span class="fl-pro" aria-hidden="true"></span></button>`;
467
+ return `<div class="fl-rx-pair${band && (pro || !hasActual) ? ' is-' + band : ''}" data-rx-pair="${esc(pair.key)}">
468
+ <span class="fl-rx-name">${esc(pair.label)}</span>${!hasActual ? ` <span class="fl-rx-idx"><b>${flRxFmtIndex(index)}</b></span>` : ''}
469
+ <span class="fl-rx-idx">${vs}</span>
470
+ ${t && (pro || !hasActual) ? `<span class="fl-rx-dim">${esc(band === 'off' ? (index < t.index ? 'below ' : 'above ') : '')}${esc(_flRxTargetText(t))}</span>` : ''}
471
+ </div>`;
472
+ }).join('');
473
+ return `<div class="fl-rx-strip" id="fl-rx-bstrip-${esc(b.id)}"><span class="fl-rx-kicker">Reactive balance</span>${chips}${flRxKitHtml(comp, hasActual ? 'Mix as weighed' : 'Mix ratio')}</div>`;
474
+ }
475
+ function flRxRefreshBatchStrip(batchId) {
476
+ const el = document.getElementById('fl-rx-bwrap-' + batchId);
477
+ const b = typeof getBatch === 'function' ? getBatch(batchId) : null;
478
+ if (el && b) el.innerHTML = flRxBatchStripHtml(b);
479
+ }
480
+
481
+ // ---- The ingredient form's Reactive groups section ----
482
+ // The form's picker names the value and the box beside it carries the unit (Jun, 28 Oct: "make this card prettier"),
483
+ // so the unit is said once: AHEW [42.6 g/eq], Amine value [660 mg KOH/g].
484
+ const _FL_RX_FORM_PICK = { eew: 'EEW', ahew: 'AHEW', eqw: 'Equivalent weight', ohv: 'OH number', av: 'Acid value', amv: 'Amine value',
485
+ ncopct: 'NCO content', wpct: 'Water content', mmol: 'Groups per gram', f: 'Groups per molecule' };
486
+ const _FL_RX_FORM_UNIT = { eew: 'g/eq', ahew: 'g/eq', eqw: 'g/eq', ohv: 'mg KOH/g', av: 'mg KOH/g', amv: 'mg KOH/g',
487
+ ncopct: '%', wpct: '%', mmol: 'mmol/g', f: 'per molecule' };
488
+ function _flRxBasisOpts(group, cur) {
489
+ return (FL_RX_GROUPS[group] || FL_RX_GROUPS.epoxy).bases.map(k => `<option value="${k}"${k === cur ? ' selected' : ''}>${esc(_FL_RX_FORM_PICK[k] || FL_RX_BASES[k].label)}</option>`).join('');
490
+ }
491
+ function _flRxFormRowHtml(g) {
492
+ const group = (g && FL_RX_GROUPS[g.group]) ? g.group : 'epoxy';
493
+ const basis = (g && FL_RX_GROUPS[group].bases.includes(g.basis)) ? g.basis : FL_RX_GROUPS[group].bases[0];
494
+ return `<div class="fl-rx-frow">
495
+ <select class="fl-rx-fgroup" aria-label="Group" onchange="_flRxFormGroup(this)">${FL_RX_GROUP_KEYS.map(k => `<option value="${k}"${k === group ? ' selected' : ''}>${esc(FL_RX_GROUPS[k].label)}</option>`).join('')}</select>
496
+ <select class="fl-rx-fbasis" aria-label="Datasheet value" onchange="_flRxFormCalc(this)">${_flRxBasisOpts(group, basis)}</select>
497
+ <label class="fl-rx-fbox"><input class="fl-rx-fval" type="number" step="any" min="0" aria-label="Value" value="${esc(g && g.value != null ? String(g.value) : '')}" oninput="_flRxFormCalc(this)"><span class="fl-rx-funit"></span></label>
498
+ <span class="fl-rx-fconv"></span>
499
+ <button type="button" class="fl-rx-fdel" onclick="_flRxFormRemove(this)" title="Remove this group" aria-label="Remove"><span class="fl-cross" aria-hidden="true"></span></button>
500
+ </div>`;
501
+ }
502
+ function flRxFormSectionHtml(ing) {
503
+ const list = (ing && ing.reactiveGroups) || [];
504
+ return `<div class="fl-rx-form" id="fl-rx-form">
505
+ <div class="fl-rx-frows" id="fl-rx-frows">${list.map(_flRxFormRowHtml).join('')}</div>
506
+ <div class="fl-rx-fhead">
507
+ <button type="button" class="btn btn-secondary btn-sm" onclick="_flRxFormAdd()">+ Add group</button>
508
+ <span class="fl-rx-note" data-tip="EEW for a resin, AHEW for a hardener, OH number for a polyol, NCO % for an isocyanate, acid or amine value; groups per molecule (with the MW) for a pure chemical.">As the datasheet quotes it, or groups per molecule for a pure chemical.</span>
509
+ </div>
510
+ </div>`;
511
+ }
512
+ function _flRxFormAdd() {
513
+ const box = document.getElementById('fl-rx-frows');
514
+ if (!box) return;
515
+ const used = new Set([...box.querySelectorAll('.fl-rx-fgroup')].map(s => s.value));
516
+ box.insertAdjacentHTML('beforeend', _flRxFormRowHtml({ group: FL_RX_GROUP_KEYS.find(k => !used.has(k)) || 'epoxy' }));
517
+ const row = box.lastElementChild;
518
+ _flRxFormCalc(row.querySelector('.fl-rx-fval'));
519
+ row.querySelector('.fl-rx-fval').focus();
520
+ }
521
+ // ✕ takes a row out at once, so it leaves "Removed Amine (basic N) · Undo" in its place; Undo puts the same row back,
522
+ // typed value and all (Jun, 28 Oct). A row with nothing typed just goes. Save and Cancel redraw the form, which ends it.
523
+ const _flRxGone = new Map();
524
+ let _flRxGoneN = 0;
525
+ function _flRxFormRemove(btn) {
526
+ const row = btn && btn.closest('.fl-rx-frow');
527
+ if (!row) return;
528
+ const val = row.querySelector('.fl-rx-fval'), sel = row.querySelector('.fl-rx-fgroup');
529
+ if (!val || String(val.value).trim() === '') { row.remove(); return; }
530
+ const key = String(++_flRxGoneN), name = sel && sel.selectedOptions && sel.selectedOptions[0] ? sel.selectedOptions[0].textContent : 'group';
531
+ const gone = document.createElement('div');
532
+ gone.className = 'fl-rx-fgone';
533
+ gone.setAttribute('data-rx-gone', key);
534
+ gone.innerHTML = `<span>Removed <b>${esc(name)}</b></span><button type="button" class="fl-rx-fundo" onclick="_flRxFormUndo('${key}')">Undo</button>`;
535
+ _flRxGone.set(key, row);
536
+ row.replaceWith(gone);
537
+ const u = gone.querySelector('.fl-rx-fundo');
538
+ if (u && u.focus) u.focus();
539
+ }
540
+ function _flRxFormUndo(key) {
541
+ const row = _flRxGone.get(key), gone = document.querySelector(`[data-rx-gone="${key}"]`);
542
+ _flRxGone.delete(key);
543
+ if (!row || !gone) { if (gone) gone.remove(); return; }
544
+ gone.replaceWith(row);
545
+ _flRxFormCalc(row.querySelector('.fl-rx-fval'));
546
+ const d = row.querySelector('.fl-rx-fdel');
547
+ if (d && d.focus) d.focus();
548
+ }
549
+ function _flRxFormGroup(sel) {
550
+ const row = sel.closest('.fl-rx-frow'), b = row.querySelector('.fl-rx-fbasis');
551
+ b.innerHTML = _flRxBasisOpts(sel.value, FL_RX_GROUPS[sel.value].bases[0]);
552
+ _flRxFormCalc(sel);
553
+ }
554
+ // The conversion under the row: = 5.35 meq/g; with MW × groups also the datasheet term (AHEW 42.6 g/eq).
555
+ function _flRxFormCalc(el) {
556
+ const row = el && el.closest('.fl-rx-frow');
557
+ if (!row) return;
558
+ const group = row.querySelector('.fl-rx-fgroup').value, basis = row.querySelector('.fl-rx-fbasis').value;
559
+ const value = row.querySelector('.fl-rx-fval'), conv = row.querySelector('.fl-rx-fconv'), unit = row.querySelector('.fl-rx-funit');
560
+ value.placeholder = '';
561
+ if (unit) unit.textContent = _FL_RX_FORM_UNIT[basis] || FL_RX_BASES[basis].unit || '';
562
+ const mw = _flRxNum((document.getElementById('f-mw') || {}).value);
563
+ const meq = flRxMeq({ group, basis, value: value.value }, mw);
564
+ conv.className = 'fl-rx-fconv';
565
+ conv.removeAttribute('data-tip');
566
+ if (meq == null) {
567
+ if (basis === 'f' && !(mw > 0) && value.value !== '') { conv.textContent = 'Needs the MW'; conv.className = 'fl-rx-fconv is-warn'; conv.setAttribute('data-tip', 'Enter the molecular weight under Physical Properties.'); }
568
+ else conv.textContent = '';
569
+ return;
570
+ }
571
+ // The chip: the result, and with groups per molecule the datasheet term it stands for. The arithmetic on hover.
572
+ conv.className = 'fl-rx-fconv is-on';
573
+ conv.textContent = basis === 'f' ? `${flRxTermText(group, meq)} · ${flRxFmt(meq)} meq/g` : `${flRxFmt(meq)} meq/g`;
574
+ conv.setAttribute('data-tip', basis === 'f' ? `MW ${mw} ÷ ${value.value} groups → ${flRxTermText(group, meq)}; 1000 ÷ that = ${flRxFmt(meq)} meq/g`
575
+ : `${value.value} ${_FL_RX_FORM_UNIT[basis] || ''} = ${flRxFmt(meq)} meq/g`);
576
+ }
577
+ function flRxFormWire() { document.querySelectorAll('#fl-rx-frows .fl-rx-fval').forEach(_flRxFormCalc); }
578
+ // The rows as stored: valid values only, one per group.
579
+ function flRxFormCollect() {
580
+ const seen = new Set(), out = [];
581
+ document.querySelectorAll('#fl-rx-frows .fl-rx-frow').forEach(row => {
582
+ const group = row.querySelector('.fl-rx-fgroup').value, basis = row.querySelector('.fl-rx-fbasis').value;
583
+ const value = _flRxNum(row.querySelector('.fl-rx-fval').value);
584
+ if (!FL_RX_GROUPS[group] || !FL_RX_BASES[basis] || value == null || value <= 0 || seen.has(group)) return;
585
+ seen.add(group);
586
+ out.push({ group, basis, value });
587
+ });
588
+ return out;
589
+ }
590
+
591
+ // ---- CSV import: datasheet columns → reactiveGroups ----
592
+ const FL_RX_CSV = [
593
+ // A header may carry its unit: "EEW (g/eq)", "OH number [mg KOH/g]", "NCO, %".
594
+ { key: 'rx:eew', label: 'EEW (g/eq)', group: 'epoxy', basis: 'eew', match: /^(eew|epoxy\s*(equivalent\s*weight|eq\.?\s*wt\.?))\s*([(\[,].*)?$/i },
595
+ { key: 'rx:ahew', label: 'AHEW (g/eq)', group: 'amineH', basis: 'ahew', match: /^(ahew|amine\s*h(ydrogen)?\s*(equivalent\s*weight|eq\.?\s*wt\.?))\s*([(\[,].*)?$/i },
596
+ { key: 'rx:ohv', label: 'OH number (mg KOH/g)', group: 'oh', basis: 'ohv', match: /^(ohv|oh\s*(number|value|no\.?)|hydroxyl\s*(number|value))\s*([(\[,].*)?$/i },
597
+ { key: 'rx:nco', label: 'NCO %', group: 'nco', basis: 'ncopct', match: /^(nco\s*%?|nco\s*content|%\s*nco)\s*([(\[,].*)?$/i },
598
+ { key: 'rx:av', label: 'Acid value (mg KOH/g)', group: 'cooh', basis: 'av', match: /^(av|acid\s*(value|number|no\.?))\s*([(\[,].*)?$/i },
599
+ { key: 'rx:amv', label: 'Amine value (mg KOH/g)', group: 'amine', basis: 'amv', match: /^(amine\s*(value|number|no\.?))\s*([(\[,].*)?$/i },
600
+ ];
601
+ // Moves rx:* fields of an import row into reactiveGroups, merged over the existing record's (same group replaced).
602
+ function flRxCsvFold(data, existing) {
603
+ const add = FL_RX_CSV.filter(c => typeof data[c.key] === 'number' && data[c.key] > 0).map(c => ({ group: c.group, basis: c.basis, value: data[c.key] }));
604
+ FL_RX_CSV.forEach(c => { delete data[c.key]; });
605
+ if (!add.length) return data;
606
+ const keep = ((existing && existing.reactiveGroups) || []).filter(g => g && !add.some(a => a.group === g.group));
607
+ data.reactiveGroups = keep.concat(add);
608
+ return data;
609
+ }
610
+
611
+ if (typeof module !== 'undefined' && module.exports) {
612
+ module.exports = { FL_RX_BASES, FL_RX_GROUPS, FL_RX_PAIRS, flRxSubViewFields, flRxKitRatio, flRxMeq, flRxIngMeq, flRxTermText, flRxViewFields, flRxEval, flRxSolve, flRxBand, flRxFmt, flRxCsvFold };
613
+ }