-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode-runner.js
More file actions
439 lines (397 loc) · 17.6 KB
/
Copy pathcode-runner.js
File metadata and controls
439 lines (397 loc) · 17.6 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
(function () {
'use strict';
const PYODIDE_VERSION = '0.26.4';
const PYODIDE_BASE = `https://cdn.jsdelivr.net/pyodide/v${PYODIDE_VERSION}/full/`;
const TFJS_SRC = 'https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.17.0/dist/tf.min.js';
const state = {
pyodidePromise: null,
pyodidePackages: new Set(),
tfPromise: null,
};
// ── Size-preference persistence ────────────────────────────────────────
// Stores the user's dragged editor height + widget width per widget, keyed by
// a stable id derived from the widget title + its index on the page. Best
// effort: storage can be unavailable (private mode / file://) and the resize
// still works for the session, it just won't be remembered.
const SIZE_STORAGE_KEY = 'ml-suite-runner-size';
function readSizePrefs() {
try {
const raw = window.localStorage && window.localStorage.getItem(SIZE_STORAGE_KEY);
const parsed = raw ? JSON.parse(raw) : null;
return parsed && typeof parsed === 'object' ? parsed : {};
} catch (err) {
return {};
}
}
function writeSizePref(id, patch) {
try {
if (!window.localStorage) return;
const all = readSizePrefs();
all[id] = Object.assign({}, all[id], patch);
window.localStorage.setItem(SIZE_STORAGE_KEY, JSON.stringify(all));
} catch (err) {
// Storage unavailable — size still applies for this session.
}
}
function sizeKey(title, index) {
const slug = String(title || 'runner').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 48);
return `${slug || 'runner'}#${index}`;
}
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
function loadScriptOnce(src, globalProbe) {
if (globalProbe && globalProbe()) return Promise.resolve();
const existing = Array.from(document.scripts).find((script) => script.dataset.codeRunnerSrc === src);
if (existing) {
return new Promise((resolve, reject) => {
existing.addEventListener('load', resolve, { once: true });
existing.addEventListener('error', reject, { once: true });
});
}
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = src;
script.async = true;
script.dataset.codeRunnerSrc = src;
script.onload = resolve;
script.onerror = () => reject(new Error(`Unable to load ${src}`));
document.head.appendChild(script);
});
}
function packageList(el) {
return (el.dataset.packages || '')
.split(',')
.map((p) => p.trim())
.filter(Boolean);
}
function runtimeLabel(runtime, packages) {
if (runtime === 'pyodide') return packages.length ? `Python / ${packages.join(', ')}` : 'Python';
if (runtime === 'tfjs') return 'JavaScript / TF.js';
return runtime || 'runner';
}
function getSource(el) {
const sourceNode = el.querySelector('script.code-runner-source[type="text/plain"], script[type="text/plain"].code-runner-source');
return dedentSource(sourceNode ? sourceNode.textContent : (el.textContent || ''));
}
function dedentSource(text) {
const raw = String(text || '').replace(/^\n/, '').replace(/\s+$/, '');
const lines = raw.split('\n');
const indents = lines
.filter((line) => line.trim())
.map((line) => (line.match(/^[ \t]*/) || [''])[0].length);
const minIndent = indents.length ? Math.min(...indents) : 0;
return lines.map((line) => line.slice(Math.min(minIndent, line.length))).join('\n');
}
function setStatus(widget, text) {
widget.status.textContent = text;
}
function setOutput(widget, text, kind) {
widget.output.textContent = text || '';
widget.output.classList.toggle('is-error', kind === 'error');
widget.output.classList.toggle('is-success', kind === 'success');
}
function formatJsValue(value) {
if (value == null) return String(value);
if (value && typeof value === 'object' && typeof value.dataSync === 'function' && Array.isArray(value.shape)) {
const vals = Array.from(value.dataSync()).slice(0, 12).map((n) => Number.isFinite(n) ? Number(n).toFixed(4).replace(/\.?0+$/, '') : String(n));
const suffix = value.size > 12 ? ', ...' : '';
return `Tensor(shape=[${value.shape.join(', ')}], data=[${vals.join(', ')}${suffix}])`;
}
if (typeof value === 'object') {
try { return JSON.stringify(value, null, 2); } catch (e) { return String(value); }
}
return String(value);
}
async function ensurePyodide(packages, widget) {
if (!state.pyodidePromise) {
setStatus(widget, 'Loading Python runtime...');
state.pyodidePromise = loadScriptOnce(PYODIDE_BASE + 'pyodide.js', () => typeof window.loadPyodide === 'function')
.then(() => window.loadPyodide({ indexURL: PYODIDE_BASE }));
}
const pyodide = await state.pyodidePromise;
const missing = packages.filter((pkg) => !state.pyodidePackages.has(pkg));
if (missing.length) {
setStatus(widget, `Loading packages: ${missing.join(', ')}...`);
await pyodide.loadPackage(missing);
missing.forEach((pkg) => state.pyodidePackages.add(pkg));
}
return pyodide;
}
async function runPyodide(widget) {
const packages = packageList(widget.root);
const pyodide = await ensurePyodide(packages, widget);
const logs = [];
pyodide.setStdout({ batched: (text) => logs.push(text) });
pyodide.setStderr({ batched: (text) => logs.push(text) });
const result = await pyodide.runPythonAsync(widget.editor.value);
if (typeof result !== 'undefined' && result !== null) logs.push(String(result));
return logs.join('\n').trim() || '(no output)';
}
async function ensureTfjs(widget) {
if (window.tf) return window.tf;
if (!state.tfPromise) {
setStatus(widget, 'Loading TF.js runtime...');
state.tfPromise = loadScriptOnce(TFJS_SRC, () => !!window.tf).then(() => window.tf);
}
return state.tfPromise;
}
async function runTfjs(widget) {
const tf = await ensureTfjs(widget);
const logs = [];
const log = (...args) => logs.push(args.map(formatJsValue).join(' '));
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
const fn = new AsyncFunction('tf', 'log', 'print', `${widget.editor.value}\n//# sourceURL=code-runner-tfjs.js`);
const result = await fn(tf, log, log);
if (typeof result !== 'undefined') log(result);
return logs.join('\n').trim() || '(no output)';
}
async function runWidget(widget) {
const runtime = widget.root.dataset.runtime || 'pyodide';
widget.run.disabled = true;
setOutput(widget, '', null);
setStatus(widget, 'Preparing runtime...');
try {
const output = runtime === 'tfjs' ? await runTfjs(widget) : await runPyodide(widget);
setOutput(widget, output, 'success');
setStatus(widget, 'Run complete');
} catch (err) {
const runtimeName = runtime === 'tfjs' ? 'TF.js' : 'Pyodide';
setOutput(
widget,
`${runtimeName} runner failed.\n${err && err.message ? err.message : String(err)}\n\nThe lesson still works without the runner; check network access and try again.`,
'error'
);
setStatus(widget, 'Runtime unavailable');
} finally {
widget.run.disabled = false;
}
}
// ── Drag-to-resize ─────────────────────────────────────────────────────
// Two pointer-driven affordances, both keyboard-accessible:
// • vertical splitter BETWEEN the editor and the output → reallocates
// height (drag up/down or ↑/↓ keys) so you can grow either panel.
// • a handle on the RIGHT EDGE of the whole widget → resizes its width
// (drag left/right or ←/→ keys), down to a readable minimum and up to
// the width of its container.
// Sizes persist per-widget in localStorage when available.
const MIN_EDITOR_H = 90;
const MIN_OUTPUT_H = 70;
const MIN_WIDTH = 280;
const KEY_STEP = 24;
function setupResize(widget, storeId) {
const { root, editor, output } = widget;
const prefs = readSizePrefs()[storeId] || {};
// ---- restore persisted sizes (guarded so a stale/huge value can't break layout) ----
if (typeof prefs.editorH === 'number' && isFinite(prefs.editorH)) {
editor.style.minHeight = '0px'; // inline height takes over from the CSS default floor
editor.style.height = clamp(prefs.editorH, MIN_EDITOR_H, 4000) + 'px';
}
if (typeof prefs.outputH === 'number' && isFinite(prefs.outputH)) {
output.style.minHeight = '0px';
output.style.maxHeight = 'none';
output.style.height = clamp(prefs.outputH, MIN_OUTPUT_H, 4000) + 'px';
}
if (typeof prefs.width === 'number' && isFinite(prefs.width)) {
root.style.width = Math.max(MIN_WIDTH, prefs.width) + 'px';
}
// ---- vertical splitter between editor and output ----
const splitter = document.createElement('div');
splitter.className = 'code-runner-splitter';
splitter.setAttribute('role', 'separator');
splitter.setAttribute('aria-orientation', 'horizontal');
splitter.setAttribute('aria-label', 'Resize code and output panels (drag, or use up and down arrow keys)');
splitter.setAttribute('tabindex', '0');
// ---- right-edge width handle ----
const widthHandle = document.createElement('div');
widthHandle.className = 'code-runner-width-handle';
widthHandle.setAttribute('role', 'separator');
widthHandle.setAttribute('aria-orientation', 'vertical');
widthHandle.setAttribute('aria-label', 'Resize panel width (drag, or use left and right arrow keys)');
widthHandle.setAttribute('tabindex', '0');
// Splitter sits directly below the code editor (above the Run/Reset bar) so
// it reads as "drag the bottom of the code panel"; dragging it reallocates
// height between the editor and the output. The width handle is absolutely
// positioned over the whole widget, appended last.
editor.parentNode.insertBefore(splitter, editor.nextSibling);
root.appendChild(widthHandle);
function persistHeights() {
writeSizePref(storeId, {
editorH: Math.round(editor.getBoundingClientRect().height),
outputH: Math.round(output.getBoundingClientRect().height),
});
}
function persistWidth() {
writeSizePref(storeId, { width: Math.round(root.getBoundingClientRect().width) });
}
// Set the editor↔output split to an absolute editor height (px), keeping both
// panels above their minimums and preserving the combined height so the rest
// of the page does not jump. Output drops its CSS max-height cap so it can
// actually grow past it.
function setEditorHeight(targetE, totalH) {
const total = totalH || (editor.getBoundingClientRect().height + output.getBoundingClientRect().height);
const newE = clamp(targetE, MIN_EDITOR_H, Math.max(MIN_EDITOR_H, total - MIN_OUTPUT_H));
// Drop both CSS floors so the inline heights fully control the split; our
// own clamp already guarantees each panel stays above its usable minimum.
editor.style.minHeight = '0px';
editor.style.height = Math.round(newE) + 'px';
output.style.minHeight = '0px';
output.style.maxHeight = 'none';
output.style.height = Math.round(total - newE) + 'px';
}
// Set the widget to an absolute width (px), bounded by a readable minimum and
// the width of its container so it can never overflow the layout.
function setWidth(targetW) {
const parent = root.parentElement;
const maxW = parent ? parent.getBoundingClientRect().width : Infinity;
const newW = clamp(targetW, MIN_WIDTH, maxW || Infinity);
root.style.width = Math.round(newW) + 'px';
}
// Keyboard nudges read the current size, then apply an absolute target.
function nudgeHeight(deltaPx) {
setEditorHeight(editor.getBoundingClientRect().height + deltaPx);
}
function nudgeWidth(deltaPx) {
setWidth(root.getBoundingClientRect().width + deltaPx);
}
// Generic pointer-drag binder. Captures a baseline on pointerdown and applies
// ABSOLUTE deltas from it (reflow-stable: never accumulates measurement drift
// from min-height flooring mid-drag). axis 'y' → height splitter, 'x' → width.
function bindDrag(el, axis, onStart, onDelta, onEnd) {
let active = false;
let origin = 0;
let base = null;
function down(ev) {
active = true;
origin = axis === 'y' ? ev.clientY : ev.clientX;
base = onStart();
el.classList.add('is-dragging');
root.classList.add('code-runner-resizing');
if (el.setPointerCapture && ev.pointerId != null) {
try { el.setPointerCapture(ev.pointerId); } catch (e) { /* ignore */ }
}
ev.preventDefault();
}
function move(ev) {
if (!active) return;
const cur = axis === 'y' ? ev.clientY : ev.clientX;
onDelta(cur - origin, base);
ev.preventDefault();
}
function up(ev) {
if (!active) return;
active = false;
el.classList.remove('is-dragging');
root.classList.remove('code-runner-resizing');
if (el.releasePointerCapture && ev && ev.pointerId != null) {
try { el.releasePointerCapture(ev.pointerId); } catch (e) { /* ignore */ }
}
if (onEnd) onEnd();
}
// Pointer Events cover mouse + touch + pen in one path.
el.addEventListener('pointerdown', down);
el.addEventListener('pointermove', move);
el.addEventListener('pointerup', up);
el.addEventListener('pointercancel', up);
}
bindDrag(
splitter,
'y',
() => {
const eH = editor.getBoundingClientRect().height;
const oH = output.getBoundingClientRect().height;
return { editorH: eH, total: eH + oH };
},
(dy, base) => setEditorHeight(base.editorH + dy, base.total),
persistHeights
);
bindDrag(
widthHandle,
'x',
() => ({ width: root.getBoundingClientRect().width }),
(dx, base) => setWidth(base.width + dx),
persistWidth
);
// Keyboard resize (arrow keys) — meets the separator role's expectations.
splitter.addEventListener('keydown', (ev) => {
if (ev.key === 'ArrowUp') { nudgeHeight(-KEY_STEP); persistHeights(); ev.preventDefault(); }
else if (ev.key === 'ArrowDown') { nudgeHeight(KEY_STEP); persistHeights(); ev.preventDefault(); }
});
widthHandle.addEventListener('keydown', (ev) => {
if (ev.key === 'ArrowLeft') { nudgeWidth(-KEY_STEP); persistWidth(); ev.preventDefault(); }
else if (ev.key === 'ArrowRight') { nudgeWidth(KEY_STEP); persistWidth(); ev.preventDefault(); }
});
// Double-click either handle to reset that dimension to the stylesheet default.
splitter.addEventListener('dblclick', () => {
editor.style.minHeight = '';
editor.style.height = '';
output.style.minHeight = '';
output.style.height = '';
output.style.maxHeight = '';
writeSizePref(storeId, { editorH: null, outputH: null });
});
widthHandle.addEventListener('dblclick', () => {
root.style.width = '';
writeSizePref(storeId, { width: null });
});
}
function buildWidget(root, index) {
const runtime = root.dataset.runtime || 'pyodide';
const packages = packageList(root);
const title = root.dataset.title || 'Runnable example';
const source = getSource(root);
root.textContent = '';
root.setAttribute('data-code-runner-ready', 'true');
const head = document.createElement('div');
head.className = 'code-runner-head';
const titleEl = document.createElement('div');
titleEl.className = 'code-runner-title';
titleEl.textContent = title;
const rt = document.createElement('div');
rt.className = 'code-runner-runtime';
rt.textContent = runtimeLabel(runtime, packages);
head.append(titleEl, rt);
const editor = document.createElement('textarea');
editor.className = 'code-runner-editor';
editor.value = source;
editor.spellcheck = false;
editor.setAttribute('aria-label', `${title} code editor`);
const controls = document.createElement('div');
controls.className = 'code-runner-controls';
const run = document.createElement('button');
run.type = 'button';
run.className = 'code-runner-run';
run.textContent = 'Run';
const reset = document.createElement('button');
reset.type = 'button';
reset.className = 'code-runner-reset';
reset.textContent = 'Reset';
const status = document.createElement('div');
status.className = 'code-runner-status';
status.id = `code-runner-status-${index}`;
status.textContent = 'Runtime loads only when Run is clicked';
controls.append(run, reset, status);
const output = document.createElement('pre');
output.className = 'code-runner-output';
output.setAttribute('aria-live', 'polite');
output.setAttribute('aria-describedby', status.id);
output.textContent = 'Output will appear here.';
root.append(head, editor, controls, output);
const widget = { root, editor, run, reset, status, output, source };
run.addEventListener('click', () => runWidget(widget));
reset.addEventListener('click', () => {
editor.value = source;
setOutput(widget, 'Output will appear here.', null);
setStatus(widget, 'Reset');
});
setupResize(widget, sizeKey(title, index));
}
function init() {
document.querySelectorAll('.code-runner[data-runtime]').forEach(buildWidget);
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init, { once: true });
} else {
init();
}
})();