Repository navigation
Expand file tree
/
Copy pathplayground.html
More file actions
529 lines (492 loc) · 25.5 KB
/
Copy pathplayground.html
File metadata and controls
529 lines (492 loc) · 25.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Plugin Playground — test any chart plugin on your own data</title>
<!-- Same library globals that data-explorer.html preloads, so plugins that
assume a global (echarts, d3, Chart, Plotly, ...) work here too.
d3 also gives us a CSV parser for the raw-data step. -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js"></script>
<script src="https://cdn.plot.ly/plotly-2.35.2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/apexcharts@3/dist/apexcharts.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/lineupjs@4/build/LineUpJS.css">
<script src="https://cdn.jsdelivr.net/npm/lineupjs@4/build/LineUpJS.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.131.0/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.131.0/examples/js/controls/OrbitControls.js"></script>
<script src="https://cdn.jsdelivr.net/npm/d3@7/dist/d3.min.js"></script>
<style>
:root { --bg:#0f1117; --panel:#1a1d27; --border:#2a2e3a; --text:#e6e8ee; --muted:#8b90a0; --accent:#534AB7; --err:#ff6b6b; --ok:#4caf50; --warn:#f0a840; }
* { box-sizing: border-box; }
body { margin:0; background:var(--bg); color:var(--text); font:14px/1.5 -apple-system,Segoe UI,Roboto,sans-serif; }
header { padding:18px 24px 12px; border-bottom:1px solid var(--border); }
h1 { margin:0 0 4px; font-size:18px; font-weight:600; }
.sub { color:var(--muted); font-size:13px; }
main { display:grid; grid-template-columns: 430px 1fr; gap:0; min-height:calc(100vh - 64px); }
.left { padding:18px 20px; border-right:1px solid var(--border); overflow:auto; }
.right { padding:18px 24px; }
.step { margin-bottom:20px; padding-bottom:18px; border-bottom:1px solid var(--border); }
.step:last-child { border-bottom:0; }
label.cap { display:block; font-size:11px; font-weight:600; text-transform:uppercase; letter-spacing:.05em; color:var(--muted); margin-bottom:6px; }
input[type=file] { font-size:12px; color:var(--text); }
input[type=number] { width:54px; background:#0b0d13; color:var(--text); border:1px solid var(--border); border-radius:4px; padding:3px 6px; font:12px ui-monospace,Consolas,monospace; }
textarea { width:100%; background:#0b0d13; color:#d6e2ff; border:1px solid var(--border); border-radius:6px; padding:10px; font:12px/1.45 ui-monospace,SFMono-Regular,Consolas,monospace; resize:vertical; }
.row { display:flex; gap:8px; align-items:center; flex-wrap:wrap; }
button { background:var(--accent); color:#fff; border:0; border-radius:6px; padding:8px 14px; font-size:13px; cursor:pointer; }
button.ghost { background:transparent; border:1px solid var(--border); color:var(--text); }
button:disabled { opacity:.45; cursor:default; }
.pill { font-size:12px; color:var(--muted); }
.pill b { color:var(--text); }
#stage { background:#fff; border-radius:10px; border:1px solid var(--border); overflow:auto; resize:both; width:100%; height:560px; min-height:200px; min-width:280px; }
#chart { width:100%; height:100%; }
.status { margin-top:10px; font-size:12px; white-space:pre-wrap; font-family:ui-monospace,Consolas,monospace; }
.status.err { color:var(--err); }
.status.ok { color:var(--ok); }
.hint { font-size:12px; color:var(--muted); margin-top:6px; }
code { background:#0b0d13; padding:1px 5px; border-radius:4px; color:#d6e2ff; }
.privacy { background:rgba(76,175,80,.08); border:1px solid rgba(76,175,80,.35); color:#bfe6c2; border-radius:8px; padding:10px 12px; font-size:12px; margin-bottom:18px; }
.privacy b { color:#dff3e0; }
#schemaPreview { margin-top:8px; background:#0b0d13; border:1px solid var(--border); border-radius:6px; padding:8px 10px; font:12px/1.5 ui-monospace,Consolas,monospace; color:#9fd0a3; max-height:150px; overflow:auto; white-space:pre-wrap; display:none; }
.warn { color:var(--warn); }
.chk { font-size:12px; color:var(--muted); display:flex; align-items:center; gap:6px; }
details summary { cursor:pointer; font-size:11px; font-weight:600; text-transform:uppercase; letter-spacing:.05em; color:var(--muted); }
</style>
</head>
<body>
<header>
<h1>Plugin Playground</h1>
<div class="sub">Test any chart plugin on your own raw data — no terminal, no console, no upload. Everything runs in this page.</div>
</header>
<main>
<div class="left">
<div class="privacy">
🔒 <b>Your data never leaves this page.</b> Files you load and text you paste stay in your browser — there are
no network calls here. To convert raw data into a chart spec you generate a prompt that shares only your
<b>column names</b> (which you can edit first), get a small <code>transform()</code> function back from a chatbot,
and run it locally on your real data. Or write the function yourself and skip the chatbot entirely.
</div>
<!-- STEP 1 — plugin -->
<div class="step">
<label class="cap">1 · Plugin file (the visualization, a .json from chart_plugins/)</label>
<input type="file" id="pluginFile" accept=".json,application/json">
<div class="hint" id="pluginInfo">No plugin loaded yet.</div>
</div>
<!-- STEP 2 — raw data -->
<div class="step">
<label class="cap">2 · Your raw data (CSV or JSON) — stays in your browser</label>
<div class="row" style="margin-bottom:8px;">
<input type="file" id="dataFile" accept=".csv,.json,.txt,text/csv,application/json">
<button class="ghost" id="schemaBtn">Derive schema</button>
</div>
<textarea id="rawText" rows="6" spellcheck="false" placeholder="Paste CSV or JSON here, e.g. source,target,bytes 10.0.0.1,10.0.0.2,540 10.0.0.1,10.0.0.5,120 …or a JSON array of row objects."></textarea>
<div id="schemaPreview"></div>
<div class="hint">Click <b>Derive schema</b> to read your columns and types. The actual rows are never shown to the chatbot unless you opt in below.</div>
</div>
<!-- STEP 3 — build prompt -->
<div class="step">
<label class="cap">3 · Build a prompt for any chatbot (shares column names only)</label>
<label class="chk" style="margin-bottom:8px;">
<input type="checkbox" id="includeSamples">
Also include <input type="number" id="sampleN" value="3" min="1" max="20"> sample rows
<span class="warn">(shares real values — leave off for privacy)</span>
</label>
<div class="row" style="margin-bottom:8px;">
<button id="buildPromptBtn">Build chatbot prompt</button>
<button class="ghost" id="copyPromptBtn" disabled>Copy</button>
</div>
<textarea id="promptOut" rows="6" spellcheck="false" placeholder="The generated prompt appears here. Paste it into ChatGPT / Claude / Gemini and copy back the transform() function it returns."></textarea>
</div>
<!-- STEP 4 — transform -->
<div class="step">
<label class="cap">4 · Paste the transform( ) function, then run it locally</label>
<textarea id="transformText" rows="7" spellcheck="false" placeholder="function transform(rows) { // map your rows into the plugin's spec shape return { type: '...', /* ... */ }; }"></textarea>
<div class="row" style="margin-top:8px;">
<button id="applyBtn" disabled>▶ Apply transform & render</button>
</div>
<div class="hint">It receives your parsed data as <code>rows</code> and returns a spec. Runs entirely in this page — read it first if you like.</div>
</div>
<!-- STEP 5 — direct spec (advanced) -->
<div class="step">
<details>
<summary>Advanced · work with a spec directly</summary>
<div style="margin-top:10px;">
<div class="row" style="margin-bottom:8px;">
<button class="ghost" id="exampleBtn" disabled>Demo this plugin</button>
<input type="file" id="specFile" accept=".json,application/json" title="…or load a .json spec file">
</div>
<textarea id="specText" rows="6" spellcheck="false" placeholder='A spec object passed straight to the plugin, e.g. { "type": "gauge", "title": "Demo", "value": 73 }'></textarea>
<div class="hint">SQL-only specs (just a <code>"sql"</code> field) can't run here — use inline data instead.</div>
</div>
</details>
<div class="row" style="margin-top:12px;">
<button id="renderBtn" disabled>▶ Render spec</button>
<span class="pill" id="typePill"></span>
</div>
<div class="status" id="status"></div>
</div>
</div>
<div class="right">
<label class="cap">Output (drag bottom-right corner to resize)</label>
<div id="stage"><div id="chart"></div></div>
</div>
</main>
<script>
const $ = id => document.getElementById(id);
let plugin = null; // parsed plugin JSON
let renderFn = null; // compiled render function
let parsedData = null; // the contributor's raw data, parsed (array of rows, or object) — never sent anywhere
let schema = null; // [{column, type}] or [{key, type}]
let dataKind = null; // 'rows' | 'object'
function setStatus(msg, kind) {
const el = $('status');
el.textContent = msg || '';
el.className = 'status' + (kind ? ' ' + kind : '');
}
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, c =>
({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
}
function readFile(file) {
return new Promise((resolve, reject) => {
const r = new FileReader();
r.onload = () => resolve(r.result);
r.onerror = () => reject(new Error('Could not read file'));
r.readAsText(file);
});
}
// ── Theme helpers ───────────────────────────────────────────────────────────
// Plugin renderScripts expect these globals to exist (they live in
// data-explorer.html). Mirror them here so theme-aware plugins (e.g. dynet3d,
// which calls getThemeColors) render in the playground too.
const CHART_COLORS = [
'#534AB7','#7F77DD','#2E9CDB','#4BC1A8',
'#E8833A','#E85858','#9B59B6','#27AE60','#F39C12','#1ABC9C',
'#3498DB','#E74C3C','#2ECC71','#F1C40F','#8E44AD'
];
function getThemeColors() {
return {
text: '#1a1a18',
text2: '#5a5a56',
grid: 'rgba(0,0,0,0.06)',
edge: 'rgba(30,30,30,0.4)',
};
}
function hexToRgba(hex, alpha) {
const r = parseInt(hex.slice(1, 3), 16);
const g = parseInt(hex.slice(3, 5), 16);
const b = parseInt(hex.slice(5, 7), 16);
return `rgba(${r},${g},${b},${alpha})`;
}
// Returns '#000000' for light backgrounds, '#ffffff' for dark ones (WCAG luminance).
function contrastColor(hex) {
const lin = v => { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); };
const r = lin(parseInt(hex.slice(1,3),16));
const g = lin(parseInt(hex.slice(3,5),16));
const b = lin(parseInt(hex.slice(5,7),16));
return 0.2126*r + 0.7152*g + 0.0722*b > 0.179 ? '#000000' : '#ffffff';
}
// ── Plugin ────────────────────────────────────────────────────────────────
function extractExampleSpec(desc) {
if (!desc) return null;
const candidates = [];
for (let i = 0; i < desc.length; i++) {
if (desc[i] !== '{') continue;
let depth = 0, inStr = false, esc = false;
for (let j = i; j < desc.length; j++) {
const c = desc[j];
if (inStr) {
if (esc) esc = false;
else if (c === '\\') esc = true;
else if (c === '"') inStr = false;
} else if (c === '"') inStr = true;
else if (c === '{') depth++;
else if (c === '}') {
depth--;
if (depth === 0) {
try {
const obj = JSON.parse(desc.slice(i, j + 1));
if (obj && typeof obj === 'object') candidates.push(obj);
} catch (e) { /* not valid JSON, skip */ }
break;
}
}
}
}
const specs = candidates.filter(o => typeof o.type === 'string' && o.type);
if (!specs.length) return null;
const renderable = specs.filter(o => !('sql' in o));
const pool = renderable.length ? renderable : specs;
pool.sort((a, b) => Object.keys(b).length - Object.keys(a).length);
return pool[0];
}
async function loadPlugin(file) {
try {
const text = await readFile(file);
plugin = JSON.parse(text);
if (!plugin.renderScript) throw new Error('This JSON has no "renderScript" field — is it a plugin file?');
renderFn = new Function('return (' + plugin.renderScript + ')')();
if (typeof renderFn !== 'function') throw new Error('renderScript did not compile to a function.');
$('pluginInfo').innerHTML = 'Loaded <b>' + (plugin.type || file.name) + '</b> ✓';
$('pluginInfo').style.color = 'var(--ok)';
$('typePill').innerHTML = 'plugin: <b>' + (plugin.type || '?') + '</b>';
$('exampleBtn').disabled = false;
$('renderBtn').disabled = false;
$('applyBtn').disabled = false;
setStatus('Plugin compiled. For an instant demo, open Advanced ▾ and click “Demo this plugin”. Or bring your data in step 2.', 'ok');
} catch (e) {
plugin = null; renderFn = null;
$('exampleBtn').disabled = true;
$('renderBtn').disabled = true;
$('applyBtn').disabled = true;
// Surface the reason right under the file picker — the bottom status line is easy to miss.
$('pluginInfo').innerHTML = '⚠ Could not load this file: ' + escapeHtml(e.message) +
'<br><span style="color:var(--muted)">It must be a chart plugin whose <code>renderScript</code> compiles to a function.</span>';
$('pluginInfo').style.color = 'var(--err)';
setStatus('Plugin error: ' + e.message, 'err');
}
}
// ── Raw data → schema (all local) ───────────────────────────────────────────
function inferType(v) {
if (v === null || v === undefined || v === '') return 'null';
if (typeof v === 'number') return Number.isFinite(v) ? 'number' : 'string';
if (typeof v === 'boolean') return 'boolean';
if (v instanceof Date) return 'date';
if (Array.isArray(v)) return 'array';
if (typeof v === 'object') return 'object';
return 'string';
}
// Parse the raw-data box into JS. Tries JSON first, then CSV (via d3). The
// parsed result is kept only in memory and is never transmitted.
function parseRawData() {
const raw = $('rawText').value.trim();
if (!raw) throw new Error('No raw data — paste CSV or JSON, or load a file.');
// JSON?
try {
const j = JSON.parse(raw);
parsedData = j;
dataKind = Array.isArray(j) ? 'rows' : 'object';
return;
} catch (e) { /* not JSON, try CSV */ }
// CSV via d3 (autoType infers numbers/dates/booleans)
const rows = d3.csvParse(raw, d3.autoType);
if (!rows || !rows.length || !rows.columns || !rows.columns.length) {
throw new Error('Could not parse as JSON or CSV. Check the format.');
}
parsedData = rows.map(r => Object.assign({}, r)); // drop d3's .columns metadata
dataKind = 'rows';
}
function deriveSchema() {
try {
parseRawData();
} catch (e) {
schema = null;
$('schemaPreview').style.display = 'none';
setStatus(e.message, 'err');
return false;
}
if (dataKind === 'rows') {
const rows = parsedData;
if (!rows.length || typeof rows[0] !== 'object') {
setStatus('Parsed an array, but its items are not row objects. The transform will receive the array as-is.', '');
}
// union of keys across up to 50 rows; type from first non-empty value seen
const cols = [];
const seen = {};
for (let i = 0; i < Math.min(rows.length, 50); i++) {
const r = rows[i]; if (!r || typeof r !== 'object') continue;
for (const k of Object.keys(r)) {
if (!(k in seen)) { seen[k] = 'null'; cols.push(k); }
if (seen[k] === 'null') { const t = inferType(r[k]); if (t !== 'null') seen[k] = t; }
}
}
schema = cols.map(c => ({ column: c, type: seen[c] === 'null' ? 'string' : seen[c] }));
$('schemaPreview').textContent =
(Array.isArray(parsedData) ? parsedData.length : 0) + ' rows · ' + schema.length + ' columns\n' +
schema.map(s => ' ' + s.column + ' : ' + s.type).join('\n');
} else {
// top-level object: describe its keys
const obj = parsedData;
schema = Object.keys(obj).map(k => ({ key: k, type: inferType(obj[k]) }));
$('schemaPreview').textContent =
'object · ' + schema.length + ' keys\n' +
schema.map(s => ' ' + s.key + ' : ' + s.type).join('\n');
}
$('schemaPreview').style.display = 'block';
setStatus('Schema derived locally. Build a prompt in step 3, or write the transform yourself in step 4.', 'ok');
return true;
}
// ── Build the chatbot prompt (column names only, unless samples opted in) ────
function buildPrompt() {
if (!plugin) { setStatus('Load a plugin first (step 1) so the prompt knows the target spec.', 'err'); return; }
if (!schema) { if (!deriveSchema()) return; }
const desc = plugin.promptDescription || '(no promptDescription in this plugin)';
const schemaJson = JSON.stringify(schema, null, 2);
let samplesBlock = '';
if ($('includeSamples').checked && dataKind === 'rows' && Array.isArray(parsedData)) {
const n = Math.max(1, Math.min(20, parseInt($('sampleN').value, 10) || 3));
samplesBlock =
'\nSAMPLE ROWS (real values — included at my discretion):\n' +
JSON.stringify(parsedData.slice(0, n), null, 2) + '\n';
}
const dataDesc = dataKind === 'rows'
? '`rows` is an array of row objects whose keys/types are described by this schema:'
: '`rows` is a single object whose keys/types are described by this schema:';
const prompt =
`I have a chart plugin and some tabular data. Write a JavaScript function that converts my data into a valid spec for the plugin. You will NOT see my data values — only its structure.
PLUGIN DESCRIPTION (defines the spec shape):
${desc}
DATA STRUCTURE — ${dataDesc}
${schemaJson}
${samplesBlock}
TASK:
Write a single self-contained JavaScript function with this exact signature:
function transform(rows) {
// ...
return spec;
}
Requirements:
- Return a spec object valid for the plugin above (match the "Spec:" shape in its description).
- Derive everything from \`rows\` at runtime — do NOT hard-code my data values.
- No external libraries, no fetch/network, no comments needed.
- Output ONLY the function. No prose, no markdown code fences.`;
$('promptOut').value = prompt;
$('copyPromptBtn').disabled = false;
setStatus('Prompt built — it shares ' + (samplesBlock ? 'your column names AND sample rows' : 'your column names only') +
'. Review/edit it, paste into a chatbot, and bring back the function.', samplesBlock ? '' : 'ok');
}
// ── Compile + apply the transform locally ───────────────────────────────────
function compileTransform(text) {
let body = (text || '').trim();
body = body.replace(/^```[a-z]*\s*/i, '').replace(/```\s*$/i, '').trim();
if (!body) return null;
// expression form: function(rows){...} or (rows)=>({...})
try { const f = new Function('return (' + body + ')')(); if (typeof f === 'function') return f; } catch (e) { /* try next */ }
// declaration form: function transform(rows){...}
try {
const f = new Function(body + '\n; return typeof transform === "function" ? transform : null;')();
if (typeof f === 'function') return f;
} catch (e) { /* fall through */ }
return null;
}
function applyTransform() {
if (!renderFn) { setStatus('Load a plugin first.', 'err'); return; }
if (!parsedData) {
try { parseRawData(); } catch (e) { setStatus(e.message, 'err'); return; }
}
const fn = compileTransform($('transformText').value);
if (!fn) { setStatus('Could not compile the transform. It should define function transform(rows){…} (or be a function expression).', 'err'); return; }
let spec;
try {
spec = fn(parsedData);
} catch (e) {
setStatus('transform() threw on your data: ' + (e && e.message ? e.message : e), 'err');
return;
}
if (!spec || typeof spec !== 'object') { setStatus('transform() did not return a spec object.', 'err'); return; }
$('specText').value = JSON.stringify(spec, null, 2);
setStatus('Transform produced a spec locally — rendering…', 'ok');
render();
}
// ── Stage teardown ──────────────────────────────────────────────────────────
// Clearing innerHTML removes the old chart's nodes but leaves the chart-library
// *instance* alive: ApexCharts/ECharts keep a resize observer + window listener
// that still point at the reused #chart element and redraw the old chart back
// into it on the next layout change (that's the "previous chart won't disappear"
// bug). So destroy the known libraries' instances, then replace #chart with a
// pristine node — any instance we miss then redraws into a detached, invisible
// element instead of ghosting over the new chart.
function freshStage() {
const old = $('chart');
// ECharts: dispose any instance bound to the container or its descendants.
if (window.echarts) {
[old, ...old.querySelectorAll('*')].forEach(el => {
try { const i = echarts.getInstanceByDom(el); if (i) i.dispose(); } catch (e) {}
});
}
// ApexCharts: destroy instances whose element lives inside the container.
if (window.Apex && Array.isArray(Apex._chartInstances)) {
Apex._chartInstances.slice().forEach(rec => {
try {
const el = rec.chart && rec.chart.el;
if (el && (el === old || old.contains(el))) rec.chart.destroy();
} catch (e) {}
});
}
// Plotly: purge its internal state before the node goes away.
if (window.Plotly) {
old.querySelectorAll('.js-plotly-plot').forEach(el => { try { Plotly.purge(el); } catch (e) {} });
}
// Swap in a clean element (drops Chart.js canvases, three.js renderers, leftover
// inline styles, and ECharts' _echarts_instance_ tag in one shot).
const fresh = document.createElement('div');
fresh.id = 'chart';
old.replaceWith(fresh);
return fresh;
}
// ── Render whatever is in the spec box ──────────────────────────────────────
function render() {
if (!renderFn) { setStatus('Load a plugin first.', 'err'); return; }
let spec;
try {
const raw = $('specText').value.trim();
if (!raw) throw new Error('No spec to render. Use steps 2–4, or paste a spec in the Advanced box.');
spec = JSON.parse(raw);
} catch (e) {
setStatus('Spec is not valid JSON: ' + e.message, 'err');
return;
}
if (spec && spec.sql && !spec.nodes && !spec.data) {
setStatus('This spec only has a "sql" field. The playground can\'t run SQL — provide inline data instead.', 'err');
return;
}
const chart = freshStage();
setStatus('Rendering…');
// Render may load a CDN script and draw asynchronously, so a plain try/catch
// around the call misses errors thrown in that callback.
let asyncErr = null;
const onErr = e => { asyncErr = e.error || e.message || e; };
window.addEventListener('error', onErr);
try {
renderFn(chart, spec);
setStatus('Rendered ✓ (if the canvas is blank, check your spec against the plugin\'s Spec example)', 'ok');
} catch (e) {
setStatus('Render threw: ' + (e && e.message ? e.message : e), 'err');
}
setTimeout(() => {
window.removeEventListener('error', onErr);
if (asyncErr) setStatus('Render error (async): ' + (asyncErr.message || asyncErr), 'err');
}, 1500);
}
// ── Wiring ──────────────────────────────────────────────────────────────────
$('pluginFile').addEventListener('change', e => { if (e.target.files[0]) loadPlugin(e.target.files[0]); });
$('dataFile').addEventListener('change', async e => {
if (!e.target.files[0]) return;
try { $('rawText').value = await readFile(e.target.files[0]); deriveSchema(); }
catch (err) { setStatus('Could not read data file: ' + err.message, 'err'); }
});
$('schemaBtn').addEventListener('click', deriveSchema);
$('buildPromptBtn').addEventListener('click', buildPrompt);
$('copyPromptBtn').addEventListener('click', async () => {
try { await navigator.clipboard.writeText($('promptOut').value); setStatus('Prompt copied to clipboard.', 'ok'); }
catch (e) { $('promptOut').select(); setStatus('Couldn\'t auto-copy — the prompt is selected, press Ctrl+C.', 'err'); }
});
$('applyBtn').addEventListener('click', applyTransform);
$('specFile').addEventListener('change', async e => {
if (!e.target.files[0]) return;
try { $('specText').value = await readFile(e.target.files[0]); setStatus('Spec file loaded.', 'ok'); }
catch (err) { setStatus('Could not read spec file: ' + err.message, 'err'); }
});
$('exampleBtn').addEventListener('click', () => {
// Prefer the plugin's own bundled demo spec (small, real, guaranteed renderable);
// fall back to scraping a spec out of the promptDescription for older plugins.
const ex = (plugin && plugin.exampleSpec) || extractExampleSpec(plugin && plugin.promptDescription);
if (!ex) { setStatus('No example spec found in this plugin — bring your own data.', 'err'); return; }
$('specText').value = JSON.stringify(ex, null, 2);
setStatus('Demo spec loaded from the plugin — rendering…', 'ok');
render();
});
$('renderBtn').addEventListener('click', render);
</script>
</body>
</html>