Remove event listeners when no longer needed to prevent memory leaks
window.addEventListener("scroll", loadVisibleTermynals);
1function setupTermynal() {2 document.querySelectorAll(".use-termynal").forEach(node => {3 node.style.display = "block";4 new Termynal(node, {5 lineDelay: 5006 });7 });8 const progressLiteralStart = "---> 100%";9 const promptLiteralStart = "$ ";10 const customPromptLiteralStart = "# ";11 const termynalActivateClass = "termy";12 let termynals = [];1314 function createTermynals() {15 document16 .querySelectorAll(`.${termynalActivateClass} .highlight code`)17 .forEach(node => {18 const text = node.textContent;19 const lines = text.split("\n");20 const useLines = [];21 let buffer = [];22 function saveBuffer() {23 if (buffer.length) {24 let isBlankSpace = true;25 buffer.forEach(line => {26 if (line) {27 isBlankSpace = false;28 }29 });30 dataValue = {};31 if (isBlankSpace) {32 dataValue["delay"] = 0;33 }34 if (buffer[buffer.length - 1] === "") {35 // A last single <br> won't have effect36 // so put an additional one37 buffer.push("");38 }39 const bufferValue = buffer.join("<br>");40 dataValue["value"] = bufferValue;41 useLines.push(dataValue);42 buffer = [];43 }44 }45 for (let line of lines) {46 if (line === progressLiteralStart) {47 saveBuffer();48 useLines.push({49 type: "progress"50 });51 } else if (line.startsWith(promptLiteralStart)) {52 saveBuffer();53 const value = line.replace(promptLiteralStart, "").trimEnd();54 useLines.push({55 type: "input",56 value: value57 });58 } else if (line.startsWith("// ")) {59 saveBuffer();60 const value = "💬 " + line.replace("// ", "").trimEnd();61 useLines.push({62 value: value,63 class: "termynal-comment",64 delay: 065 });66 } else if (line.startsWith(customPromptLiteralStart)) {67 saveBuffer();68 const promptStart = line.indexOf(promptLiteralStart);69 if (promptStart === -1) {70 console.error("Custom prompt found but no end delimiter", line)71 }72 const prompt = line.slice(0, promptStart).replace(customPromptLiteralStart, "")73 let value = line.slice(promptStart + promptLiteralStart.length);74 useLines.push({75 type: "input",76 value: value,77 prompt: prompt78 });79 } else {80 buffer.push(line);81 }82 }83 saveBuffer();84 const inputCommands = useLines85 .filter(line => line.type === "input")86 .map(line => line.value)87 .join("\n");88 node.textContent = inputCommands;89 const div = document.createElement("div");90 node.style.display = "none";91 node.after(div);92 const termynal = new Termynal(div, {93 lineData: useLines,94 noInit: true,95 lineDelay: 50096 });97 termynals.push(termynal);98 });99 }100101 function loadVisibleTermynals() {102 termynals = termynals.filter(termynal => {103 if (termynal.container.getBoundingClientRect().top - innerHeight <= 0) {104 termynal.init();105 return false;106 }107 return true;108 });109 }110 window.addEventListener("scroll", loadVisibleTermynals);111 createTermynals();112 loadVisibleTermynals();113}114115function shuffle(array) {116 var currentIndex = array.length, temporaryValue, randomIndex;117 while (0 !== currentIndex) {118 randomIndex = Math.floor(Math.random() * currentIndex);119 currentIndex -= 1;120 temporaryValue = array[currentIndex];121 array[currentIndex] = array[randomIndex];122 array[randomIndex] = temporaryValue;123 }124 return array;125}126127async function showRandomAnnouncement(groupId, timeInterval) {128 const announceFastAPI = document.getElementById(groupId);129 if (announceFastAPI) {130 let children = [].slice.call(announceFastAPI.children);131 children = shuffle(children)132 let index = 0133 const announceRandom = () => {134 children.forEach((el, i) => { el.style.display = "none" });135 children[index].style.display = "block"136 index = (index + 1) % children.length137 }138 announceRandom()139 setInterval(announceRandom, timeInterval140 )141 }142}143144function handleSponsorImages() {145 const announceRight = document.getElementById('announce-right');146 if(!announceRight) return;147148 const sponsorImages = document.querySelectorAll('.sponsor-image');149150 const imagePromises = Array.from(sponsorImages).map(img => {151 return new Promise((resolve, reject) => {152 if (img.complete && img.naturalHeight !== 0) {153 resolve();154 } else {155 img.addEventListener('load', () => {156 if (img.naturalHeight !== 0) {157 resolve();158 } else {159 reject();160 }161 });162 img.addEventListener('error', reject);163 }164 });165 });166167 Promise.all(imagePromises)168 .then(() => {169 announceRight.style.display = 'block';170 showRandomAnnouncement('announce-right', 10000);171 })172 .catch(() => {173 // do nothing174 });175}176177function openLinksInNewTab() {178 const siteUrl = document.querySelector("link[rel='canonical']")?.href179 || window.location.origin;180 const siteOrigin = new URL(siteUrl).origin;181 document.querySelectorAll(".md-content a[href]").forEach(a => {182 if (a.getAttribute("target") === "_self") return;183 const href = a.getAttribute("href");184 if (!href) return;185 try {186 const url = new URL(href, window.location.href);187 // Skip same-page anchor links (only the hash differs)188 if (url.origin === window.location.origin189 && url.pathname === window.location.pathname190 && url.search === window.location.search) return;191 if (!a.hasAttribute("target")) {192 a.setAttribute("target", "_blank");193 a.setAttribute("rel", "noopener");194 }195 if (url.origin !== siteOrigin) {196 a.dataset.externalLink = "";197 } else {198 a.dataset.internalLink = "";199 }200 } catch (_) {}201 });202}203204function setupOpinionsTabs() {205 const root = document.querySelector('.fastapi-opinions');206 if (!root) return;207 const tabs = Array.from(root.querySelectorAll('[role="tab"]'));208 const panels = Array.from(root.querySelectorAll('[role="tabpanel"]'));209 if (!tabs.length) return;210211 function activate(tab, focus) {212 tabs.forEach(t => {213 const selected = t === tab;214 t.setAttribute('aria-selected', selected ? 'true' : 'false');215 t.setAttribute('tabindex', selected ? '0' : '-1');216 });217 const targetId = tab.getAttribute('aria-controls');218 panels.forEach(p => {219 if (p.id === targetId) p.removeAttribute('hidden');220 else p.setAttribute('hidden', '');221 });222 if (focus) tab.focus();223 }224225 tabs.forEach((tab, i) => {226 tab.addEventListener('click', () => activate(tab, false));227 tab.addEventListener('keydown', (e) => {228 let next = null;229 if (e.key === 'ArrowRight') next = tabs[(i + 1) % tabs.length];230 else if (e.key === 'ArrowLeft') next = tabs[(i - 1 + tabs.length) % tabs.length];231 else if (e.key === 'Home') next = tabs[0];232 else if (e.key === 'End') next = tabs[tabs.length - 1];233 if (next) {234 e.preventDefault();235 activate(next, true);236 }237 });238 });239}240241let cleanupNewsletterEmbed = () => {};242243function setupNewsletterEmbed() {244 cleanupNewsletterEmbed();245 const frame = document.querySelector('.newsletter-embed');246 if (!frame) return;247 const origin = new URL(frame.src).origin;248 const configure = () => frame.contentWindow.postMessage({249 type: 'fastapi-newsletter:configure',250 theme: document.body.dataset.mdColorScheme === 'slate' ? 'dark' : 'light',251 fontSize: parseFloat(getComputedStyle(frame.parentElement).fontSize),252 }, origin);253 const resize = (event) => {254 if (event.origin !== origin || event.source !== frame.contentWindow) return;255 const { type, height } = event.data ?? {};256 if (type !== 'fastapi-newsletter:resize' || !Number.isFinite(height) || height <= 0 || height > 2000) return;257 frame.style.height = `${Math.ceil(height)}px`;258 };259 window.addEventListener('message', resize);260 frame.addEventListener('load', configure);261 window.addEventListener('resize', configure);262 const themeObserver = new MutationObserver(configure);263 themeObserver.observe(document.body, { attributes: true, attributeFilter: ['data-md-color-scheme'] });264 configure();265 cleanupNewsletterEmbed = () => {266 window.removeEventListener('message', resize);267 frame.removeEventListener('load', configure);268 window.removeEventListener('resize', configure);269 themeObserver.disconnect();270 };271}272273async function main() {274 setupTermynal();275 showRandomAnnouncement('announce-left', 5000)276 handleSponsorImages();277 openLinksInNewTab();278 setupOpinionsTabs();279 setupNewsletterEmbed();280}281document$.subscribe(() => {282 main()283})
Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.
Generated by searchcode.com · powered by code_get_file + code_get_findings