Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
1682 lines (1512 loc) · 67.4 KB
/
Copy pathscript.js
File metadata and controls
1682 lines (1512 loc) · 67.4 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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* =============================================================
carterscoding.com: page behavior
-------------------------------------------------------------
1. Project cards built from the PROJECTS array in projects.js (featured
first), plus the search box and sort button above them
2. Title effects a random click animation (never the same twice in a row)
3. Card tilt 3D tilt + glare that follows the mouse (not on touch)
4. Particles glowing dots and drifting 0/1s on a <canvas>
5. Click bursts clicking empty background sends a few 1s, 0s, and dots
drifting out (drawn on the particle canvas, behind everything)
6. 404 banner "you've been redirected" notice after a bad URL (see 404.html)
7. Offline registers sw.js, which keeps a copy of the page for offline use
Everything respects prefers-reduced-motion.
============================================================= */
(() => {
"use strict";
/* ---------- Shared helpers ---------- */
const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
const finePointer = window.matchMedia("(hover: hover) and (pointer: fine)");
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const rand = (min, max) => Math.random() * (max - min) + min;
const cssVar = (name) =>
getComputedStyle(document.documentElement).getPropertyValue(name).trim();
// The visible viewport, minus any scrollbar (innerWidth includes it), which is
// exactly the area the fixed canvas and effects layer cover
const viewport = () => ({
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight,
});
/* =============================================================
1. Project cards
============================================================= */
function renderProjects() {
const grid = document.getElementById("project-grid");
if (!grid) return;
// PROJECTS is a top-level const in projects.js. Reading it can throw if
// projects.js crashed partway through, so treat that as "no projects".
let list = [];
try {
list = typeof PROJECTS !== "undefined" && Array.isArray(PROJECTS) ? PROJECTS : [];
} catch {
/* projects.js failed to run */
}
// Skip stray entries (a lone null or a typo) instead of breaking every card
const projects = list.filter((project) => project && typeof project === "object");
if (projects.length === 0) {
const empty = document.createElement("li");
empty.className = "grid__empty";
empty.textContent = "No projects yet. Check back soon!";
grid.replaceChildren(empty);
return;
}
// Featured first, in list order. Each card keeps its list position (for a
// stable id and the "date added" sort) and gets its place on screen (for
// which images load first and the fade-in stagger).
const entries = projects.map((project, index) => ({ project, index }));
const ordered = [...entries.filter(isFeatured), ...entries.filter((entry) => !isFeatured(entry))];
const fragment = document.createDocumentFragment();
ordered.forEach((entry, position) => {
entry.item = createCard(entry.project, entry.index, position);
fragment.appendChild(entry.item);
});
grid.replaceChildren(fragment);
initProjectControls(grid, entries);
}
const isFeatured = (entry) => entry.project.featured === true;
/* ---------- Search + sort ---------- */
// The cards are built once; searching hides them and sorting moves them, so
// nothing set up on them later (like the tilt) is lost.
function initProjectControls(grid, entries) {
const controls = document.getElementById("project-controls");
const search = document.getElementById("project-search");
const sortButton = document.getElementById("project-sort");
const status = document.getElementById("project-status");
if (!controls || !search || !sortButton || !status) return;
const titleOf = (entry) => entry.project.title || "Untitled project";
const SORTS = {
added: { label: "Sort: date added", compare: (a, b) => a.index - b.index },
az: {
label: "Sort: A–Z",
// numeric: "Game 2" before "Game 10"; base: ignore case and accents
compare: (a, b) => titleOf(a).localeCompare(titleOf(b), undefined, { numeric: true, sensitivity: "base" }),
},
};
let sort = "added";
// Lowercase without accents, so "pokemon" finds "Pokémon"
const fold = (text) => text.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase();
entries.forEach((entry) => (entry.haystack = fold(titleOf(entry))));
// Cards fade in once, on load. Moving or unhiding one would replay that
// (with its delay), so switch it off the first time the list changes.
const settle = () => grid.classList.add("is-settled");
const applySort = () => {
// Featured stay on top whichever sort is picked
const sorted = [...entries].sort((a, b) => isFeatured(b) - isFeatured(a) || SORTS[sort].compare(a, b));
grid.append(...sorted.map((entry) => entry.item));
};
const applySearch = () => {
const query = fold(search.value.trim());
let shown = 0;
entries.forEach((entry) => {
const match = entry.haystack.includes(query);
entry.item.hidden = !match;
if (match) shown += 1;
});
const plural = shown === 1 ? "project" : "projects";
if (!query) status.textContent = "";
else if (shown === 0) status.textContent = `No projects match “${search.value.trim()}”.`;
else status.textContent = `${shown} ${plural} found`;
// The count is for screen readers; only "no matches" needs showing
status.classList.toggle("sr-only", shown > 0);
};
search.addEventListener("input", () => {
settle();
applySearch();
});
sortButton.addEventListener("click", () => {
settle();
sort = sort === "added" ? "az" : "added";
sortButton.textContent = SORTS[sort].label;
applySort();
});
// A browser may refill the search box when coming back to the page
if (search.value) applySearch();
controls.hidden = false;
}
/**
* Builds:
* <li><a class="card" href="…">
* <div class="card__media"><img class="card__img" …></div>
* <span class="card__glare"></span>
* <div class="card__body"><h3>title</h3><span>open →</span></div>
* </a></li>
* Project data is only ever set with textContent (the one innerHTML below is
* fixed markup), so project text can never inject HTML.
*/
// index: place in projects.js (keeps ids unique and stable).
// position: place on screen when the page loads.
function createCard(project, index, position) {
const id = `project-${index}`;
const name = project.title || "Untitled project";
const item = document.createElement("li");
const card = document.createElement("a");
card.className = "card";
card.href = safeUrl(project.url);
card.style.setProperty("--i", position); // staggered fade-in
// Screen readers announce just the title as the link name
card.setAttribute("aria-labelledby", `${id}-title`);
const media = document.createElement("div");
media.className = "card__media";
if (project.image) {
const img = document.createElement("img");
img.className = "card__img";
// The first row is on screen straight away, so load it right away;
// the rest wait until they're scrolled near. Set before src so it applies.
img.loading = position < 3 ? "eager" : "lazy";
if (position === 0) img.fetchPriority = "high";
img.decoding = "async";
img.width = 1200; // card images are 1200×900 (4:3, same as the card)
img.height = 900;
img.alt = project.alt || `Preview of ${name}`;
// If the image is missing, fall back to the patterned background
img.addEventListener("error", () => card.classList.add("card--no-image"), { once: true });
img.src = project.image;
media.appendChild(img);
} else {
card.classList.add("card--no-image");
}
const glare = document.createElement("span");
glare.className = "card__glare";
glare.setAttribute("aria-hidden", "true");
const body = document.createElement("div");
body.className = "card__body";
const title = document.createElement("h3");
title.className = "card__title";
title.id = `${id}-title`;
title.textContent = name;
const cta = document.createElement("span");
cta.className = "card__cta";
cta.setAttribute("aria-hidden", "true");
cta.innerHTML = 'open <span class="card__arrow">→</span>';
// "Featured" sits above the title (projects with featured: true)
if (project.featured === true) {
card.classList.add("card--featured");
const tag = document.createElement("span");
tag.className = "card__tag";
tag.id = `${id}-tag`;
tag.textContent = "Featured";
card.setAttribute("aria-describedby", tag.id); // "Four Kingdoms, Featured"
body.appendChild(tag);
}
body.append(title, cta);
card.append(media, glare, body);
item.appendChild(card);
return item;
}
// Only http(s) links or links on this site; anything else (javascript:,
// data:, a typo) becomes "#" so a card can never run code when clicked
function safeUrl(url) {
if (!url) return "#";
try {
const parsed = new URL(url, window.location.href);
return parsed.protocol === "https:" || parsed.protocol === "http:" ? parsed.href : "#";
} catch {
return "#";
}
}
/* =============================================================
2. Title click animations
============================================================= */
// Only ASCII so every glyph has the same width in a monospace font (no layout shift)
const GLYPHS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$#%&*+=<>/\\|{}[]";
const randomGlyph = () => GLYPHS[Math.floor(Math.random() * GLYPHS.length)];
function initTitle() {
const button = document.getElementById("title-btn");
const textEl = document.getElementById("title-text");
const fxLayer = document.getElementById("fx-layer");
const cursor = button && button.querySelector(".cursor");
const page = document.querySelector(".page");
if (!button || !textEl || !fxLayer || !cursor || !page) return;
const word = textEl.textContent.trim();
// The effect that's playing right now, so it can be stopped part-way
// (window resized, reduced motion switched on): its pending waits are
// cancelled, its animations are cancelled, and reset() tidies up.
let current = null;
// Every element an effect adds, so reset() can always remove them
const effectNodes = new Set();
// Like the shared wait(), but stops (rejects) if the effect is stopped
const wait = (ms) =>
new Promise((resolve, reject) => {
const run = current;
const cancel = () => {
clearTimeout(timer);
reject(new DOMException("Effect stopped", "AbortError"));
};
const timer = setTimeout(() => {
if (run) run.cancels.delete(cancel);
resolve();
}, ms);
if (run) run.cancels.add(cancel);
});
const stopped = () => !current || current.stopped;
// Split the word into one <span> per letter so each can be animated
textEl.textContent = "";
const chars = [...word].map((letter) => {
const span = document.createElement("span");
span.className = "title__char";
span.textContent = letter;
textEl.appendChild(span);
return span;
});
// Pin each letter's width so glyph swaps can never nudge the layout
const lockWidths = () =>
chars.forEach((span) => (span.style.width = `${span.getBoundingClientRect().width}px`));
// Where the click happened. Keyboard "clicks" have no pointer position,
// so those start from the title's center.
const clickPoint = (event) => {
if (event.detail && (event.clientX || event.clientY)) return { x: event.clientX, y: event.clientY };
const rect = button.getBoundingClientRect();
return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
};
/* ---- Animation pool: add a new function here to add an effect ---- */
// Matrix-style decode: letters cycle through random glyphs, then lock in left to right
function decode() {
return new Promise((resolve) => {
lockWidths();
chars.forEach((span) => span.classList.add("is-scrambling"));
const resolveAt = chars.map((_, i) => 250 + i * 60 + rand(0, 140));
const end = Math.max(...resolveAt);
const start = performance.now();
let lastSwap = 0;
function frame(now) {
if (stopped()) return resolve();
const elapsed = now - start;
const swap = now - lastSwap > 50; // ~20 glyph changes per second
if (swap) lastSwap = now;
chars.forEach((span, i) => {
if (elapsed >= resolveAt[i]) {
if (span.classList.contains("is-scrambling")) {
span.textContent = word[i];
span.classList.replace("is-scrambling", "is-resolved");
}
} else if (swap) {
span.textContent = randomGlyph();
}
});
if (elapsed < end) requestAnimationFrame(frame);
else wait(FLASH_MS).then(resolve, resolve); // let the last flash finish
}
requestAnimationFrame(frame);
});
}
// Letters fly apart, spin, then spring back into place
function scatter() {
const size = parseFloat(getComputedStyle(textEl).fontSize);
const animations = chars.map((span) => {
const dx = rand(-1.2, 1.2) * size;
const dy = rand(-1, 1) * size;
return span.animate(
[
{ transform: "none", easing: "cubic-bezier(.15,.8,.3,1)" },
{
transform: `translate(${dx}px, ${dy}px) rotate(${rand(-200, 200)}deg) scale(${rand(0.5, 1.3)})`,
opacity: rand(0.3, 0.8),
offset: 0.4,
easing: "cubic-bezier(.34,1.56,.64,1)", // overshoot = "snap"
},
{ transform: "none", opacity: 1 },
],
{ duration: 1100, delay: rand(0, 90) }
);
});
return Promise.all(animations.map((a) => a.finished));
}
// RGB-split glitch (CSS keyframes) plus a few corrupted letters
async function glitch() {
let onEnd;
const cssDone = new Promise((resolve) => {
onEnd = (event) => {
if (event.target === textEl) resolve();
};
textEl.addEventListener("animationend", onEnd);
textEl.addEventListener("animationcancel", onEnd);
});
textEl.classList.add("fx-glitch");
for (let n = 0; n < 6; n++) {
const i = Math.floor(Math.random() * chars.length);
chars[i].textContent = randomGlyph();
chars[i].classList.add("is-glitched");
await wait(rand(60, 120));
chars[i].textContent = word[i];
chars[i].classList.remove("is-glitched");
}
try {
// The CSS animation is ~0.6s; don't hang if it never runs or never ends
await Promise.race([cssDone, wait(1500)]);
} finally {
textEl.removeEventListener("animationend", onEnd);
textEl.removeEventListener("animationcancel", onEnd);
}
}
// Green rings burst from the click point; letters bounce as the wave passes
function shockwave(event) {
const { x, y } = clickPoint(event);
const { width, height } = viewport();
const size = Math.max(width, height) * 1.2;
const rings = [0, 150].map((delay) => {
const ring = fx("shockwave");
ring.style.setProperty("--size", `${size}px`);
ring.style.left = `${x}px`;
ring.style.top = `${y}px`;
return ring
.animate(
[
{ transform: "scale(0.02)", opacity: 1 },
{ transform: "scale(1)", opacity: 0 },
],
{ duration: 1100, delay, easing: "cubic-bezier(.1,.7,.3,1)", fill: "both" }
)
.finished.then(() => ring.remove());
});
const bounces = chars.map((span) => {
const rect = span.getBoundingClientRect();
const centerX = rect.left + rect.width / 2;
const direction = centerX < x ? -1 : 1;
return span.animate(
[
{ transform: "none" },
{
transform: `translate(${direction * 6}px, -0.35em) scale(1.25)`,
color: "#ffffff",
offset: 0.3,
},
{ transform: "none" },
],
{ duration: 600, delay: Math.abs(centerX - x) * 1.1, easing: "cubic-bezier(.3,.7,.4,1)" }
).finished;
});
return Promise.all([...rings, ...bounces]);
}
// Typewriter: backspace the word, pause, retype it. Letters are hidden
// (not removed) and the cursor slides with a transform, so nothing reflows.
async function typewriter() {
cursor.classList.add("is-solid");
const last = chars[chars.length - 1];
const endX = last.offsetLeft + last.offsetWidth;
const placeCursor = (visibleCount) => {
const x = visibleCount < chars.length ? chars[visibleCount].offsetLeft : endX;
cursor.style.transform = `translateX(${x - endX}px)`;
};
for (let i = chars.length - 1; i >= 0; i--) {
chars[i].classList.add("is-hidden");
placeCursor(i);
await wait(45);
}
await wait(450);
for (let i = 0; i < chars.length; i++) {
chars[i].classList.remove("is-hidden");
placeCursor(i + 1);
await wait(rand(55, 120));
}
await wait(250);
}
// Old CRT monitor switching off and back on: the title squashes into a
// glowing line, shrinks to a dot, goes dark, then reverses.
function crt() {
const rect = button.getBoundingClientRect();
const beam = pinned("crt-beam", "", rect.left + rect.width / 2, rect.top + rect.height / 2);
beam.style.width = `${rect.width}px`;
// Easing goes on each step (not the whole animation) so the
// line/dot/off moments land exactly at their offsets
const frame = (offset, sx, sy, brightness, opacity) => ({
offset,
transform: `scale(${sx}, ${sy})`,
filter: `brightness(${brightness}) saturate(${brightness > 1 ? 0.4 : 1})`,
opacity,
easing: "ease-in-out",
});
const tube = button.animate(
[
frame(0, 1, 1, 1, 1),
frame(0.1, 1.03, 0.5, 1.8, 1),
frame(0.2, 1.1, 0.02, 3, 1), // collapsed to a line
frame(0.3, 0.01, 0.02, 3, 1), // then a dot
frame(0.36, 0, 0, 3, 0), // off
frame(0.6, 0, 0, 3, 0),
frame(0.66, 0.01, 0.02, 3, 1), // dot again
frame(0.78, 1.1, 0.02, 3, 1), // line again
frame(0.9, 0.98, 1.08, 1.5, 1),
frame(1, 1, 1, 1, 1),
],
{ duration: 1600 }
);
// A bright horizontal beam that sells the line → dot → off look
const glow = beam.animate(
[
{ offset: 0, opacity: 0, transform: "scaleX(1)" },
{ offset: 0.16, opacity: 0, transform: "scaleX(1)" },
{ offset: 0.2, opacity: 1, transform: "scaleX(1.1)" },
{ offset: 0.3, opacity: 1, transform: "scaleX(0.02)" },
{ offset: 0.42, opacity: 0, transform: "scaleX(0.02)" },
{ offset: 0.6, opacity: 0, transform: "scaleX(0.02)" },
{ offset: 0.66, opacity: 1, transform: "scaleX(0.02)" },
{ offset: 0.78, opacity: 1, transform: "scaleX(1.1)" },
{ offset: 0.84, opacity: 0, transform: "scaleX(1)" },
{ offset: 1, opacity: 0, transform: "scaleX(1)" },
].map((step) => ({ ...step, easing: "ease-in-out" })),
{ duration: 1600 }
);
return Promise.all([tube.finished, glow.finished.then(() => beam.remove())]);
}
// Matrix rain: the letters themselves fall away like Matrix code, each one
// the bright head of a trail of green characters, then drop back into place
async function rain() {
const titleSize = parseFloat(getComputedStyle(textEl).fontSize);
const glyphSize = Math.max(11, Math.round(titleSize * 0.3));
const letterStyle = getComputedStyle(chars[0]);
const accent = cssVar("--c-accent") || "#00ff9c";
const easing = "cubic-bezier(.45,0,.9,.6)"; // speeds up as it falls
const drops = chars.map((span, i) => {
const rect = span.getBoundingClientRect();
const fall = Math.max(viewport().height - rect.top, 0); // all the way off the bottom
const delay = i * 30 + rand(0, 180);
// Longer drops take longer, so the speed feels the same on any screen
const duration = Math.min(Math.max(fall * rand(2, 2.6), 900), 2200);
// Trail column: starts a little below the letter's top (roughly where
// lowercase letters begin), so the trail stays hidden until the letter
// falls, then hugs it all the way down
const attach = rect.height * 0.28;
const column = fx("rain");
column.style.left = `${rect.left + rect.width / 2}px`;
column.style.top = `${rect.top + attach}px`;
column.style.height = `${fall + rect.height}px`;
column.style.fontSize = `${glyphSize}px`;
const strip = document.createElement("div");
strip.className = "rain__strip";
const count = Math.round(rand(6, 12));
const glyphs = [];
for (let k = 0; k < count; k++) {
const glyph = document.createElement("span");
glyph.textContent = randomGlyph();
glyph.style.opacity = ((k + 1) / count).toFixed(2); // brightest next to the letter
glyphs.push(glyph);
strip.appendChild(glyph);
}
column.appendChild(strip);
// Trail and letter move together: the strip's bottom edge tracks the letter
const stripHeight = count * glyphSize * 1.1;
const trail = strip.animate(
[{ transform: `translateY(${-stripHeight}px)` }, { transform: `translateY(${fall - stripHeight}px)` }],
{ duration, delay, easing, fill: "both" }
);
// The falling letter is a copy on the fixed effects layer, so it can
// drop off the bottom of the screen without ever making the page
// taller. The real letter is hidden but keeps its space. (Being on the
// fixed layer, the drops don't follow the page if it scrolls mid-fall;
// that's the trade-off for never adding a scrollbar.)
const letter = fx("rain-letter");
letter.textContent = span.textContent;
letter.style.left = `${rect.left}px`;
letter.style.top = `${rect.top}px`;
letter.style.fontFamily = letterStyle.fontFamily;
letter.style.fontSize = letterStyle.fontSize;
letter.style.fontWeight = letterStyle.fontWeight;
letter.style.lineHeight = `${rect.height}px`;
span.classList.add("is-hidden");
const drop = letter.animate(
[{ transform: "none" }, { transform: `translateY(${fall}px)` }],
{ duration, delay, easing, fill: "both" }
);
// Letter and trail stay solid for most of the fall, then dissolve,
// fully gone by the time they reach the bottom of the screen
const dissolve = [{ opacity: 1 }, { opacity: 1, offset: 0.8 }, { opacity: 0 }];
const fades = [letter, column].map(
(el) => el.animate(dissolve, { duration, delay, fill: "both" }).finished
);
return { span, column, letter, glyphs, trail, drop, fades };
});
// Trail characters keep changing as they fall
const flicker = setInterval(() => {
drops.forEach(({ glyphs }) => {
glyphs[Math.floor(Math.random() * glyphs.length)].textContent = randomGlyph();
});
}, 70);
try {
await Promise.all(
drops.map(({ trail, drop, fades }) => Promise.all([trail.finished, drop.finished, ...fades]))
);
} finally {
clearInterval(flicker);
drops.forEach(({ column, letter }) => {
column.remove();
letter.remove();
});
}
// Letters drop back in from just above, left to right, with a white flash
const returns = drops.map(({ span }, i) => {
span.classList.remove("is-hidden"); // stays invisible until its turn (fill: backwards)
return span.animate(
[
{ transform: "translateY(-0.6em)", opacity: 0, color: "#ffffff" },
{ transform: "none", opacity: 1, color: "#ffffff", offset: 0.6 },
{ transform: "none", opacity: 1, color: accent },
],
{ duration: 380, delay: i * 40, easing: "cubic-bezier(.2,.8,.2,1)", fill: "backwards" }
).finished;
});
await Promise.all(returns);
await wait(150);
}
// Split-flap board: each letter flips through a few characters like an
// airport departures board before landing on the right one
async function flap() {
const FLAP_GLYPHS = "abcdefghijklmnopqrstuvwxyz0123456789";
// One flip = top half folds away (0 → -90°), glyph swaps, next half folds in (90 → 0°)
const half = (span, from, to, easing) =>
span.animate(
[{ transform: `perspective(300px) rotateX(${from}deg)` }, { transform: `perspective(300px) rotateX(${to}deg)` }],
{ duration: 60, easing, fill: "forwards" }
).finished;
const flipTo = async (span, glyph) => {
await half(span, 0, -90, "ease-in");
span.textContent = glyph;
await half(span, 90, 0, "ease-out");
};
lockWidths();
chars.forEach((span) => span.classList.add("is-flap"));
await Promise.all(
chars.map(async (span, i) => {
await wait(i * 45);
const flips = 3 + Math.floor(Math.random() * 4);
for (let k = 0; k < flips; k++) {
await flipTo(span, FLAP_GLYPHS[Math.floor(Math.random() * FLAP_GLYPHS.length)]);
}
await flipTo(span, word[i]);
span.classList.add("is-resolved");
})
);
await wait(350);
chars.forEach((span) => span.classList.add("is-flap-out")); // tiles fade away
await wait(300);
}
// Fake loading bar: the word turns into "████░░░░ 47%", fills up
// (with the classic stall near the end), then turns back into the word
async function progress() {
const cells = Math.max(chars.length - 5, 1); // room for " 100%" on the right
const slot = (i, pct) => {
if (i < cells) {
const filled = i < Math.round((pct / 100) * cells);
return [filled ? "█" : "░", filled ? "" : "is-bar-empty"];
}
// NBSP rather than a plain space, so the empty slots keep their width
if (i === cells) return [NBSP, ""];
const label = `${pct}%`.padStart(4, NBSP);
return [label[i - cells - 1] || NBSP, "is-meter"];
};
const render = (pct) =>
chars.forEach((span, i) => {
const [text, cls] = slot(i, pct);
span.textContent = text;
span.className = `title__char ${cls}`;
});
lockWidths();
cursor.classList.add("is-solid");
// The bar rolls out leftward from the cursor
for (let i = chars.length - 1; i >= 0; i--) {
const [text, cls] = slot(i, 0);
chars[i].textContent = text;
chars[i].className = `title__char ${cls}`;
await wait(22);
}
let pct = 0;
let stalled = false;
while (pct < 100) {
pct = Math.min(100, pct + Math.round(rand(4, 16)));
render(pct);
if (pct >= 80 && pct < 100 && !stalled) {
stalled = true;
await wait(rand(380, 560)); // "almost done…"
} else {
await wait(rand(50, 120));
}
}
await wait(300);
// Back to the word, left to right
for (let i = 0; i < chars.length; i++) {
chars[i].textContent = word[i];
chars[i].className = "title__char is-resolved";
await wait(28);
}
await wait(FLASH_MS); // let the last letter's flash finish
}
// Jello: the word gets poked where you clicked, squishes, and wobbles
function jello(event) {
const { x } = clickPoint(event);
const rect = textEl.getBoundingClientRect();
const originX = Math.min(Math.max(x - rect.left, 0), rect.width);
textEl.style.transformOrigin = `${originX}px 100%`;
const squish = textEl.animate(
[
{ transform: "none" },
{ transform: "scale(1.2, 0.72)", offset: 0.14 },
{ transform: "scale(0.85, 1.2) skewX(-7deg)", offset: 0.3 },
{ transform: "scale(1.1, 0.9) skewX(5deg)", offset: 0.46 },
{ transform: "scale(0.95, 1.06) skewX(-3deg)", offset: 0.62 },
{ transform: "scale(1.03, 0.97) skewX(1.5deg)", offset: 0.78 },
{ transform: "none" },
].map((step) => ({ ...step, easing: "ease-in-out" })),
{ duration: 1100 }
);
// Letters jiggle a beat later the farther they are from the poke
const jiggles = chars.map((span) => {
const r = span.getBoundingClientRect();
const distance = Math.abs(r.left + r.width / 2 - x);
return span.animate(
[
{ transform: "none" },
{ transform: "translateY(-0.12em) scaleY(1.12)", offset: 0.35 },
{ transform: "translateY(0.04em) scaleY(0.94)", offset: 0.7 },
{ transform: "none" },
],
{ duration: 500, delay: 120 + distance * 0.6, easing: "ease-in-out" }
).finished;
});
return Promise.all([squish.finished, ...jiggles]);
}
/* ---- Everyday-computer jokes ---- */
// Make an element on the fixed effects layer. html must be fixed markup
// written here, never text from a variable (use textContent for that).
const fx = (className, html = "") => {
const el = document.createElement("div");
el.className = className;
el.innerHTML = html;
fxLayer.appendChild(el);
effectNodes.add(el);
return el;
};
// Same, but placed on the page at viewport point (x, y), so it scrolls
// along with the title instead of staying stuck to the screen. It's
// decorative, so it's hidden from screen readers like the fx layer is.
const pinned = (className, html, x, y) => {
const el = fx(`fx-pinned ${className}`, html);
el.setAttribute("aria-hidden", "true");
const origin = page.getBoundingClientRect();
page.appendChild(el);
el.style.left = `${x - origin.left}px`;
el.style.top = `${y - origin.top}px`;
return el;
};
const clamp = (n, min, max) => Math.min(Math.max(n, min), max);
const NBSP = "\u00a0"; // no-break space: holds a letter's width where a space would collapse
const FLASH_MS = 450; // length of the white "resolved" flash (char-flash in styles.css)
// DVD screensaver: the title shrinks into a logo, bounces around the
// screen changing color, nails the corner, then flies home
async function dvd() {
const COLORS = ["#00ff9c", "#00d8c4", "#ff4fd8", "#ffd84f", "#4f9bff", "#ff7a4f"];
const textRect = textEl.getBoundingClientRect();
const titleStyle = getComputedStyle(textEl);
const logo = fx("dvd", "<span></span>");
logo.firstChild.textContent = word;
logo.style.fontFamily = titleStyle.fontFamily;
logo.style.fontSize = titleStyle.fontSize;
logo.style.fontWeight = titleStyle.fontWeight;
logo.style.letterSpacing = titleStyle.letterSpacing;
// Line the logo's text up exactly with the real title before swapping
const boxRect = logo.getBoundingClientRect();
const inner = logo.firstChild.getBoundingClientRect();
const offsetX = inner.left - boxRect.left;
const offsetY = inner.top - boxRect.top + inner.height / 2;
const startX = textRect.left - offsetX;
const startY = textRect.top + textRect.height / 2 - offsetY;
const w = boxRect.width;
const h = boxRect.height;
const view = viewport();
const scale = Math.min(Math.min(view.width * 0.42, 240) / w, 0.45);
// How far the logo can travel (at least 1px, so the maths below never
// divides by zero on a very short or narrow window)
const roomX = Math.max(view.width - w * scale, 1);
const roomY = Math.max(view.height - h * scale, 1);
const place = (x, y, s) => `translate(${x}px, ${y}px) scale(${s})`;
textEl.style.visibility = "hidden";
cursor.style.visibility = "hidden";
logo.style.transform = place(startX, startY, 1);
// 1. Shrink into a logo
const x0 = clamp(startX + (w * (1 - scale)) / 2, 0, roomX);
const y0 = clamp(startY + (h * (1 - scale)) / 2, 0, roomY);
await logo.animate(
[{ transform: place(startX, startY, 1) }, { transform: place(x0, y0, scale) }],
{ duration: 450, easing: "cubic-bezier(.5,0,.3,1)", fill: "forwards" }
).finished;
// 2. Bounce. The path is planned so it lands exactly in a corner at the
// end: moving diagonally, each axis must travel a whole number of
// screen-widths/heights. Pick the combo with the most DVD-like angle.
const duration = 2800;
const dirX = Math.random() < 0.5 ? 1 : -1;
const dirY = Math.random() < 0.5 ? 1 : -1;
const fromX = dirX > 0 ? x0 : roomX - x0; // distance measured in the travel direction
const fromY = dirY > 0 ? y0 : roomY - y0;
let best = null;
for (let k = 1; k <= 5; k++) {
for (let m = 1; m <= 5; m++) {
const vx = (k * roomX - fromX) / duration;
const vy = (m * roomY - fromY) / duration;
if (vx <= 0 || vy <= 0) continue;
const score = Math.abs(Math.log(vx / vy)) + (k + m < 4 ? 0.6 : 0); // prefer a few bounces
if (!best || score < best.score) best = { vx, vy, score };
}
}
// Can't happen with the 1px minimum above, but never get stuck without a path
if (!best) best = { vx: roomX / duration, vy: roomY / duration };
// Unfold the straight-line distance back into the box (a triangle wave)
const fold = (u, len) => {
const m = ((u % (2 * len)) + 2 * len) % (2 * len);
return m <= len ? m : 2 * len - m;
};
const at = (t) => {
const ux = fromX + best.vx * t;
const uy = fromY + best.vy * t;
const x = dirX > 0 ? fold(ux, roomX) : roomX - fold(ux, roomX);
const y = dirY > 0 ? fold(uy, roomY) : roomY - fold(uy, roomY);
return { x, y, bounces: Math.floor(ux / roomX) + Math.floor(uy / roomY) };
};
logo.getAnimations().forEach((a) => a.cancel()); // hand position over to the loop
logo.style.transform = place(x0, y0, scale);
logo.classList.add("is-logo"); // border fades in (after the cancel, so its transition survives)
await new Promise((resolve, reject) => {
let elapsed = 0;
let last = performance.now();
let lastBounces = 0;
let color = 0;
const step = (now) => {
if (stopped()) return reject(new DOMException("Effect stopped", "AbortError"));
// Clamp both ways: the first frame's timestamp can be a hair before `last`
elapsed = Math.min(elapsed + Math.max(0, Math.min(now - last, 50)), duration);
last = now;
const { x, y, bounces } = at(elapsed);
if (bounces !== lastBounces) {
lastBounces = bounces;
color = (color + 1) % COLORS.length;
logo.style.color = COLORS[color]; // new color on every wall hit
}
logo.style.transform = place(x, y, scale);
if (elapsed < duration) requestAnimationFrame(step);
else resolve();
};
requestAnimationFrame(step);
});
// 3. Corner! Celebrate with a flash and a burst of confetti
const end = at(duration);
const cornerX = end.x < roomX / 2 ? 0 : view.width;
const cornerY = end.y < roomY / 2 ? 0 : view.height;
const inward = Math.atan2(view.height / 2 - cornerY, view.width / 2 - cornerX);
const confetti = Array.from({ length: 16 }, (_, i) => {
const bit = fx("confetti");
bit.style.left = `${cornerX}px`;
bit.style.top = `${cornerY}px`;
bit.style.background = COLORS[i % COLORS.length];
const angle = inward + rand(-0.8, 0.8);
const dist = rand(60, 170);
return bit.animate(
[
{ transform: "translate(0, 0) rotate(0)", opacity: 1 },
{ transform: `translate(${Math.cos(angle) * dist}px, ${Math.sin(angle) * dist}px) rotate(${rand(-360, 360)}deg)`, opacity: 0 },
],
{ duration: rand(600, 900), easing: "cubic-bezier(.2,.8,.3,1)" }
).finished.then(
() => bit.remove(),
() => {} // stopped early: reset() removes it
);
});
await logo.animate(
[{ filter: "brightness(1)" }, { filter: "brightness(2.2)" }, { filter: "brightness(1)" }, { filter: "brightness(2.2)" }, { filter: "brightness(1)" }],
{ duration: 650 }
).finished;
// 4. Fly home and turn back into the title. Measure again: the page
// may have scrolled since the start.
const accent = cssVar("--c-accent") || "#00ff9c";
const home = textEl.getBoundingClientRect();
const homeX = home.left - offsetX;
const homeY = home.top + home.height / 2 - offsetY;
await logo.animate(
[
{ transform: place(end.x, end.y, scale), color: logo.style.color || accent },
{ transform: place(homeX, homeY, 1), color: accent },
],
{ duration: 600, easing: "cubic-bezier(.5,0,.2,1)", fill: "forwards" }
).finished;
textEl.style.visibility = "";
cursor.style.visibility = "";
logo.remove();
await Promise.all(confetti);
}
// Caps lock: a caps lock key lights up and the title YELLS for a moment
async function capslock() {
const rect = textEl.getBoundingClientRect();
const key = pinned("keycap", '<span class="keycap__led"></span><span>⇪ caps lock</span>', rect.left + rect.width / 2, rect.top);
const press = () =>
key.animate([{ transform: "none" }, { transform: "translateY(3px) scale(0.97)" }, { transform: "none" }], { duration: 160 }).finished;
lockWidths();
await key.animate([{ opacity: 0, transform: "translateY(8px) scale(0.8)" }, { opacity: 1, transform: "none" }], {
duration: 220,
easing: "ease-out",
}).finished;
await wait(150);
await press();
key.classList.add("is-on");
chars.forEach((span, i) => (span.textContent = word[i].toUpperCase()));
// Shake like it's shouting
const shake = [0, -7, 7, -6, 6, -4, 4, -2, 0].map((x, i, all) => ({
transform: `translateX(${x}px) rotate(${x * 0.15}deg)`,
offset: i / (all.length - 1),
}));
await textEl.animate(shake, { duration: 500 }).finished;
await wait(120);
await textEl.animate(shake, { duration: 450 }).finished;
await wait(250);
await press();
key.classList.remove("is-on");
chars.forEach((span, i) => (span.textContent = word[i]));
await wait(250);
await key.animate([{ opacity: 1 }, { opacity: 0, transform: "translateY(-6px)" }], { duration: 200, fill: "forwards" }).finished;
key.remove();
}
// Low battery: the cursor becomes a draining battery and the title dims,
// then it gets plugged in and everything brightens back up
async function battery() {
const c = cursor.getBoundingClientRect();
const cell = pinned(
"battery",
'<div class="battery__level"></div><svg class="battery__bolt" viewBox="0 0 24 24"><path d="M13.5 1.5 3.5 14h7l-1.5 8.5 11-13h-7z"/></svg>',
c.left,
c.top
);
cell.style.width = `${c.width}px`;
cell.style.height = `${c.height}px`;
cell.style.fontSize = getComputedStyle(textEl).fontSize;
cursor.style.visibility = "hidden";
const level = cell.querySelector(".battery__level");
const bolt = cell.querySelector(".battery__bolt");
const DIM = "brightness(0.3) saturate(0.5)";
// Drain: green → yellow → red while the screen dims
await Promise.all([
level.animate(
[{ height: "100%", background: "#3dff8a" }, { height: "50%", background: "#ffd23d" }, { height: "8%", background: "#ff3d5a" }],
{ duration: 1400, fill: "forwards" }
).finished,
textEl.animate([{ filter: "brightness(1)" }, { filter: DIM }], { duration: 1400, fill: "forwards" }).finished,
]);
// Low battery blink
await cell.animate([{ opacity: 1 }, { opacity: 0.2 }, { opacity: 1 }, { opacity: 0.2 }, { opacity: 1 }], { duration: 650 }).finished;
// Plugged in!
bolt.animate(
[{ opacity: 0, transform: "translate(-50%, -50%) scale(0)" }, { opacity: 1, transform: "translate(-50%, -50%) scale(1.4)", offset: 0.6 }, { opacity: 1, transform: "translate(-50%, -50%) scale(1)" }],
{ duration: 320, fill: "forwards" }
);
await wait(200);
await Promise.all([
level.animate([{ height: "8%", background: "#ff3d5a" }, { height: "50%", background: "#ffd23d" }, { height: "100%", background: "#3dff8a" }], {
duration: 700,
easing: "ease-out",
fill: "forwards",
}).finished,
textEl.animate([{ filter: DIM }, { filter: "brightness(1.6) saturate(1)", offset: 0.75 }, { filter: "brightness(1) saturate(1)" }], {
duration: 700,