diff --git a/public/app.mjs b/public/app.mjs index 596726e..d06a57f 100644 --- a/public/app.mjs +++ b/public/app.mjs @@ -584,13 +584,15 @@ function open_template_dialog(tmpl = null) { } catch (err) { alert(`Error: ${err.message}`); } }); - // Live preview against first component + // Live preview qs(template_dialog, '#tmpl-formatter').addEventListener('input', update_tmpl_preview); + qs(template_dialog, '#tmpl-test-data').addEventListener('input', update_tmpl_preview); } qs(template_dialog, '.dialog-title').textContent = tmpl ? 'Edit template' : 'Add template'; qs(template_dialog, '#tmpl-name').value = tmpl?.name ?? ''; qs(template_dialog, '#tmpl-formatter').value = tmpl?.formatter ?? ''; + qs(template_dialog, '#tmpl-test-data').value = ''; update_tmpl_preview(); template_dialog_callback = async () => { @@ -617,15 +619,32 @@ function update_tmpl_preview() { const preview_el = qs(template_dialog, '#tmpl-preview'); const formatter_str = qs(template_dialog, '#tmpl-formatter').value.trim(); if (!formatter_str) { preview_el.textContent = '—'; return; } - const sample = all_components[0]; - if (!sample) { preview_el.textContent = '(no components to preview)'; return; } + + // Build the component to preview against + let preview_comp; + const test_data_str = qs(template_dialog, '#tmpl-test-data').value.trim(); + if (test_data_str) { + try { + // eslint-disable-next-line no-new-func + const test_fields = new Function(test_data_str)(); + preview_comp = { name: '(test)', fields: test_fields ?? {} }; + } catch (err) { + preview_el.textContent = `Test data error: ${err.message}`; + return; + } + } else { + const sample = all_components[0]; + if (!sample) { preview_el.textContent = '(no components to preview)'; return; } + preview_comp = named_fields_comp(sample); + } + try { // eslint-disable-next-line no-new-func const fn = new Function('c', `"use strict"; return (${formatter_str})(c);`); - const result = fn(named_fields_comp(sample)); - preview_el.textContent = result != null ? String(result) : `null — falls back to "${sample.name}"`; + const result = fn(preview_comp); + preview_el.textContent = result != null ? String(result) : `null — falls back to "${preview_comp.name}"`; } catch (err) { - preview_el.textContent = `Error: ${err.message}`; + preview_el.textContent = `Formatter error: ${err.message}`; } } diff --git a/public/templates.html b/public/templates.html index 563090f..9fc962f 100644 --- a/public/templates.html +++ b/public/templates.html @@ -184,6 +184,10 @@ +
+ + +
Preview: