Files
playground/chat.html
T
abdus 89f2d784a1 feat(chat): Copy buttons for code blocks
feat(chat): New models
feat(chat): Gemini with less thinking
fix(chat): Better scroll to bottom
2025-12-23 07:57:25 +01:00

705 lines
25 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Cet ci pi ti</title>
<style>
:root {
color-scheme: light dark;
--bg-primary: Canvas;
--bg-secondary: #ccc;
--bg-input: #f0f0f0;
--bg-user-message: Highlight;
--bg-code: Field;
--text-primary: CanvasText;
--text-user: HighlightText;
--border-color: #aaa;
}
@media (prefers-color-scheme: dark) {
:root {
--bg-secondary: #555;
--bg-input: #444;
}
}
*,
*::before,
*::after {
box-sizing: border-box;
font-family: inherit;
}
body {
margin: 0;
/* font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; */
font-family: "JetBrains Mono", Consolas, Menlo, monospace;
line-height: 1.6;
font-size: 14px;
/* color: var(--text-primary); */
}
a {
color: var(--text-user);
text-decoration: none;
}
.chat-container {
height: 100vh;
display: grid;
grid-template-columns: 1fr min-content;
grid-template-rows: 1fr min-content;
gap: 1rem;
padding: 1rem;
grid-template-areas:
"messages messages"
"prompt submit";
}
.messages {
grid-area: messages;
overflow-y: auto;
padding-right: 0.5rem;
}
.message {
padding: 0.8rem 1.2rem;
border-radius: 0.8rem;
max-width: 85%;
}
textarea,
button {
font-size: inherit;
font-family: inherit;
appearance: none;
}
.button {
text-transform: uppercase;
letter-spacing: 0.05em;
}
.message + .message {
margin-top: 1rem;
}
.user-message {
color: var(--text-user);
background: var(--bg-user-message);
margin-left: auto;
white-space: pre-wrap;
}
.system-message {
background: var(--bg-secondary);
margin-right: auto;
}
.system-message pre,
.system-message code,
.system-message pre {
font-family: menlo, consolas, monospace;
background: var(--bg-code);
border-radius: 0.4rem;
}
.system-message pre {
position: relative;
padding: 0.5rem 2.5rem 0.5rem 0.5rem;
white-space: pre;
overflow-x: auto;
}
.copy-btn {
position: absolute;
top: 0.4rem;
right: 0.6rem;
background: var(--bg-secondary);
color: var(--text-primary);
border: none;
border-radius: 0.3rem;
padding: 0.2rem 0.6rem;
font-size: 0.9em;
cursor: pointer;
opacity: 0.6;
transition: opacity 0.2s;
z-index: 2;
}
.copy-btn:hover {
opacity: 1;
}
.system-message code {
padding: 2px 4px;
}
.prompt {
grid-area: prompt;
min-height: 40px;
padding: 0.8rem;
border: none;
border-radius: 0.4rem;
/* background: var(--bg-input); */
/* color: var(--text-primary); */
resize: vertical;
}
.submit {
grid-area: submit;
cursor: pointer;
padding: 0.8rem 2rem;
background: var(--bg-secondary);
/* color: var(--text-primary); */
border: none;
border-radius: 0.4rem;
transition: background-color 0.2s ease;
}
.submit:hover {
background: var(--bg-user-message);
}
/* Scrollbar styling */
.messages::-webkit-scrollbar {
width: 4px;
}
.messages::-webkit-scrollbar-track {
background: var(--bg-primary);
}
.messages::-webkit-scrollbar-thumb {
background: var(--border-color);
border-radius: 4px;
}
/* Focus styles */
.prompt:focus,
.submit:focus {
outline: none;
border-color: var(--bg-user-message);
}
.submit {
anchor-name: --submit;
}
@keyframes pulse {
20% {
opacity: 0.8;
}
}
.submit.busy {
animation: both pulse 1s;
}
#model-selector {
position: absolute;
position-anchor: --submit;
bottom: anchor(top);
right: anchor(right);
opacity: 0.3;
padding: 0.5rem;
}
#model-selector:is(:hover, [open]) {
opacity: 1;
}
#model-selector summary {
font-weight: bold;
}
.model-opt__label {
display: block;
}
details {
cursor: pointer;
}
blockquote {
padding: 1rem;
margin: 1rem 0;
background-color: rgba(0, 0, 0, 0.1);
border-left: 3px solid dodgerblue;
}
blockquote > p + p {
margin: 1em 0 0 0;
}
blockquote > p:only-child {
margin: 0;
}
ul {
padding-left: 1rem;
}
td {
vertical-align: top;
}
th {
vertical-align: top;
}
tr:nth-child(odd) {
background-color: rgba(0, 0, 0, 0.05);
}
</style>
</head>
<body>
<div id="app">
<div class="chat-container">
<div id="messages" class="messages"></div>
<textarea rows="6" id="prompt" class="prompt" placeholder="Type your message..."></textarea>
<button id="submit" class="submit button">Send</button>
<details id="model-selector">
<summary>Model</summary>
</details>
</div>
</div>
<script type="module">
import * as smd from "https://cdn.jsdelivr.net/npm/streaming-markdown@latest/smd.min.js";
window.env ??= {};
const models = [
{ name: "gpt-4.1", chat: chatWithOpenAI },
{ name: "gpt-4.1-mini", chat: chatWithOpenAI },
{ name: "gemini-3-flash-preview", chat: chatWithGemini },
{ name: "claude-haiku-4-5-20251001", chat: chatWithClaude },
];
window.env.MODEL ||= "gemini-3-flash-preview";
const systemPrompt = `You are a helpful AI assistant.
Do not preach about implications,
do not praise excessively.
Keep a critical mindset,
do not assume blindly.
Answer in valid markdown.`;
const messages = [
{
role: "system",
content: systemPrompt,
},
];
const $messages = document.querySelector("#messages");
const $prompt = document.querySelector("#prompt");
const $submit = document.querySelector("#submit");
const $modelSelector = document.querySelector("#model-selector");
// grow the prompt textarea as needed
const minRows = +$prompt.rows;
const maxRows = 10;
$prompt.addEventListener(
"input",
debounce((e) => {
const lines = e.target.value.split("\n").length;
e.target.rows = Math.min(maxRows, Math.max(minRows, lines));
}, 100)
);
// populate model selector
$modelSelector.append(
...models.map((model) => {
return Object.assign(document.createElement("label"), {
className: "model-opt__label",
innerHTML: `<div><input type="radio" name="model" value="${model.name}" />${model.name}</div>`,
});
})
);
$modelSelector.addEventListener("mouseenter", (e) => {
const open = $modelSelector.hasAttribute("open");
if (!open) {
$modelSelector.setAttribute("open", "");
}
});
document.querySelectorAll("[name=model]").forEach(($option) => {
if ($option.value === window.env.MODEL) {
$option.checked = true;
}
});
/** @type {AbortController} */
let abortController = null;
$submit.addEventListener("click", () => {
if (abortController) {
abortController.abort();
} else {
handleSubmit();
}
});
$prompt.addEventListener("keydown", (e) => {
if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
e.preventDefault();
if (!abortController) {
handleSubmit();
}
}
});
const injectedPrompt = window.env.PROMPT?.trim() ?? "";
if (injectedPrompt) {
$prompt.value = injectedPrompt + "\n\n";
}
$prompt.focus();
async function handleSubmit() {
const prompt = $prompt.value.trim();
if (!prompt) return;
$modelSelector.removeAttribute("open");
// Add user message
const $userMessage = createMessageElement(prompt, true);
$messages.appendChild($userMessage);
messages.push({ role: "user", content: prompt });
// Prepare for system response
const $systemMessage = createMessageElement("", false);
$messages.appendChild($systemMessage);
const md = new StreamingMarkdown($systemMessage);
let fullResponse = "";
$prompt.value = "";
scrollToBottom($messages);
abortController = new AbortController();
const pickedModel = document.querySelector("[name=model]:checked")?.value;
const chat = models.find((m) => m.name === pickedModel)?.chat;
if (!chat) {
console.error(`Unknown model: ${window.env.MODEL}`);
return;
}
$submit.textContent = "Cancel";
$submit.classList.add("busy");
try {
await chat({
model: pickedModel,
onContent: (content) => {
fullResponse += content;
md.append(content);
scrollToBottom($messages);
},
onError(e) {
md.append("ERROR:```\n" + e.message + "\n```");
},
messages,
signal: abortController.signal,
});
if (fullResponse.trim() !== "") {
messages.push({ role: "assistant", content: fullResponse });
}
} catch (err) {
if (err.name === "AbortError") {
md.append("\n\n[Cancelled]");
} else {
md.append("\n\n[Error: " + err.message + "]");
}
} finally {
md.finish();
$submit.textContent = "Send";
$submit.classList.remove("busy");
abortController = null;
}
}
function createMessageElement(content, isUser) {
const $el = document.createElement("div");
$el.className = `message ${isUser ? "user-message" : "system-message"}`;
if (isUser) {
$el.innerText = content;
}
return $el;
}
// Auto scroll functionality
let userHasScrolledUp = false;
// Function to check if user is at the bottom
function isAtBottom($el) {
const threshold = 50; // Allow some tolerance (50px from bottom)
return $el.scrollHeight - $el.clientHeight - $el.scrollTop <= threshold;
}
const scrollToBottom = throttle(($el) => {
if (!userHasScrolledUp) {
$el.scrollTop = $el.scrollHeight;
}
}, 500);
$messages.addEventListener("scroll", () => {
userHasScrolledUp = !isAtBottom($messages);
});
/**
* @typedef {{
* onContent: (content: string) => Promise<void>,
* messages: Array<{ role: string, content: string }>,
* extraHeaders: Record<string, string>,
* signal: AbortSignal,
* apiKey: string,
* model: string,
* [key: string]: any
* }} ChatArgs
*/
/** @param {ChatArgs} args - The arguments for the chatWithClaude function. */
async function chatWithOpenAI({
baseUrl = "https://api.openai.com/v1",
onContent,
onError,
messages,
signal,
apiKey = window.env.OPENAI_API_KEY,
model,
extraHeaders = {},
...rest
}) {
const response = await fetch(`${baseUrl}/chat/completions`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
...extraHeaders,
},
body: JSON.stringify({
model,
messages,
stream: true,
...rest,
}),
signal,
});
if (!response.ok) {
const text = await response.text();
await onError?.(new Error(`HTTP ${response.status}:\n${text.trim()}`));
return;
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const text = decoder.decode(value, { stream: true });
const lines = text
.split("\n\n")
.filter((line) => !!line.trim())
.map((line) => line.trim().replace("data: ", ""));
for (const line of lines) {
if (line === "[DONE]") return;
try {
const parsed = JSON.parse(line);
const content = parsed.choices[0].delta.content;
if (content) {
await onContent(content);
}
} catch (e) {}
}
}
}
/*** @param {ChatArgs} args - The arguments for the chatWithClaude function. */
async function chatWithClaude(args) {
return chatWithOpenAI({
...args,
baseUrl: "https://api.anthropic.com/v1",
extraHeaders: {
"x-api-key": args.apiKey,
"anthropic-version": "2023-06-01",
"anthropic-dangerous-direct-browser-access": "true",
},
apiKey: window.env.ANTHROPIC_API_KEY,
});
}
/*** @param {ChatArgs} args - The arguments for the chatWithGemini function. */
/**
* Native Gemini Implementation
* @param {ChatArgs} args
*/
async function chatWithGemini({ onContent, onError, messages, signal, apiKey = window.env.GEMINI_API_KEY, model = "gemini-3-flash-preview", ...rest }) {
// Convert OpenAI message format to Gemini format
const contents = messages.map((msg) => ({
role: msg.role === "assistant" ? "model" : "user",
parts: [{ text: msg.content }],
}));
try {
const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${model}:streamGenerateContent?key=${apiKey}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
contents,
generationConfig: {
thinkingConfig: {
thinkingLevel: "low",
},
...rest,
},
}),
signal,
});
if (!response.ok) {
const text = await response.text();
await onError?.(new Error(`Gemini API Error ${response.status}: ${text}`));
return;
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
// Gemini's native stream returns a JSON array of objects.
// In a streaming context, it looks like: [ { ... }, { ... } ]
// We need to strip the brackets and commas or parse the chunks.
// Note: This is a simplified parser for the typical Gemini stream format
// which arrives as an array of JSON objects.
let startIdx;
while ((startIdx = buffer.indexOf("{")) !== -1) {
let endIdx = -1;
let depth = 0;
// Find the matching closing bracket
for (let i = startIdx; i < buffer.length; i++) {
if (buffer[i] === "{") depth++;
else if (buffer[i] === "}") depth--;
if (depth === 0) {
endIdx = i;
break;
}
}
if (endIdx === -1) break; // Incomplete JSON object
const jsonStr = buffer.substring(startIdx, endIdx + 1);
buffer = buffer.substring(endIdx + 1);
try {
const parsed = JSON.parse(jsonStr);
const content = parsed.candidates?.[0]?.content?.parts?.[0]?.text;
if (content) {
await onContent(content);
}
} catch (e) {
console.error("Error parsing Gemini chunk", e);
}
}
}
} catch (err) {
if (err.name !== "AbortError") {
await onError?.(err);
}
}
}
class StreamingMarkdown {
constructor($el) {
this.$el = $el;
this.renderer = smd.default_renderer($el);
this.parser = smd.parser(this.renderer);
}
append(markdown) {
smd.parser_write(this.parser, markdown);
// Add copy buttons after rendering new markdown
addCopyButtonsToCodeBlocks(this.$el);
}
finish() {
smd.parser_end(this.parser);
addCopyButtonsToCodeBlocks(this.$el);
}
}
/**
* Creates a debounced function that delays execution
* @param {Function} func - Function to debounce
* @param {number} delay - Delay in milliseconds
* @returns {Function} Debounced function
*/
function debounce(func, delay) {
let timeoutId;
return function debounced(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}
/**
* Creates a throttled function that limits execution frequency
* @param {Function} func - Function to throttle
* @param {number} limit - Minimum time between calls in milliseconds
* @returns {Function} Throttled function
*/
function throttle(func, limit) {
let inThrottle;
return function throttled(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
}
// Add copy-to-clipboard buttons to code blocks in system messages
function addCopyButtonsToCodeBlocks($container) {
// Only add to <pre><code>...</code></pre> blocks
$container.querySelectorAll("pre").forEach(($pre) => {
// Avoid duplicate buttons
if ($pre.querySelector(".copy-btn")) return;
const $code = $pre.querySelector("code");
if (!$code) return;
const $btn = document.createElement("button");
$btn.className = "copy-btn";
$btn.type = "button";
$btn.textContent = "Copy";
$btn.addEventListener("click", (e) => {
try {
const textArea = document.createElement("textarea");
textArea.value = $code.innerText;
document.body.appendChild(textArea);
textArea.select();
document.execCommand("copy");
document.body.removeChild(textArea);
$btn.textContent = "Copied!";
setTimeout(() => ($btn.textContent = "Copy"), 1200);
} catch {
$btn.textContent = "Failed";
setTimeout(() => ($btn.textContent = "Copy"), 1200);
}
});
$pre.appendChild($btn);
});
}
</script>
</body>
</html>