-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
719 lines (596 loc) · 19 KB
/
script.js
File metadata and controls
719 lines (596 loc) · 19 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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
const container = document.getElementById('digitContainer');
const equationEl = document.getElementById('equation');
const resultEl = document.getElementById('resultDisplay');
const moveEl = document.getElementById('moveIndicator');
const goBtn = document.getElementById('goBtn');
const numberInput = document.getElementById('numberInput');
const divisorInput = document.getElementById('divisorInput');
const navBackBtn = document.getElementById('navBack');
const navNextBtn = document.getElementById('navNext');
const playFullBtn = document.getElementById('playFullBtn');
let animating = false;
let operation = 'divide';
let stepResolve = null;
let speedMultiplier = 1;
let skipSteps = false;
// Replay system
let stepHistory = [];
let historyIndex = -1;
let stepCounter = 0;
let fastForwardUntilStep = -1;
let abortFlag = false;
let animParams = null;
let currentSleepResolve = null;
let currentSleepTimeout = null;
let queuedNextCount = 0;
function setOperation(op) {
operation = op;
document.getElementById('opDivide').classList.toggle('active', op === 'divide');
document.getElementById('opMultiply').classList.toggle('active', op === 'multiply');
}
function waitForStep() {
if (abortFlag) throw 'abort';
if (skipSteps) return Promise.resolve();
const thisStep = stepCounter++;
// Save snapshot
stepHistory[thisStep] = {
containerHTML: container.innerHTML,
equationText: equationEl.textContent,
moveText: moveEl.textContent
};
stepHistory.length = thisStep + 1;
if (fastForwardUntilStep >= 0 && thisStep < fastForwardUntilStep) {
historyIndex = thisStep;
return Promise.resolve();
}
fastForwardUntilStep = -1;
historyIndex = thisStep;
container.classList.remove('fast-forward');
container.getBoundingClientRect();
if (queuedNextCount > 0) {
queuedNextCount--;
return Promise.resolve();
}
return new Promise(resolve => {
stepResolve = resolve;
navBackBtn.classList.add('active');
navNextBtn.classList.add('active');
});
}
function resolveStep() {
if (stepResolve) {
const fn = stepResolve;
stepResolve = null;
fn();
}
}
function abortCurrentSleep() {
if (currentSleepTimeout) {
clearTimeout(currentSleepTimeout);
currentSleepTimeout = null;
}
if (currentSleepResolve) {
const fn = currentSleepResolve;
currentSleepResolve = null;
fn();
}
}
function replayToStep(target) {
abortFlag = true;
queuedNextCount = 0;
resolveStep();
abortCurrentSleep();
setTimeout(() => {
abortFlag = false;
stepCounter = 0;
fastForwardUntilStep = target;
stepHistory = [];
historyIndex = -1;
container.innerHTML = '';
container.classList.add('fast-forward');
resultEl.classList.remove('visible');
resultEl.textContent = '';
moveEl.textContent = '';
const p = animParams;
const opSymbol = operation === 'divide' ? '\u00F7' : '\u00D7';
equationEl.textContent = `${p.raw} ${opSymbol} ${p.divisorRaw} = ?`;
runSequence(p.raw, p.num, p.result, p.moves, p.divisorRaw);
}, 0);
}
function handleNext() {
if (!animating) return;
if (stepResolve) {
resolveStep();
} else {
queuedNextCount++;
}
}
function handleBack() {
if (!animating && historyIndex <= 0) return;
// If paused at a step, go to previous step; if mid-animation, restart current step
const target = stepResolve ? historyIndex - 1 : historyIndex;
if (target >= 0) {
// If animation already finished, restart it for replay
if (!animating) {
animating = true;
goBtn.disabled = true;
}
replayToStep(target);
}
}
document.addEventListener('keydown', e => {
const inputFocused = numberInput.matches(':focus') || divisorInput.matches(':focus');
if (e.key === ' ' || e.code === 'Space') {
if (animating) {
e.preventDefault();
handleNext();
}
return;
}
if (e.key === 'ArrowRight') {
if (animating) {
e.preventDefault();
handleNext();
}
return;
}
if (e.key === 'Backspace' || e.key === 'ArrowLeft') {
if (!inputFocused && (animating || historyIndex > 0)) {
e.preventDefault();
handleBack();
}
return;
}
if (e.key === '-' && !inputFocused) {
speedMultiplier = Math.min(speedMultiplier * 1.3, 5);
return;
}
if (e.key === '=' && !inputFocused) {
speedMultiplier = Math.max(speedMultiplier / 1.3, 0.2);
return;
}
});
// Swipe detection for mobile
let touchStartX = 0;
let touchStartY = 0;
let swipeHandled = false;
document.addEventListener('touchstart', e => {
touchStartX = e.changedTouches[0].screenX;
touchStartY = e.changedTouches[0].screenY;
swipeHandled = false;
}, { passive: true });
document.addEventListener('touchmove', e => {
if (!animating && historyIndex <= 0) return;
const dx = e.changedTouches[0].screenX - touchStartX;
const dy = e.changedTouches[0].screenY - touchStartY;
if (Math.abs(dx) > 10 && Math.abs(dx) > Math.abs(dy)) {
e.preventDefault();
}
}, { passive: false });
document.addEventListener('touchend', e => {
if (!animating && historyIndex <= 0) return;
const dx = e.changedTouches[0].screenX - touchStartX;
const dy = e.changedTouches[0].screenY - touchStartY;
if (Math.abs(dx) < 50 || Math.abs(dx) < Math.abs(dy)) return;
if (dx > 0) handleNext();
else handleBack();
}, { passive: true });
numberInput.addEventListener('keydown', e => {
if (e.key === 'Enter' && !animating) startAnimation();
});
divisorInput.addEventListener('keydown', e => {
if (e.key === 'Enter' && !animating) startAnimation();
});
function sleep(ms) {
if (abortFlag) throw 'abort';
if (fastForwardUntilStep >= 0 && stepCounter <= fastForwardUntilStep) {
return Promise.resolve();
}
return new Promise(resolve => {
currentSleepResolve = resolve;
currentSleepTimeout = setTimeout(() => {
currentSleepTimeout = null;
currentSleepResolve = null;
resolve();
}, Math.round(ms * speedMultiplier));
});
}
function scaleToFit() {
container.style.transform = 'none';
const areaWidth = container.parentElement.clientWidth;
// Measure the widest element: either the digits themselves or any label inside
let contentWidth = container.scrollWidth;
const labels = container.querySelectorAll('.label, .cleanup-label');
labels.forEach(lbl => {
const lr = lbl.getBoundingClientRect();
const cr = container.getBoundingClientRect();
const labelLeft = lr.left - cr.left;
const labelRight = labelLeft + lr.width;
contentWidth = Math.max(contentWidth, labelRight);
});
if (contentWidth > areaWidth) {
const scale = areaWidth / contentWidth;
container.style.transform = `scale(${scale})`;
}
}
function getMovesFromDivisor(d) {
let moves = 0;
let v = Math.abs(d);
if (v < 1) return 0;
while (v >= 10 && v % 10 === 0) {
v /= 10;
moves++;
}
return v === 1 ? moves : 0;
}
function playFullAnimation() {
if (animating) {
skipSteps = true;
navBackBtn.classList.remove('active');
navNextBtn.classList.remove('active');
resolveStep();
return;
}
skipSteps = true;
startAnimation();
}
function startAnimation() {
if (animating) return;
animating = true;
goBtn.disabled = true;
stepHistory = [];
historyIndex = -1;
stepCounter = 0;
fastForwardUntilStep = -1;
abortFlag = false;
queuedNextCount = 0;
const raw = numberInput.value.trim();
const divisorRaw = divisorInput.value.trim();
if (!raw || isNaN(Number(raw)) || !divisorRaw || isNaN(Number(divisorRaw))) {
animating = false;
goBtn.disabled = false;
return;
}
const num = Number(raw);
const divisor = Number(divisorRaw);
const moves = getMovesFromDivisor(divisor);
if (moves === 0) {
animating = false;
goBtn.disabled = false;
return;
}
const result = operation === 'divide' ? num / divisor : num * divisor;
const opSymbol = operation === 'divide' ? '\u00F7' : '\u00D7';
equationEl.textContent = `${raw} ${opSymbol} ${divisorRaw} = ?`;
resultEl.classList.remove('visible');
resultEl.textContent = '';
moveEl.textContent = '';
container.innerHTML = '';
animParams = { raw, num, result, moves, divisorRaw };
runSequence(raw, num, result, moves, divisorRaw);
}
async function runSequence(raw, num, result, moves, divisorRaw) {
try {
let digits = [];
let dotIndex = -1;
const str = raw.replace(/^-/, '');
const isNegative = num < 0;
if (str.includes('.')) {
const parts = str.split('.');
for (const ch of parts[0]) digits.push(ch);
dotIndex = digits.length;
for (const ch of parts[1]) digits.push(ch);
} else {
for (const ch of str) digits.push(ch);
dotIndex = digits.length;
}
renderDigits(digits, dotIndex, !str.includes('.'));
scaleToFit();
await sleep(600);
// If integer, show the invisible decimal as its own step
let dotEl = container.querySelector('.dot');
if (!str.includes('.')) {
await waitForStep();
const label = dotEl.querySelector('.label');
dotEl.classList.add('visible');
label.classList.add('visible');
await sleep(1000);
label.classList.remove('visible');
await sleep(300);
}
if (operation === 'divide') {
await animateDivide(moves);
} else {
await animateMultiply(moves);
}
await sleep(300);
await waitForStep();
const opSymbol = operation === 'divide' ? '\u00F7' : '\u00D7';
const resultStr = formatResult(result);
equationEl.textContent = `${raw} ${opSymbol} ${divisorRaw} = ${isNegative ? '-' : ''}${resultStr}`;
resultEl.textContent = `${isNegative ? '-' : ''}${resultStr}`;
resultEl.classList.add('visible');
navBackBtn.classList.add('active');
navNextBtn.classList.remove('active');
skipSteps = false;
animating = false;
goBtn.disabled = false;
} catch (e) {
if (e === 'abort') return;
throw e;
}
}
async function animateDivide(moves) {
for (let move = 1; move <= moves; move++) {
await waitForStep();
let dotEl = container.querySelector('.dot');
moveEl.textContent = `Move ${move} of ${moves}`;
const elements = Array.from(container.children);
const currentDotIdx = elements.indexOf(dotEl);
if (currentDotIdx <= 0) {
const zeroSpan = document.createElement('span');
zeroSpan.className = 'digit fade-in';
zeroSpan.style.width = '0';
zeroSpan.style.overflow = 'hidden';
zeroSpan.textContent = '0';
container.insertBefore(zeroSpan, container.firstChild);
zeroSpan.getBoundingClientRect();
zeroSpan.classList.add('visible');
zeroSpan.style.width = '2.4ch';
await sleep(450);
scaleToFit();
}
await animateDotLeft(dotEl);
await sleep(500);
}
moveEl.textContent = '';
await cleanupTrailingZeros();
await addLeadingZeroIfNeeded();
await cleanupLoneDecimal();
}
async function animateMultiply(moves) {
for (let move = 1; move <= moves; move++) {
await waitForStep();
let dotEl = container.querySelector('.dot');
moveEl.textContent = `Move ${move} of ${moves}`;
const elements = Array.from(container.children);
const currentDotIdx = elements.indexOf(dotEl);
if (currentDotIdx >= elements.length - 1) {
const zeroSpan = document.createElement('span');
zeroSpan.className = 'digit fade-in';
zeroSpan.style.width = '0';
zeroSpan.style.overflow = 'hidden';
zeroSpan.textContent = '0';
container.appendChild(zeroSpan);
zeroSpan.getBoundingClientRect();
zeroSpan.classList.add('visible');
zeroSpan.style.width = '2.4ch';
await sleep(450);
scaleToFit();
}
await animateDotRight(dotEl);
await sleep(500);
}
moveEl.textContent = '';
await cleanupLeadingZeros();
await cleanupLoneDecimal();
}
function renderDigits(digits, dotIndex, isDotInvisible) {
container.innerHTML = '';
for (let i = 0; i < digits.length; i++) {
if (i === dotIndex) {
const dotSpan = document.createElement('span');
dotSpan.className = 'dot' + (isDotInvisible ? ' fade-in' : ' visible');
dotSpan.textContent = '.';
const label = document.createElement('span');
label.className = 'label';
label.textContent = 'invisible decimal';
dotSpan.appendChild(label);
container.appendChild(dotSpan);
}
const span = document.createElement('span');
span.className = 'digit visible';
span.textContent = digits[i];
container.appendChild(span);
}
if (dotIndex === digits.length) {
const dotSpan = document.createElement('span');
dotSpan.className = 'dot' + (isDotInvisible ? ' fade-in' : ' visible');
dotSpan.textContent = '.';
const label = document.createElement('span');
label.className = 'label';
label.textContent = 'invisible decimal';
dotSpan.appendChild(label);
container.appendChild(dotSpan);
}
}
async function animateDotLeft(dotEl) {
const elements = Array.from(container.children);
const idx = elements.indexOf(dotEl);
if (idx <= 0) return;
const leftEl = elements[idx - 1];
dotEl.style.transition = 'transform 0.4s ease';
leftEl.style.transition = 'transform 0.4s ease';
// Use offsetWidth: unaffected by container's scale transform
const dotWidth = dotEl.offsetWidth;
const digitWidth = leftEl.offsetWidth;
dotEl.style.transform = `translateX(-${digitWidth}px)`;
leftEl.style.transform = `translateX(${dotWidth}px)`;
await sleep(450);
dotEl.style.transition = 'none';
leftEl.style.transition = 'none';
dotEl.style.transform = '';
leftEl.style.transform = '';
container.insertBefore(dotEl, leftEl);
}
async function animateDotRight(dotEl) {
const elements = Array.from(container.children);
const idx = elements.indexOf(dotEl);
if (idx >= elements.length - 1) return;
const rightEl = elements[idx + 1];
dotEl.style.transition = 'transform 0.4s ease';
rightEl.style.transition = 'transform 0.4s ease';
// Use offsetWidth: unaffected by container's scale transform
const dotWidth = dotEl.offsetWidth;
const digitWidth = rightEl.offsetWidth;
dotEl.style.transform = `translateX(${digitWidth}px)`;
rightEl.style.transform = `translateX(-${dotWidth}px)`;
await sleep(450);
dotEl.style.transition = 'none';
rightEl.style.transition = 'none';
dotEl.style.transform = '';
rightEl.style.transform = '';
// Move the right element before the dot (effectively moving dot right)
container.insertBefore(rightEl, dotEl);
}
async function cleanupTrailingZeros() {
const elements = Array.from(container.children);
const dotEl = container.querySelector('.dot');
if (!dotEl) return;
const dotIdx = elements.indexOf(dotEl);
const trailingZeros = [];
for (let i = elements.length - 1; i > dotIdx; i--) {
if (elements[i].textContent.trim() === '0') {
trailingZeros.push(elements[i]);
} else {
break;
}
}
if (trailingZeros.length === 0) return;
await waitForStep();
const groupLabel = document.createElement('span');
groupLabel.className = 'cleanup-label';
groupLabel.textContent = 'remove zeroes that don\u2019t change the value';
trailingZeros[trailingZeros.length - 1].style.position = 'relative';
trailingZeros[trailingZeros.length - 1].appendChild(groupLabel);
if (trailingZeros.length > 1) {
groupLabel.style.left = '0';
groupLabel.style.transform = 'none';
}
await sleep(100);
groupLabel.classList.add('visible');
await sleep(1200);
groupLabel.classList.remove('visible');
await sleep(400);
for (const zero of trailingZeros) {
const lbl = zero.querySelector('.cleanup-label');
if (lbl) lbl.remove();
zero.style.overflow = 'hidden';
zero.style.transition = 'opacity 0.35s ease, width 0.35s ease';
zero.style.opacity = '0';
zero.style.width = '0';
await sleep(400);
zero.remove();
}
scaleToFit();
}
async function cleanupLeadingZeros() {
const dotEl = container.querySelector('.dot');
if (!dotEl) return;
const elements = Array.from(container.children);
const dotIdx = elements.indexOf(dotEl);
const leadingZeros = [];
for (let i = 0; i < dotIdx; i++) {
if (elements[i].textContent.trim() === '0') {
leadingZeros.push(elements[i]);
} else {
break;
}
}
const digitsBeforeDot = dotIdx;
if (leadingZeros.length >= digitsBeforeDot) {
leadingZeros.pop(); // keep one zero
}
if (leadingZeros.length === 0) return;
await waitForStep();
const groupLabel = document.createElement('span');
groupLabel.className = 'cleanup-label';
groupLabel.textContent = 'leading zeros don\u2019t change the value';
leadingZeros[0].style.position = 'relative';
leadingZeros[0].appendChild(groupLabel);
if (leadingZeros.length > 1) {
groupLabel.style.left = '0';
groupLabel.style.transform = 'none';
}
await sleep(100);
groupLabel.classList.add('visible');
await sleep(1200);
groupLabel.classList.remove('visible');
await sleep(400);
for (const zero of leadingZeros) {
const lbl = zero.querySelector('.cleanup-label');
if (lbl) lbl.remove();
zero.style.overflow = 'hidden';
zero.style.transition = 'opacity 0.35s ease, width 0.35s ease';
zero.style.opacity = '0';
zero.style.width = '0';
await sleep(400);
zero.remove();
}
scaleToFit();
}
async function addLeadingZeroIfNeeded() {
const dotEl = container.querySelector('.dot');
if (!dotEl) return;
const elements = Array.from(container.children);
const dotIdx = elements.indexOf(dotEl);
if (dotIdx !== 0) return;
await waitForStep();
const label = document.createElement('span');
label.className = 'cleanup-label';
label.textContent = 'add leading zero';
dotEl.style.position = 'relative';
dotEl.appendChild(label);
await sleep(100);
label.classList.add('visible');
await sleep(1200);
label.classList.remove('visible');
await sleep(400);
label.remove();
const zeroSpan = document.createElement('span');
zeroSpan.className = 'digit fade-in';
zeroSpan.style.width = '0';
zeroSpan.style.overflow = 'hidden';
zeroSpan.textContent = '0';
container.insertBefore(zeroSpan, dotEl);
zeroSpan.getBoundingClientRect();
zeroSpan.classList.add('visible');
zeroSpan.style.width = '2.4ch';
await sleep(450);
scaleToFit();
}
async function cleanupLoneDecimal() {
const dotEl = container.querySelector('.dot');
if (!dotEl) return;
const elements = Array.from(container.children);
const dotIdx = elements.indexOf(dotEl);
if (dotIdx < elements.length - 1) return;
// Step gate inside — only pauses when there's work to do
await waitForStep();
const label = document.createElement('span');
label.className = 'cleanup-label';
label.textContent = 'remove decimal with no digits after it';
dotEl.style.position = 'relative';
dotEl.appendChild(label);
await sleep(100);
label.classList.add('visible');
await sleep(1200);
label.classList.remove('visible');
await sleep(400);
dotEl.style.overflow = 'hidden';
dotEl.style.transition = 'opacity 0.35s ease, width 0.35s ease';
dotEl.style.opacity = '0';
dotEl.style.width = '0';
await sleep(400);
dotEl.remove();
}
function formatResult(n) {
const s = String(n);
if (s.includes('e')) {
return n.toFixed(20).replace(/\.?0+$/, '');
}
return s;
}
function toggleHelp() {
document.getElementById('helpOverlay').classList.toggle('visible');
}