Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
672 lines (610 loc) · 27.2 KB
/
Copy pathscript.js
File metadata and controls
672 lines (610 loc) · 27.2 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
(() => {
const isMac = /Mac|iPhone|iPad/.test(navigator.platform);
if (isMac) document.querySelectorAll(".key-mod").forEach((k) => (k.textContent = "⌘"));
// Toast + copiar
const toast = document.getElementById("toast");
let toastTimer;
const showToast = (msg) => {
toast.textContent = msg;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("show"), 1800);
};
// navigator.clipboard só existe em contexto seguro (HTTPS), daí o plano B
const legacyCopy = (text) => {
const ta = document.createElement("textarea");
ta.value = text;
ta.setAttribute("readonly", "");
ta.style.cssText = "position:fixed;top:0;left:-9999px";
document.body.appendChild(ta);
const previous = document.activeElement;
ta.select();
ta.setSelectionRange(0, ta.value.length);
let ok = false;
try {
ok = document.execCommand("copy");
} catch {
ok = false;
}
ta.remove();
previous?.focus?.();
return ok;
};
const copy = async (text) => {
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
showToast(`Copiado: ${text}`);
return;
}
} catch {
// cai no plano B abaixo
}
showToast(legacyCopy(text) ? `Copiado: ${text}` : "Não foi possível copiar");
};
// Delegado para funcionar também nas cópias do conteúdo dentro do modal
document.addEventListener("click", (e) => {
const btn = e.target.closest("[data-copy]");
if (btn) copy(btn.dataset.copy);
});
// Contatos protegidos contra robôs de spam (item 36 do ROADMAP): ficam aqui em base64, fora do HTML,
// que só marca o lugar com data-contact. O e-mail do Yahoo é montado ao abrir a página; o telefone só
// aparece quando alguém clica em "mostrar". O Gmail continua em texto puro: ele já é público nos commits.
// O terminal usa o mesmo objeto (window.Contacts), porque lê a home com DOMParser, que não roda scripts.
const Contacts = (() => {
const CODES = { yahoo: "bHVjYXNlMzkzQHlhaG9vLmNvbQ==", phone: "NTUzODk5ODEzMDU4MQ==" };
const get = (key) => {
try {
return atob(CODES[key] || "");
} catch {
return "";
}
};
// Dígitos com código do país e DDD (55 DD 9XXXXXXXX) → (DD) 9XXXX-XXXX
const phone = () => {
const d = get("phone");
return { text: `(${d.slice(2, 4)}) ${d.slice(4, 9)}-${d.slice(9)}`, tel: `tel:+${d}`, whatsapp: `https://wa.me/${d}` };
};
const revealEmails = (root = document) =>
root.querySelectorAll('a[data-contact="yahoo"]').forEach((a) => {
const email = get("yahoo");
a.href = `mailto:${email}`;
a.textContent = email;
a.removeAttribute("data-contact");
const btn = a.parentElement.querySelector("[data-copy]");
if (btn) {
btn.dataset.copy = email;
btn.hidden = false;
}
});
// Troca todos os botões "mostrar telefone" (o do README e o da cópia no modal) pelos links
const revealPhones = (clicked) => {
const p = phone();
document.querySelectorAll('button[data-contact="phone"]').forEach((btn) => {
const tel = document.createElement("a");
tel.href = p.tel;
tel.textContent = p.text;
const wa = document.createElement("a");
wa.className = "pill";
wa.href = p.whatsapp;
wa.target = "_blank";
wa.rel = "noopener";
wa.textContent = "WhatsApp";
btn.replaceWith(tel, wa);
if (btn === clicked) tel.focus();
});
};
return { get, phone, revealEmails, revealPhones };
})();
window.Contacts = Contacts;
Contacts.revealEmails();
document.addEventListener("click", (e) => {
const btn = e.target.closest('button[data-contact="phone"]');
if (btn) Contacts.revealPhones(btn);
});
// Páginas: a home tem o README e o modal; as outras (ex.: /setup) apontam para a
// raiz via data-root e mandam Skills/Contato para a home, que abre o modal pelo hash.
const root = document.body.dataset.root || "./";
const page = document.body.dataset.page || "home";
const isHome = page === "home";
// Tema: "light", "dark" ou "system" (padrão). O <head> já aplicou o tema antes de desenhar;
// aqui ficam o menu, a troca e o acompanhamento do sistema quando a escolha é "Sistema".
const html = document.documentElement;
const themeMeta = document.querySelector('meta[name="theme-color"]');
const prefersLight = matchMedia("(prefers-color-scheme: light)");
const themeNames = { light: "claro", dark: "escuro", system: "do sistema" };
const getThemePref = () => {
try {
const pref = localStorage.getItem("theme");
return pref === "light" || pref === "dark" ? pref : "system";
} catch {
return "system";
}
};
const applyTheme = () => {
const pref = getThemePref();
const theme = pref === "system" ? (prefersLight.matches ? "light" : "dark") : pref;
html.dataset.theme = theme;
themeMeta?.setAttribute("content", theme === "light" ? "#faf7f0" : "#08070b");
document
.querySelectorAll("[data-theme-choice]")
.forEach((b) => b.setAttribute("aria-checked", String(b.dataset.themeChoice === pref)));
document.querySelector(".theme-toggle")?.setAttribute("aria-label", `Tema ${themeNames[pref]}`);
};
const setTheme = (pref) => {
try {
if (pref === "system") localStorage.removeItem("theme");
else localStorage.setItem("theme", pref);
} catch {
// armazenamento bloqueado: o tema muda só nesta visita
}
applyTheme();
};
prefersLight.addEventListener("change", () => getThemePref() === "system" && applyTheme());
applyTheme();
const themeToggle = document.querySelector(".theme-toggle");
const themeMenu = document.getElementById("theme-menu");
const themeItems = [...document.querySelectorAll("[data-theme-choice]")];
const closeThemeMenu = (returnFocus = false) => {
if (!themeMenu || themeMenu.hidden) return false;
themeMenu.hidden = true;
themeToggle.setAttribute("aria-expanded", "false");
if (returnFocus) themeToggle.focus();
return true;
};
const openThemeMenu = () => {
themeMenu.hidden = false;
themeToggle.setAttribute("aria-expanded", "true");
(themeItems.find((b) => b.getAttribute("aria-checked") === "true") || themeItems[0]).focus();
};
themeToggle?.addEventListener("click", () => (themeMenu.hidden ? openThemeMenu() : closeThemeMenu()));
themeItems.forEach((b) =>
b.addEventListener("click", () => {
setTheme(b.dataset.themeChoice);
closeThemeMenu(true);
})
);
themeMenu?.addEventListener("keydown", (e) => {
const i = themeItems.indexOf(document.activeElement);
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
e.preventDefault();
const next = (i + (e.key === "ArrowDown" ? 1 : -1) + themeItems.length) % themeItems.length;
themeItems[next].focus();
} else if (e.key === "Tab") {
closeThemeMenu();
}
});
document.addEventListener("click", (e) => {
if (!e.target.closest(".theme-switch")) closeThemeMenu();
});
// Data da "edição" no README em estilo de jornal (tema claro)
const today = new Date();
document.querySelectorAll("[data-today]").forEach((el) => {
const text = new Intl.DateTimeFormat("pt-BR", { weekday: "long", day: "numeric", month: "long", year: "numeric" }).format(today);
el.textContent = text.charAt(0).toUpperCase() + text.slice(1);
el.dateTime = today.toISOString().slice(0, 10);
});
// Modal dos tópicos: o conteúdo vem do README ([data-topic]), sem duplicar HTML
const topics = {
skills: { title: "Skills", file: "skills.md" },
contato: { title: "Contato", file: "contato.md" },
};
const modal = document.getElementById("modal");
const modalBox = modal?.querySelector(".modal-box");
const modalTitle = document.getElementById("modal-title");
const modalFile = document.getElementById("modal-file");
const modalContent = document.getElementById("modal-content");
const modalClose = modal?.querySelector(".modal-close");
let modalReturnFocus = null;
const openTopic = (name) => () => {
const source = document.querySelector(`[data-topic="${name}"]`);
if (!modal || !source) {
location.href = `${root}#${name}`;
return;
}
const clone = source.cloneNode(true);
clone.removeAttribute("data-topic");
clone.querySelectorAll("[id]").forEach((el) => el.removeAttribute("id"));
modalTitle.textContent = topics[name].title;
modalFile.textContent = topics[name].file;
modalContent.replaceChildren(clone);
if (modal.hidden) {
modalReturnFocus = document.activeElement;
modal.hidden = false;
document.body.classList.add("modal-open");
}
modalContent.parentElement.scrollTop = 0;
modalClose.focus();
};
const closeModal = () => {
if (!modal || modal.hidden) return;
modal.hidden = true;
document.body.classList.remove("modal-open");
modalReturnFocus?.focus?.();
};
const goHome = () => {
if (!isHome) {
location.href = root;
return;
}
closeModal();
window.scrollTo({ top: 0, behavior: "smooth" });
};
const goSetup = () => {
if (page === "setup") {
window.scrollTo({ top: 0, behavior: "smooth" });
return;
}
location.href = `${root}setup/`;
};
const goTerminal = () => {
if (page === "terminal") {
document.getElementById("term-input")?.focus();
return;
}
location.href = `${root}terminal/`;
};
const goCurriculo = () => {
if (page === "curriculo") {
window.scrollTo({ top: 0, behavior: "smooth" });
return;
}
location.href = `${root}curriculo/`;
};
const goServicos = (id = "") => () => {
if (page === "servicos") {
if (id) document.getElementById(id)?.scrollIntoView({ behavior: "smooth" });
else window.scrollTo({ top: 0, behavior: "smooth" });
return;
}
location.href = `${root}servicos/${id && `#${id}`}`;
};
// PDF do currículo: a própria página impressa (CSS @media print). De outras páginas, abre /curriculo/#pdf,
// que imprime assim que carrega.
const printCurriculo = () => {
if (page === "curriculo") window.print();
else location.href = `${root}curriculo/#pdf`;
};
document.addEventListener("click", (e) => e.target.closest("[data-print]") && printCurriculo());
if (page === "curriculo" && location.hash === "#pdf") {
history.replaceState(null, "", location.pathname + location.search);
addEventListener("load", () => document.fonts.ready.then(() => window.print()));
}
const goJogos = (id = "") => () => {
if (page === "jogos") {
// A página troca de aba pelo hash (jogos/jogos.js)
if (id) location.hash = id;
else window.scrollTo({ top: 0, behavior: "smooth" });
return;
}
location.href = `${root}jogos/${id && `#${id}`}`;
};
const navActions = { "#inicio": goHome, "#skills": openTopic("skills"), "#contato": openTopic("contato") };
document.querySelectorAll('a[href^="#"]').forEach((a) =>
a.addEventListener("click", (e) => {
const action = navActions[a.getAttribute("href")];
if (!action) return;
e.preventDefault();
action();
})
);
document.querySelectorAll("[data-close-modal]").forEach((b) => b.addEventListener("click", closeModal));
// Vindo de outra página (ex.: /setup → Skills), abre o modal pedido e limpa o hash
if (isHome && topics[location.hash.slice(1)]) {
openTopic(location.hash.slice(1))();
history.replaceState(null, "", location.pathname + location.search);
}
// Mantém o Tab dentro do modal enquanto ele estiver aberto
modal?.addEventListener("keydown", (e) => {
if (e.key !== "Tab") return;
const focusables = [...modalBox.querySelectorAll("a[href], button:not([disabled])")];
const first = focusables[0];
const last = focusables[focusables.length - 1];
if (e.shiftKey && document.activeElement === first) {
e.preventDefault();
last.focus();
} else if (!e.shiftKey && document.activeElement === last) {
e.preventDefault();
first.focus();
}
});
// Paleta de comandos
const open = (url) => () => window.open(url, "_blank", "noopener");
const commands = [
{ group: "Navegação", label: "Início", key: "I", run: goHome },
{ group: "Navegação", label: "Skills", key: "S", run: openTopic("skills") },
{ group: "Navegação", label: "Contato", key: "C", run: openTopic("contato") },
{ group: "Navegação", label: "Setup", key: "U", run: goSetup },
{ group: "Navegação", label: "Currículo", key: "E", run: goCurriculo },
{ group: "Navegação", label: "Serviços", key: "V", run: goServicos() },
{ group: "Navegação", label: "Terminal", key: "T", run: goTerminal },
{ group: "Navegação", label: "Jogos", key: "J", run: goJogos() },
{ group: "Currículo", label: "Baixar currículo (PDF)", hint: "pdf", run: printCurriculo },
{ group: "Serviços", label: "Planos de formatação de PC", hint: "formatação", run: goServicos("formatacao") },
{ group: "Serviços", label: "Contratar um serviço", hint: "whatsapp", run: goServicos("contratar") },
{ group: "Jogos", label: "Jogo da velha", hint: "velha", run: goJogos("velha") },
{ group: "Jogos", label: "Damas", hint: "tabuleiro", run: goJogos("damas") },
{ group: "Jogos", label: "Carrinho", hint: "corrida", run: goJogos("carrinho") },
{ group: "Tema", label: "Tema claro", hint: "light", run: () => setTheme("light") },
{ group: "Tema", label: "Tema escuro", hint: "dark", run: () => setTheme("dark") },
{ group: "Tema", label: "Tema do sistema", hint: "system", run: () => setTheme("system") },
{ group: "Contato", label: "Copiar e-mail", hint: "gmail", run: () => copy("lucase616@gmail.com") },
{ group: "Contato", label: "Enviar e-mail", hint: "gmail", run: () => (location.href = "mailto:lucase616@gmail.com") },
{ group: "Contato", label: "Copiar e-mail (Yahoo)", hint: "yahoo", run: () => copy(Contacts.get("yahoo")) },
{ group: "Contato", label: "Conversar no WhatsApp", hint: "whatsapp", run: () => open(Contacts.phone().whatsapp)() },
{ group: "Contato", label: "Copiar telefone", hint: "telefone", run: () => copy(Contacts.phone().text) },
{ group: "Redes", label: "GitHub", hint: "lucase616", run: open("https://github.com/lucase616") },
{ group: "Redes", label: "LinkedIn", hint: "in", run: open("https://www.linkedin.com/in/lucas-emanuel-santos-martins-105304242/") },
{ group: "Redes", label: "Instagram", hint: "@lucase616", run: open("https://instagram.com/lucase616") },
];
const palette = document.getElementById("palette");
const input = document.getElementById("palette-input");
const list = document.getElementById("palette-list");
let filtered = commands;
let active = 0;
let lastFocus = null;
const normalize = (s) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase();
const render = () => {
list.innerHTML = "";
if (!filtered.length) {
list.innerHTML = '<li class="palette-empty">Nenhum resultado</li>';
return;
}
let group = null;
filtered.forEach((cmd, i) => {
if (cmd.group !== group) {
group = cmd.group;
const g = document.createElement("li");
g.className = "palette-group";
g.setAttribute("role", "presentation");
g.textContent = group;
list.appendChild(g);
}
const li = document.createElement("li");
li.className = "palette-item";
li.id = `cmd-${i}`;
li.setAttribute("role", "option");
li.setAttribute("aria-selected", String(i === active));
li.innerHTML = cmd.key ? `<span></span><kbd></kbd>` : `<span></span><small></small>`;
li.firstChild.textContent = cmd.label;
li.lastChild.textContent = cmd.key || cmd.hint;
li.addEventListener("mousemove", () => setActive(i));
li.addEventListener("click", () => execute(i));
list.appendChild(li);
});
input.setAttribute("aria-activedescendant", `cmd-${active}`);
};
const setActive = (i) => {
if (i === active) return;
active = i;
list.querySelectorAll(".palette-item").forEach((el, idx) => el.setAttribute("aria-selected", String(idx === i)));
input.setAttribute("aria-activedescendant", `cmd-${i}`);
document.getElementById(`cmd-${i}`)?.scrollIntoView({ block: "nearest" });
};
const openPalette = () => {
lastFocus = document.activeElement;
palette.hidden = false;
input.value = "";
filtered = commands;
active = 0;
render();
input.focus();
};
const closePalette = () => {
palette.hidden = true;
lastFocus?.focus?.();
};
const execute = (i) => {
const cmd = filtered[i];
if (!cmd) return;
closePalette();
cmd.run();
};
input.addEventListener("input", () => {
const q = normalize(input.value.trim());
filtered = commands.filter((c) => normalize(`${c.label} ${c.group} ${c.hint || ""}`).includes(q));
active = 0;
render();
});
input.addEventListener("keydown", (e) => {
if (e.key === "ArrowDown") {
e.preventDefault();
setActive((active + 1) % filtered.length || 0);
} else if (e.key === "ArrowUp") {
e.preventDefault();
setActive((active - 1 + filtered.length) % filtered.length || 0);
} else if (e.key === "Enter") {
e.preventDefault();
execute(active);
}
});
document.addEventListener("keydown", (e) => {
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "k") {
e.preventDefault();
palette.hidden ? openPalette() : closePalette();
} else if (e.key === "Escape") {
// Esc fecha primeiro o que estiver por cima: menu de tema, paleta, depois modal
if (closeThemeMenu(true)) return;
if (!palette.hidden) closePalette();
else closeModal();
}
});
// Atalhos de uma tecla (I, S, C, U, E, T, J) — ignorados enquanto se digita ou com a paleta aberta.
// Com o modal aberto continuam valendo: S/C trocam o tópico e I fecha e volta ao topo.
const shortcuts = Object.fromEntries(commands.filter((c) => c.key).map((c) => [c.key.toLowerCase(), c]));
shortcuts["`"] = shortcuts.t; // crase abre o terminal, como o console de um jogo
document.addEventListener("keydown", (e) => {
if (e.ctrlKey || e.metaKey || e.altKey || e.repeat || !palette.hidden) return;
const t = e.target;
if (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName)) return;
const cmd = shortcuts[e.key.toLowerCase()];
if (!cmd) return;
e.preventDefault();
cmd.run();
});
document.querySelectorAll("[data-open-palette]").forEach((b) => b.addEventListener("click", openPalette));
document.querySelectorAll("[data-close-palette]").forEach((b) => b.addEventListener("click", closePalette));
// Setup: alternância Lista/Grade (lembrada no navegador)
if (page === "setup") {
const viewButtons = document.querySelectorAll("[data-view]");
const setView = (view) => {
document.querySelectorAll(".items").forEach((ul) => ul.classList.toggle("is-grid", view === "grid"));
viewButtons.forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.view === view)));
try {
localStorage.setItem("setup-view", view);
} catch {
// navegação privada ou armazenamento bloqueado: só não lembra a escolha
}
};
let savedView = null;
try {
savedView = localStorage.getItem("setup-view");
} catch {
// idem
}
setView(savedView === "grid" ? "grid" : "list");
viewButtons.forEach((b) => b.addEventListener("click", () => setView(b.dataset.view)));
}
// Sumário "Nesta página" (setup, currículo e serviços): a seção atual é a última cujo topo já passou um pouco
// abaixo do cabeçalho
const tocLinks = [...document.querySelectorAll(".toc a")];
const sections = tocLinks.map((a) => document.querySelector(a.getAttribute("href"))).filter(Boolean);
const header = document.querySelector(".site-header");
const markCurrent = () => {
const line = header.offsetHeight + 120;
let current = sections[0];
sections.forEach((s) => {
if (s.getBoundingClientRect().top <= line) current = s;
});
// No fim da página, a última seção pode não chegar à linha: marca ela mesmo assim
if (window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 2) {
current = sections[sections.length - 1];
}
tocLinks.forEach((a) => a.setAttribute("aria-current", String(a.getAttribute("href") === `#${current.id}`)));
};
if (sections.length) {
markCurrent();
window.addEventListener("scroll", markCurrent, { passive: true });
}
// Efeito de digitação no cargo e nas linguagens da home: ao passar o mouse (ou tocar) em uma das duas linhas,
// as duas são apagadas e redigitadas uma depois da outra, com um cursor aceso enquanto digita e piscando quando
// para, como no terminal. O texto
// completo fica num <span class="sr-only"> para leitores de tela; o que anima é uma cópia com aria-hidden.
// A montagem é feita aqui, e não no HTML, porque o terminal lê essas linhas do HTML da home (DOMParser).
const typeLines = [...document.querySelectorAll(".hero .role, .hero .stack")].map((el) => {
const full = el.textContent;
const visible = document.createElement("span");
visible.className = "type-visible";
visible.setAttribute("aria-hidden", "true");
visible.textContent = full;
const hidden = document.createElement("span");
hidden.className = "sr-only";
hidden.textContent = full;
el.replaceChildren(hidden, visible);
return { el, full, visible };
});
let typingRun = false;
const typeAll = async () => {
if (typingRun || matchMedia("(prefers-reduced-motion: reduce)").matches) return;
typingRun = true;
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
// Trava a altura de cada linha: se ela quebrar em duas no celular, apagar não pode puxar o resto da tela para cima
typeLines.forEach((l) => (l.el.style.minHeight = `${l.el.getBoundingClientRect().height}px`));
// Apaga as duas juntas, de trás para frente, duas letras por vez, até não sobrar nenhuma
const longest = Math.max(...typeLines.map((l) => l.full.length));
typeLines[0].el.classList.add("typing", "typing-busy");
for (let n = longest; n > -2; n -= 2) {
typeLines.forEach((l) => (l.visible.textContent = l.full.slice(0, Math.max(0, Math.min(n, l.full.length))) || "\u200b"));
await wait(16);
}
// Redigita uma linha de cada vez; o cursor passa para a linha de baixo, aceso enquanto digita
for (const [i, l] of typeLines.entries()) {
typeLines.forEach((other) => {
other.el.classList.toggle("typing", other === l);
other.el.classList.toggle("typing-busy", other === l);
});
for (let n = 1; n <= l.full.length; n++) {
l.visible.textContent = l.full.slice(0, n);
await wait(l.full[n - 1] === " " ? 20 : 38);
}
l.el.classList.remove("typing-busy");
if (i < typeLines.length - 1) await wait(150);
}
await wait(1200);
typeLines.forEach((l) => {
l.el.classList.remove("typing", "typing-busy");
l.el.style.minHeight = "";
});
typingRun = false;
};
typeLines.forEach((l) => l.el.addEventListener("pointerenter", typeAll));
// Transição do cabeçalho entre páginas, para navegadores sem View Transitions entre documentos (o Firefox,
// até a versão 157 pelo menos). No Chrome, Edge e Safari quem anima é o CSS (@view-transition em style.css).
// Ao sair, guarda onde estavam o logo, cada link do menu e os botões da direita, com a largura e a cor do texto;
// na página nova, cada peça começa no lugar, num tamanho próximo e na cor antigos e desliza até os novos (técnica FLIP).
// Só transform, opacity e color são animados: nada muda o layout durante a animação, então nada "pula".
// Duração e curva iguais às do CSS (::view-transition-group em style.css).
const NAV_KEY = "nav-header";
const PAGE_TRANSITION = { duration: 500, easing: "cubic-bezier(0.65, 0, 0.35, 1)" };
const headerParts = () => {
const parts = { logo: document.querySelector(".site-header .logo"), actions: document.querySelector(".header-actions") };
document.querySelectorAll(".nav a").forEach((a, i) => (parts[`nav-${i + 1}`] = a));
return parts;
};
const snapshot = (el) => {
const r = el?.getBoundingClientRect();
if (!r || !r.width) return null;
return { x: r.left + r.width / 2, y: r.top + r.height / 2, right: r.right, width: r.width, color: getComputedStyle(el).color };
};
addEventListener("pagehide", () => {
if (window.CSSViewTransitionRule) return;
const parts = {};
Object.entries(headerParts()).forEach(([key, el]) => (parts[key] = snapshot(el)));
try {
sessionStorage.setItem(NAV_KEY, JSON.stringify({ t: Date.now(), path: location.pathname, paper: document.body.classList.contains("paper-page"), parts }));
} catch {
// sem sessionStorage, a página só troca, sem animação
}
});
(() => {
let saved = null;
try {
saved = JSON.parse(sessionStorage.getItem(NAV_KEY));
sessionStorage.removeItem(NAV_KEY);
} catch {
return;
}
// Só logo depois de uma navegação para outra página (não num recarregamento nem numa visita de outro dia)
if (!saved?.parts || Date.now() - saved.t > 3000 || saved.path === location.pathname) return;
if (window.CSSViewTransitionRule || matchMedia("(prefers-reduced-motion: reduce)").matches) return;
const moves = Object.entries(headerParts())
.map(([key, el]) => ({ key, el, from: saved.parts[key], to: snapshot(el) }))
.filter((m) => m.from && m.to);
// Uma escala só para todos os links (a menor razão entre a largura antiga e a nova): o texto muda de tamanho por
// igual, e nenhum link fica maior que o espaço que ocupava, então não encosta no vizinho (as maiúsculas são mais largas)
const navScale = Math.min(...moves.filter((m) => m.key.startsWith("nav-")).map((m) => m.from.width / m.to.width));
moves.forEach(({ key, el, from, to }) => {
if (key === "actions") {
// Os botões da direita mudam de conteúdo (⌘ ↔ busca): presos pela borda direita, só aparecem aos poucos
el.animate([{ transform: `translateX(${from.right - to.right}px)`, opacity: 0 }, { transform: "none", opacity: 1 }], PAGE_TRANSITION);
return;
}
// Logo e links: saem do centro e da cor antigos
const scale = key === "logo" ? 1 : navScale;
el.animate(
[
{ transform: `translate(${from.x - to.x}px, ${from.y - to.y}px) scale(${scale})`, color: from.color, opacity: key === "logo" ? 1 : 0.6 },
{ transform: "none", color: to.color, opacity: 1 },
],
PAGE_TRANSITION
);
});
// A borda de baixo do cabeçalho só existe nas páginas .paper-page: aparece aos poucos
const siteHeader = document.querySelector(".site-header");
if (siteHeader && document.body.classList.contains("paper-page") && !saved.paper) {
siteHeader.animate([{ borderBottomColor: "transparent" }, { borderBottomColor: getComputedStyle(siteHeader).borderBottomColor }], PAGE_TRANSITION);
}
// O conteúdo da página nova surge aos poucos, como no Chrome
document.querySelectorAll("main, .site-footer").forEach((el) => el.animate([{ opacity: 0 }, { opacity: 1 }], PAGE_TRANSITION));
})();
})();