Fix template formatters: expose c.fields by name not ID

c.fields was keyed by generated field IDs, so c.fields?.resistance
was always undefined. Now fields are remapped by name before being
passed to formatters, so the documented API works as expected.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-21 00:15:37 +00:00
parent 64157013ed
commit 896b6fcb39

View File

@@ -90,10 +90,23 @@ function compile_templates() {
} }
} }
// Build a version of the component where c.fields is keyed by field name
// instead of field ID, so formatters can use c.fields?.resistance etc.
function named_fields_comp(comp) {
const fields = {};
for (const [fid, val] of Object.entries(comp.fields ?? {})) {
const def = field_by_id(fid);
if (def) { fields[def.name] = val; }
}
return { ...comp, fields };
}
function component_display_name(comp) { function component_display_name(comp) {
if (!compiled_formatters.length) return comp.name;
const c = named_fields_comp(comp);
for (const { fn } of compiled_formatters) { for (const { fn } of compiled_formatters) {
try { try {
const result = fn(comp); const result = fn(c);
if (result != null && result !== '') return String(result); if (result != null && result !== '') return String(result);
} catch (_) { } catch (_) {
// formatter threw — skip it // formatter threw — skip it
@@ -609,7 +622,7 @@ function update_tmpl_preview() {
try { try {
// eslint-disable-next-line no-new-func // eslint-disable-next-line no-new-func
const fn = new Function('c', `"use strict"; return (${formatter_str})(c);`); const fn = new Function('c', `"use strict"; return (${formatter_str})(c);`);
const result = fn(sample); const result = fn(named_fields_comp(sample));
preview_el.textContent = result != null ? String(result) : `null — falls back to "${sample.name}"`; preview_el.textContent = result != null ? String(result) : `null — falls back to "${sample.name}"`;
} catch (err) { } catch (err) {
preview_el.textContent = `Error: ${err.message}`; preview_el.textContent = `Error: ${err.message}`;