-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.js
More file actions
551 lines (504 loc) · 22.8 KB
/
Copy pathcore.js
File metadata and controls
551 lines (504 loc) · 22.8 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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
/* ====================================================================
CORE — shared by every numerical method, regardless of type
(bracketing, open, or interpolation).
Anything in here doesn't know or care whether the active method is
Bisection, Newton-Raphson, or Lagrange interpolation — it's pure
plumbing: parsing what the user typed, formatting numbers, turning
a results panel into a PNG/PDF, and the page-chrome behaviors
(sidebar collapse, stop-option highlighting) that look the same no
matter which method is selected.
Method-specific engines (e.g. engine-bracketing.js) read from and
attach to the single shared `window.NAW` namespace below, so this
file must load *before* any engine file.
==================================================================== */
(function () {
'use strict';
const NAW = (window.NAW = window.NAW || {});
/* ================================================================
DOM REFERENCES
A single shared lookup table, since most ids on the page (the
form fields, status message, export buttons, etc.) are used by
whichever engine is active. Engine files add their own extra
ids onto this same object rather than keeping a separate one.
================================================================ */
const $ = id => document.getElementById(id);
const D = {
fxInput: $('fx-input'),
aInput: $('a-input'),
bInput: $('b-input'),
trueIn: $('true-root-input'),
precisionIn: $('precision-input'),
bracketHint: $('bracket-found-hint'),
fineToggle: $('bracket-fine-toggle'),
fxDot: $('fx-validity'),
statusMsg:$('status-msg'),
heroGr: $('hero-graph'),
heroLbl: $('hero-step-label'),
heroSection: $('hero-section'),
heroTitle: $('hero-title'),
heroSubEl: $('hero-sub'),
metaMethodVal: $('meta-method-val'),
metaOrderVal: $('meta-order-val'),
metaNeedsVal: $('meta-needs-val'),
cReadingLabel: $('c-reading-label'),
bisGr: $('bisection-graph'),
solSec: $('solution-section'),
vizSec: $('viz-section'),
tblSec: $('table-section'),
solBox: $('sol-box'),
readA: $('read-a'),
readB: $('read-b'),
readC: $('read-c'),
readFc: $('read-fc'),
readConv: $('read-converged'),
readConvW:$('read-converged-wrap'),
prevBtn: $('step-prev'),
nextBtn: $('step-next'),
playBtn: $('play-pause'),
speedSel: $('speed-select'),
stepInd: $('step-indicator'),
tHead: $('iter-thead-row'),
tBody: $('iter-tbody'),
capSum: $('capture-summary'),
tblNote: $('table-note'),
expImg: $('export-image-btn'),
expPdf: $('export-pdf-btn'),
expGif: $('export-gif-btn'),
bFieldWrap: $('b-field-wrap'),
aInputLabel: $('a-input-label'),
bInputLabel: $('b-input-label'),
bracketLegend: $('bracket-legend'),
bracketAutoLabel: $('bracket-auto-label'),
bracketAutoHint: $('bracket-auto-hint'),
bracketManualLabel: $('bracket-manual-label'),
bracketManualHint: $('bracket-manual-hint'),
};
NAW.$ = $;
NAW.D = D;
/* ================================================================
PRECISION (shared state — every method's table/graph formats
numbers through fmt()/fmtE() below, which read this)
================================================================ */
let _precision = 4; // decimal places shown everywhere (user-adjustable, 1-8)
NAW.getPrecision = () => _precision;
NAW.setPrecision = v => { _precision = Math.min(8, Math.max(1, v)); };
/* ================================================================
MATH UTILITIES
================================================================ */
/* mathjs natively defines log(x) as the NATURAL log and has no ln() at all.
We want the opposite convention for this tool: log(x) = base-10,
ln(x) = natural. Remap the two function names *after* the shorthand
pre-processing has already expanded lnx → ln(x) and logx → log(x).
The \blog\( pattern only matches a bare "log(" call — it cannot match
"log10(" or "log2(" because the very next character has to be "(",
so those are left untouched. */
function remapLogNotation(expr) {
return expr
.replace(/\bln\(/g, '__LN_PLACEHOLDER__(') // stash ln( calls
.replace(/\blog\(/g, 'log10(') // log(x) -> base-10
.replace(/__LN_PLACEHOLDER__\(/g, 'log('); // ln(x) -> mathjs's natural log
}
/* Parse a bound that may contain e, pi, sqrt(2), etc. */
function parseVal(s) {
if (!s || !s.trim()) return NaN;
if (s.length > 200) return NaN; // guard against oversized bound expressions
try {
const v = math.evaluate(remapLogNotation(s.trim()));
return (typeof v === 'number' && isFinite(v)) ? v : NaN;
} catch { return NaN; }
}
/* Pre-process a raw expression string to handle common shorthand notations:
1. Function name applied to bare variable: logx → log(x), cosx → cos(x)
2. Implicit multiplication before a function call: xtan(x) → x*tan(x), 2sin(x) → 2*sin(x) */
function preprocessExpr(expr) {
// Ordered longest-first so alternation matches correctly (log10 before log, asin before sin, etc.)
const fnPat = 'asin|acos|atan|sinh|cosh|tanh|log10|log2|sin|cos|tan|log|ln|exp|sqrt|abs|ceil|floor|round';
// Step 1: bare-variable function shorthand — sinx → sin(x), logx → log(x)
// Matches: word-boundary + function name + single letter + word-boundary + NOT followed by '('
expr = expr.replace(
new RegExp('\\b(' + fnPat + ')\\s*([a-zA-Z])\\b(?!\\s*\\()', 'g'),
'$1($2)'
);
// Step 2: implicit multiply before a function call — xtan( → x*tan(, 2sin( → 2*sin(
// Matches: letter/digit immediately before a function name that is followed by '('
expr = expr.replace(
new RegExp('([a-zA-Z0-9])\\s*(' + fnPat + ')\\s*\\(', 'g'),
'$1*$2('
);
return expr;
}
/* Compile f(x) expression into an evaluator */
function compileFn(expr) {
if (!expr || !expr.trim()) return null;
try {
const processed = remapLogNotation(preprocessExpr(expr.trim()));
const node = math.parse(processed);
const scope = {};
const fn = x => {
scope.x = x;
const r = node.evaluate(scope);
return typeof r === 'number' ? r : NaN;
};
fn.valid = true;
return fn;
} catch { return null; }
}
/* Format a number for table display */
function fmt(v, d = _precision) {
if (v == null || isNaN(v) || !isFinite(v)) return '—';
const a = Math.abs(v);
if (a > 0 && (a >= 1e7 || a < 1e-3)) return v.toExponential(d);
return v.toFixed(d);
}
/* Scientific notation for error columns */
function fmtE(v, d = _precision) {
if (v == null || isNaN(v) || !isFinite(v)) return '—';
return v.toExponential(d);
}
NAW.preprocessExpr = preprocessExpr;
NAW.remapLogNotation = remapLogNotation;
NAW.compileFn = compileFn;
NAW.parseVal = parseVal;
NAW.fmt = fmt;
NAW.fmtE = fmtE;
/* ================================================================
STATUS MESSAGES
================================================================ */
/* Escape user-supplied strings before inserting into innerHTML.
Covers both element content and attribute value contexts. */
function escHtml(s) {
return String(s)
.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>')
.replace(/"/g,'"').replace(/'/g,''');
}
function showStatus(msg, type = 'error') {
D.statusMsg.textContent = msg;
D.statusMsg.className = `status-msg ${type}`;
D.statusMsg.hidden = false;
}
function clearStatus() { D.statusMsg.hidden = true; }
NAW.escHtml = escHtml;
NAW.showStatus = showStatus;
NAW.clearStatus = clearStatus;
/* ================================================================
EXPORT PLUMBING — generic capture/download mechanics
(Building *what* goes in the export panel is method-specific and
stays in each engine; turning a built panel into a PNG/PDF blob
and triggering the download is identical for every method.)
================================================================ */
function mkCaptureOverlay(label) {
const el = document.createElement('div');
el.style.cssText = [
'position:fixed','inset:0','z-index:99999',
'background:rgba(8,23,41,0.93)',
'display:flex','align-items:center','justify-content:center',
'flex-direction:column','gap:10px'
].join(';');
el.innerHTML = `
<div style="font-family:monospace;font-size:13px;letter-spacing:2px;color:#C9784B">${label}</div>
<div style="font-family:monospace;font-size:11px;color:#7B93B0">Building landscape report\u2026</div>`;
document.body.appendChild(el);
return el;
}
/* Wait for two animation frames so the browser fully paints
the export element before html2canvas reads the pixels. */
function waitFrames() {
return new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)));
}
function ts() { return Date.now(); }
function dl(blob, filename) {
/* Validate MIME type before triggering download */
if (!blob || !['image/png','application/pdf','image/gif'].includes(blob.type)) return;
const safeName = filename.replace(/[^a-zA-Z0-9_.\-]/g, '_').slice(0, 80);
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url; a.download = safeName; a.rel = 'noopener noreferrer'; a.click();
setTimeout(() => URL.revokeObjectURL(url), 8000);
}
function canvasBlob(canvas) {
return new Promise(res => canvas.toBlob(res, 'image/png'));
}
NAW.mkCaptureOverlay = mkCaptureOverlay;
NAW.waitFrames = waitFrames;
NAW.ts = ts;
NAW.dl = dl;
NAW.canvasBlob = canvasBlob;
/* ================================================================
GIF EXPORT — generic across every method's graph.
Rasterizing an SVG frame and assembling a GIF is identical no
matter which engine drew the graph; what differs per engine is
only *how to jump to step i* and *how many steps there are* —
each engine passes those in.
================================================================ */
function svgToCanvas(hostEl, scale = 2) {
return new Promise((resolve, reject) => {
try {
/* renderGraph() replaces the host <svg>'s innerHTML with a
fresh nested <svg>...</svg> string each frame — that inner
node carries the real, current viewBox, so prefer it. */
const svgEl = (hostEl.tagName?.toLowerCase() === 'svg' && hostEl.querySelector('svg'))
? hostEl.querySelector('svg') : hostEl;
const vb = svgEl.viewBox && svgEl.viewBox.baseVal;
const w = (vb && vb.width) || svgEl.clientWidth || 800;
const h = (vb && vb.height) || svgEl.clientHeight || 456;
const svgData = new XMLSerializer().serializeToString(svgEl);
const svgBlob = new Blob([svgData], { type: 'image/svg+xml;charset=utf-8' });
const url = URL.createObjectURL(svgBlob);
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = Math.round(w * scale);
canvas.height = Math.round(h * scale);
const ctx = canvas.getContext('2d');
ctx.fillStyle = NAW.graphPalette ? NAW.graphPalette().bgDeep2 : '#0d2543';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
URL.revokeObjectURL(url);
resolve(canvas);
};
img.onerror = () => { URL.revokeObjectURL(url); reject(new Error('Could not rasterize the graph.')); };
img.src = url;
} catch (err) { reject(err); }
});
}
/* opts: { svgEl, totalSteps, gotoStep(i), currentIdx, filename, button } */
async function exportGraphGIF(opts) {
const { svgEl, totalSteps, gotoStep, currentIdx, filename, button } = opts;
if (!totalSteps || totalSteps < 1) return;
if (typeof GIF === 'undefined') {
alert('The GIF encoder failed to load — check your connection and try again.');
return;
}
const originalLabel = button.textContent;
button.disabled = true;
const overlay = mkCaptureOverlay('Building GIF\u2026');
try {
/* Some browsers refuse a cross-origin Worker script even with
CORS headers set — fetch it and hand gif.js a same-origin
blob URL instead, which every browser accepts. */
let workerScriptUrl = 'https://cdnjs.cloudflare.com/ajax/libs/gif.js/0.2.0/gif.worker.js';
try {
const wRes = await fetch(workerScriptUrl);
if (wRes.ok) workerScriptUrl = URL.createObjectURL(await wRes.blob());
} catch { /* fall back to the direct CDN URL below */ }
const gif = new GIF({ workers: 2, quality: 8, workerScript: workerScriptUrl });
for (let i = 0; i < totalSteps; i++) {
gotoStep(i);
await waitFrames();
const canvas = await svgToCanvas(svgEl);
gif.addFrame(canvas, { delay: i === totalSteps - 1 ? 1500 : 900, copy: true });
button.textContent = `Frame ${i + 1}/${totalSteps}\u2026`;
}
await new Promise((resolve, reject) => {
gif.on('finished', blob => { dl(blob, filename); resolve(); });
gif.on('abort', () => reject(new Error('rendering was aborted')));
gif.render();
});
} catch (err) {
alert('GIF export failed: ' + err.message);
} finally {
gotoStep(currentIdx);
overlay.remove();
button.textContent = originalLabel;
button.disabled = false;
}
}
NAW.svgToCanvas = svgToCanvas;
NAW.exportGraphGIF = exportGraphGIF;
/* ================================================================
PAGE CHROME — behaviors identical no matter which method is active
================================================================ */
/* Generic radio-group toggle (active-mode highlight), scoped to each
fieldset's own .stop-options container so multiple radio groups
on the page (stop-mode, bracket-mode, or any future method's own
option group) don't interfere with each other */
document.querySelectorAll('.stop-option input[type="radio"]').forEach(radio => {
radio.addEventListener('change', () => {
const container = radio.closest('.stop-options');
container.querySelectorAll('.stop-option').forEach(opt => {
opt.classList.remove('active-mode');
const sub = opt.querySelector('.sub-input');
if (sub) sub.disabled = true;
});
const opt = radio.closest('.stop-option');
opt.classList.add('active-mode');
const sub = opt.querySelector('.sub-input');
if (sub) { sub.disabled = false; sub.focus(); }
});
});
/* Initialise disabled state */
document.querySelectorAll('.stop-options').forEach(container => {
container.querySelectorAll('.stop-option').forEach(opt => {
const radio = opt.querySelector('input[type="radio"]');
const sub = opt.querySelector('.sub-input');
if (radio?.checked) { opt.classList.add('active-mode'); if (sub) sub.disabled = false; }
else if (sub) sub.disabled = true;
});
});
/* Sheet index toggle (desktop sidebar only — the mobile nav is a
separate, always-compact element and isn't affected by this). */
(function initSheetToggle() {
const btn = $('sheet-list-toggle');
const list = $('sheet-list');
if (!btn || !list) return;
const STORAGE_KEY = 'nawSheetListHidden';
function applyState(hidden) {
list.classList.toggle('is-collapsed', hidden);
btn.textContent = hidden ? 'Show' : 'Hide';
btn.setAttribute('aria-expanded', String(!hidden));
}
let hidden = false;
try { hidden = localStorage.getItem(STORAGE_KEY) === '1'; } catch {}
applyState(hidden);
btn.addEventListener('click', () => {
hidden = !list.classList.contains('is-collapsed');
applyState(hidden);
try { localStorage.setItem(STORAGE_KEY, hidden ? '1' : '0'); } catch {}
});
})();
/* ================================================================
METHOD REGISTRY & SWITCHING (shared across every engine)
Each engine (engine-bracketing.js, engine-open.js, ...) merges
its own method definitions into NAW.METHODS via
`Object.assign(NAW.METHODS, METHODS)` and subscribes with
NAW.onMethodChange(fn) to learn when its own method becomes
active or inactive — that's the only hook it needs to know when
to run its own initHero()/hideResults().
A method entry needs at minimum: id, num, docTitle, heroTitleHTML,
heroSub, metaMethod, metaOrder, metaNeeds, cLabel, graphAria,
heroGraphAria, hideB (true only for single-guess methods like
Newton-Raphson), and shapeCopy — a { elementId: text } map applied
to whichever bracket/initial-guess labels that method's fieldset
needs relabeled (see the ids read below).
================================================================ */
NAW.METHODS = NAW.METHODS || {};
let _activeMethod = 'bisection';
const _methodListeners = [];
NAW.getActiveMethod = () => _activeMethod;
NAW.onMethodChange = fn => { _methodListeners.push(fn); };
function applyMethodContentGeneric(m) {
document.title = `Numerical Analysis Workbench — ${m.docTitle}`;
D.heroTitle.innerHTML = m.heroTitleHTML;
D.heroSubEl.textContent = m.heroSub;
D.metaMethodVal.textContent = m.metaMethod;
D.metaOrderVal.textContent = m.metaOrder;
D.metaNeedsVal.textContent = m.metaNeeds;
D.cReadingLabel.textContent = m.cLabel;
D.bisGr.setAttribute('aria-label', m.graphAria);
D.heroGr.setAttribute('aria-label', m.heroGraphAria);
document.querySelectorAll('.plate-tag').forEach(el => {
el.textContent = el.textContent.replace(/Sheet \d+/, 'Sheet ' + m.num);
});
if (D.bFieldWrap) D.bFieldWrap.hidden = !!m.hideB;
if (m.shapeCopy) {
Object.entries(m.shapeCopy).forEach(([id, text]) => {
const el = $(id);
if (el) el.textContent = text;
});
}
}
NAW.setActiveMethod = function (id) {
const m = NAW.METHODS[id];
if (!m || id === _activeMethod) return;
const oldId = _activeMethod;
document.querySelectorAll('.sheet-item[data-method]').forEach(el => {
el.classList.toggle('active', el.dataset.method === id);
});
document.querySelectorAll('.mobile-nav button[data-method]').forEach(el => {
el.classList.toggle('active', el.dataset.method === id);
});
_activeMethod = id;
const finish = () => {
applyMethodContentGeneric(m);
_methodListeners.forEach(fn => fn(id, oldId));
D.heroSection.classList.remove('is-swapping');
};
const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
if (reduceMotion) { finish(); return; }
D.heroSection.classList.add('is-swapping');
setTimeout(finish, 220);
};
function wireMethodSwitch(el) {
if (!el || el.classList.contains('disabled') || el.disabled) return;
const id = el.dataset.method;
if (!id) return;
el.addEventListener('click', () => NAW.setActiveMethod(id));
el.addEventListener('keydown', e => {
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); NAW.setActiveMethod(id); }
});
}
document.querySelectorAll('.sheet-item[data-method]').forEach(wireMethodSwitch);
document.querySelectorAll('.mobile-nav button[data-method]').forEach(wireMethodSwitch);
/* ================================================================
THEME (light / dark)
The palette below is what every JS-drawn SVG graph (both engines'
renderGraph/miniLine/hero demo) reads at render time, so the
graph's colors switch along with the CSS. Exported PNG/PDF/GIF
reports intentionally stay on the dark palette — a report you'd
print or share shouldn't change appearance depending on which
theme the browser happened to be in when you clicked export.
================================================================ */
const THEME_KEY = 'naw-theme';
let _theme = 'dark';
try { _theme = localStorage.getItem(THEME_KEY) === 'light' ? 'light' : 'dark'; } catch {}
const _themeListeners = [];
const PALETTES = {
dark: {
curve: '#7FA68C', point: '#7FA68C', c: '#E2945F', danger: '#D9776B',
axis: '#AEC0D6', tick: '#7B93B0', tickLine: '#3D6694', copper: '#C9784B',
bgDeep: '#081729', bgDeep2: '#0A1F36', miniTrack: '#253F5E',
gridRGB: '61,102,148', verdigrisRGB: '127,166,140', copperRGB: '201,120,75', bgDeepRGB: '8,23,41',
},
light: {
curve: '#3E7059', point: '#3E7059', c: '#B35A22', danger: '#B3453A',
axis: '#5C5342', tick: '#8A8064', tickLine: '#B4A483', copper: '#A85D2E',
bgDeep: '#FBF8F0', bgDeep2: '#EFE7D2', miniTrack: '#CBB99A',
gridRGB: '139,124,96', verdigrisRGB: '62,112,89', copperRGB: '179,90,34', bgDeepRGB: '250,246,235',
},
};
NAW.getTheme = () => _theme;
NAW.onThemeChange = fn => { _themeListeners.push(fn); };
NAW.graphPalette = () => PALETTES[_theme];
function applyTheme(theme) {
document.documentElement.dataset.theme = theme;
document.documentElement.style.colorScheme = theme;
document.querySelectorAll('.theme-toggle-btn').forEach(btn => {
btn.setAttribute('aria-pressed', theme === 'light' ? 'true' : 'false');
const lbl = btn.querySelector('.theme-toggle-label');
if (lbl) lbl.textContent = theme === 'light' ? 'Light' : 'Dark';
});
}
NAW.setTheme = function (theme) {
_theme = (theme === 'light') ? 'light' : 'dark';
try { localStorage.setItem(THEME_KEY, _theme); } catch {}
applyTheme(_theme);
_themeListeners.forEach(fn => fn(_theme));
};
applyTheme(_theme);
document.querySelectorAll('.theme-toggle-btn').forEach(btn => {
btn.addEventListener('click', () => NAW.setTheme(_theme === 'light' ? 'dark' : 'light'));
});
/* ================================================================
TUTORIAL VIDEO — click-to-play (privacy-friendly: no embed loads
until the person actually asks for it)
================================================================ */
(function () {
const wrap = $('tutorial-video');
if (!wrap) return;
const thumb = $('tutorial-video-thumb');
thumb.addEventListener('click', () => {
const id = wrap.dataset.videoId;
const iframe = document.createElement('iframe');
iframe.src = `https://www.youtube-nocookie.com/embed/${id}?autoplay=1&rel=0`;
iframe.title = 'Tutorial video';
iframe.allow = 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture';
iframe.allowFullscreen = true;
iframe.loading = 'lazy';
wrap.innerHTML = '';
wrap.appendChild(iframe);
});
thumb.addEventListener('keydown', e => {
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); thumb.click(); }
});
})();
})();