const resampler = element.querySelector(".resampler"); const form = element.querySelector("#composer"); const prompt = element.querySelector("#prompt"); const reasoning = element.querySelector("#reasoning"); const generate = element.querySelector("#generate"); const stop = element.querySelector("#stop"); const status = element.querySelector("#status"); const thought = element.querySelector("#thought"); const thinkingLabel = element.querySelector("#thinking-label"); const reasoningOutput = element.querySelector("#reasoning-output"); const answerOutput = element.querySelector("#answer-output"); const copy = element.querySelector("#copy"); const remake = element.querySelector("#remake"); const resultActions = element.querySelector("#result-actions"); const error = element.querySelector("#error"); const example = element.querySelector("#example"); const history = element.querySelector("#prompt-history"); const historyTab = history.parentElement; let requestId = null; let activeSession = null; let selectedSession = null; const sentPrompt = element.querySelector("#sent-prompt"); function followReasoning() { if (thought.open && thinkingLabel.classList.contains("shimmer")) { reasoningOutput.scrollTop = reasoningOutput.scrollHeight; } } thought.addEventListener("toggle", followReasoning); function formatThinkingTime(milliseconds) { const totalSeconds = Math.round(milliseconds / 1000); const minutes = Math.floor(totalSeconds / 60); const seconds = totalSeconds % 60; const secondsLabel = seconds + (seconds === 1 ? " second" : " seconds"); if (!minutes) return totalSeconds ? secondsLabel : "less than a second"; return minutes + (minutes === 1 ? " minute" : " minutes") + " and " + secondsLabel; } function renderSession() { sentPrompt.hidden = !selectedSession; sentPrompt.textContent = selectedSession?.prompt ?? ""; const thinking = selectedSession && selectedSession === activeSession && !selectedSession.answer?.trim(); const hasReasoning = Boolean(selectedSession?.reasoning?.trim()); const label = thinking ? "Thinking" : hasReasoning ? "Thought for " + formatThinkingTime(selectedSession.thinkingDuration) : ""; if (thinkingLabel.textContent !== label) thinkingLabel.textContent = label; thinkingLabel.classList.toggle("shimmer", Boolean(thinking)); status.textContent = selectedSession?.status ?? ""; answerOutput.textContent = selectedSession?.answer ?? ""; const reasoningText = selectedSession?.reasoning ?? ""; const reasoningChanged = reasoningOutput.textContent !== reasoningText; const reasoningScrollTop = reasoningOutput.scrollTop; const atReasoningEnd = reasoningOutput.scrollHeight - reasoningOutput.clientHeight - reasoningScrollTop <= 2; if (reasoningChanged) reasoningOutput.textContent = reasoningText; reasoningOutput.hidden = !hasReasoning; thought.hidden = !thinking && !hasReasoning; if (reasoningChanged && thought.open) { if (atReasoningEnd) followReasoning(); else reasoningOutput.scrollTop = reasoningScrollTop; } error.textContent = selectedSession?.error ?? ""; error.hidden = !selectedSession?.error; resultActions.hidden = !selectedSession?.answer || selectedSession === activeSession; remake.disabled = Boolean(requestId); syncControls(); } function selectSession(session) { selectedSession?.button.removeAttribute("aria-current"); selectedSession = session; session?.button.setAttribute("aria-current", "true"); thought.open = false; copy.title = "Copy"; copy.setAttribute("aria-label", "Copy"); renderSession(); } function sizeHistoryTab() { const width = Math.max(0, ...Array.from(history.querySelectorAll(".prompt-history-preview"), node => node.scrollWidth)); historyTab.style.setProperty("--history-text-size", width + "px"); } document.fonts.ready.then(sizeHistoryTab); function addSentPrompt(text, thinking) { const item = document.createElement("li"); const number = history.children.length + 1; const badge = document.createElement("span"); badge.className = "prompt-history-number"; badge.textContent = number; const preview = document.createElement("span"); preview.className = "prompt-history-preview"; const characters = Array.from(text); preview.textContent = characters.slice(0, 40).join("").replace(/\s+/g, " "); preview.toggleAttribute("data-truncated", characters.length > 40); const button = document.createElement("button"); button.type = "button"; button.className = "prompt-history-button"; button.append(badge, preview); button.setAttribute("aria-label", "Prompt " + number + ": " + preview.textContent); item.append(button); item.dataset.pending = "true"; const session = {prompt: text, thinking, item, button}; button.addEventListener("click", () => selectSession(session)); history.hidden = false; history.append(item); sizeHistoryTab(); history.scrollTop = history.scrollHeight; return session; } const historyHoverPadding = 64; document.addEventListener("pointermove", event => { if (event.pointerType !== "mouse" || history.hidden) return; const {left, right, top, bottom} = historyTab.getBoundingClientRect(); const nearby = event.clientX >= left - historyHoverPadding && event.clientX <= right + historyHoverPadding && event.clientY >= top - historyHoverPadding && event.clientY <= bottom + historyHoverPadding; historyTab.toggleAttribute("data-nearby", nearby); }); document.addEventListener("pointerleave", () => historyTab.removeAttribute("data-nearby")); historyTab.addEventListener("click", event => { if (event.pointerType === "touch" || !matchMedia("(hover: hover)").matches) { if (!historyTab.hasAttribute("data-expanded")) { historyTab.setAttribute("data-expanded", ""); } else if (!event.target.closest("button")) { historyTab.removeAttribute("data-expanded"); } } }); element.addEventListener("pointerdown", event => { if (!historyTab.contains(event.target)) historyTab.removeAttribute("data-expanded"); }); function resizePrompt() { const scrollTop = prompt.scrollTop; prompt.style.overflowY = "hidden"; prompt.style.height = "0px"; prompt.style.height = prompt.scrollHeight + "px"; if (prompt.scrollHeight > prompt.clientHeight + 1) { prompt.style.overflowY = "auto"; prompt.scrollTop = scrollTop; } } function syncPrompt() { resizePrompt(); syncControls(); } function syncControls() { generate.disabled = !prompt.value.trim() || Boolean(requestId); prompt.readOnly = Boolean(requestId); example.disabled = Boolean(requestId); generate.hidden = Boolean(requestId); stop.hidden = !requestId; } function stopThinkingTimer(session) { if (session.thinkingDuration === null) { session.thinkingDuration = performance.now() - (session.thinkingStarted ?? session.submittedAt); } } function finish(message) { stopThinkingTimer(activeSession); activeSession.status = message; delete activeSession.item.dataset.pending; activeSession = null; requestId = null; renderSession(); } function showError(message) { activeSession.error = message; finish(""); } window.addEventListener("resampler:update", ({ detail }) => { if (!requestId || detail.requestId !== requestId) return; switch (detail.kind) { case "start": activeSession.thinkingStarted ??= performance.now(); break; case "update": activeSession.reasoning = detail.reasoning; activeSession.answer = detail.answer; if (detail.answer?.trim()) stopThinkingTimer(activeSession); break; case "done": finish(detail.limited ? "Generation limit reached." : ""); return; case "error": showError(detail.message); return; } if (selectedSession === activeSession) renderSession(); }); window.addEventListener("resampler:failed", () => { if (requestId) showError("Generation could not start. Check the ZeroGPU message and try again."); }); function startGeneration(session, retry = false) { requestId = crypto.randomUUID(); activeSession = session; session.item.dataset.pending = "true"; session.status = ""; session.error = ""; session.reasoning = ""; session.answer = ""; session.submittedAt = performance.now(); session.thinkingStarted = null; session.thinkingDuration = null; form.dataset.request = JSON.stringify({ request_id: requestId, prompt: session.prompt, reasoning: session.thinking, remake: retry, }); selectSession(session); trigger("submit_prompt"); } form.addEventListener("submit", event => { event.preventDefault(); if (generate.disabled || requestId) return; const session = addSentPrompt(prompt.value.trim(), reasoning.checked); prompt.value = ""; resizePrompt(); startGeneration(session); const thinkingTop = thought.getBoundingClientRect().top - resampler.getBoundingClientRect().top; if (thinkingTop > resampler.clientHeight * 0.4) { resampler.scrollBy({ top: thinkingTop - resampler.clientHeight * 0.33 }); } }); remake.addEventListener("click", () => { if (!requestId && selectedSession) startGeneration(selectedSession, true); }); stop.addEventListener("click", () => { trigger("stop_prompt"); finish("Generation stopped."); }); prompt.addEventListener("input", syncPrompt); window.addEventListener("resize", resizePrompt); prompt.addEventListener("keydown", event => { if (event.key === "Enter" && (event.metaKey || event.ctrlKey) && !event.isComposing) { event.preventDefault(); form.requestSubmit(); } }); example.addEventListener("click", () => { prompt.value = "Maya buys four notebooks for $3 each and pays with a $20 bill. How much change does she get?"; prompt.focus(); syncPrompt(); }); copy.addEventListener("click", async () => { try { await navigator.clipboard.writeText(answerOutput.textContent); copy.title = "Copied"; copy.setAttribute("aria-label", "Copied"); } catch { copy.title = "Copy unavailable"; copy.setAttribute("aria-label", "Copy unavailable"); } }); const composerObserver = new ResizeObserver(([entry]) => { resampler.style.setProperty("--composer-height", entry.target.offsetHeight + "px"); }); composerObserver.observe(form); syncPrompt();