feat(chat): Copy buttons for code blocks

feat(chat): New models
feat(chat): Gemini with less thinking
fix(chat): Better scroll to bottom
This commit is contained in:
2025-12-23 07:57:25 +01:00
parent a201ed62d3
commit 89f2d784a1
+286 -62
View File
@@ -6,26 +6,21 @@
<title>Cet ci pi ti</title>
<style>
:root {
/* Light theme variables */
--bg-primary: #ffffff;
--bg-secondary: hsl(220, 20%, 90%);
--bg-user-message: hsl(220, 58%, 80%);
--bg-code: #f8f8f8;
--text-primary: #2c3e50;
--text-user: hsl(220, 78%, 22%);
--border-color: #e1e1e1;
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 {
/* Dark theme variables */
--bg-primary: #1a1a1a;
--bg-secondary: hsl(220, 20%, 15%);
--bg-user-message: hsl(220, 30%, 25%);
--bg-code: #2d2d2d;
--text-primary: #e1e1e1;
--text-user: hsl(220, 58%, 80%);
--border-color: #404040;
--bg-secondary: #555;
--bg-input: #444;
}
}
@@ -38,12 +33,11 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
/* 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;
background-color: var(--bg-primary);
color: var(--text-primary);
/* color: var(--text-primary); */
}
a {
@@ -78,6 +72,13 @@
textarea,
button {
font-size: inherit;
font-family: inherit;
appearance: none;
}
.button {
text-transform: uppercase;
letter-spacing: 0.05em;
}
.message + .message {
@@ -97,14 +98,36 @@
}
.system-message pre,
.system-message code {
.system-message code,
.system-message pre {
font-family: menlo, consolas, monospace;
background: var(--bg-code);
padding: 0.5rem;
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;
@@ -114,20 +137,20 @@
grid-area: prompt;
min-height: 40px;
padding: 0.8rem;
border: 1px solid var(--border-color);
border: none;
border-radius: 0.4rem;
background: var(--bg-primary);
color: var(--text-primary);
/* background: var(--bg-input); */
/* color: var(--text-primary); */
resize: vertical;
}
.submit {
grid-area: submit;
cursor: pointer;
padding: 0.8rem 1.6rem;
padding: 0.8rem 2rem;
background: var(--bg-secondary);
color: var(--text-primary);
border: 1px solid var(--border-color);
/* color: var(--text-primary); */
border: none;
border-radius: 0.4rem;
transition: background-color 0.2s ease;
}
@@ -161,12 +184,32 @@
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;
}
@@ -210,9 +253,9 @@
<div id="app">
<div class="chat-container">
<div id="messages" class="messages"></div>
<textarea rows="5" id="prompt" class="prompt" placeholder="Type your message..."></textarea>
<button id="submit" class="submit">Send</button>
<details id="model-selector" popover>
<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>
@@ -224,17 +267,17 @@
const models = [
{ name: "gpt-4.1", chat: chatWithOpenAI },
{ name: "gpt-4.1-mini", chat: chatWithOpenAI },
{ name: "gemini-2.5-flash", chat: chatWithGemini },
{ name: "claude-3-7-sonnet-20250219", chat: chatWithClaude },
{ name: "gemini-3-flash-preview", chat: chatWithGemini },
{ name: "claude-haiku-4-5-20251001", chat: chatWithClaude },
];
window.env.MODEL ||= "gemini-2.5-flash";
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 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 = [
{
@@ -248,6 +291,18 @@
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"), {
@@ -256,7 +311,7 @@
});
})
);
$modelSelector.addEventListener("mouseover", (e) => {
$modelSelector.addEventListener("mouseenter", (e) => {
const open = $modelSelector.hasAttribute("open");
if (!open) {
$modelSelector.setAttribute("open", "");
@@ -301,14 +356,14 @@
$modelSelector.removeAttribute("open");
// Add user message
const userMessage = createMessageElement(prompt, true);
$messages.appendChild(userMessage);
const $userMessage = createMessageElement(prompt, true);
$messages.appendChild($userMessage);
messages.push({ role: "user", content: prompt });
// Prepare for system response
const systemMessage = createMessageElement("", false);
const md = new StreamingMarkdown(systemMessage);
$messages.appendChild(systemMessage);
const $systemMessage = createMessageElement("", false);
$messages.appendChild($systemMessage);
const md = new StreamingMarkdown($systemMessage);
let fullResponse = "";
$prompt.value = "";
@@ -326,14 +381,18 @@
}
$submit.textContent = "Cancel";
$submit.classList.add("busy");
try {
await chat({
model: pickedModel,
onContent: (content) => {
fullResponse += content;
smd.parser_write(parser, content);
md.append(content);
scrollToBottom($messages);
},
onError(e) {
md.append("ERROR:```\n" + e.message + "\n```");
},
messages,
signal: abortController.signal,
});
@@ -349,6 +408,7 @@
} finally {
md.finish();
$submit.textContent = "Send";
$submit.classList.remove("busy");
abortController = null;
}
}
@@ -371,14 +431,12 @@
return $el.scrollHeight - $el.clientHeight - $el.scrollTop <= threshold;
}
// Function to scroll to bottom (only called when new content arrives)
function scrollToBottom($el) {
const scrollToBottom = throttle(($el) => {
if (!userHasScrolledUp) {
$el.scrollTop = $el.scrollHeight;
}
}
}, 500);
// Listen for user scroll events to detect if they scrolled up
$messages.addEventListener("scroll", () => {
userHasScrolledUp = !isAtBottom($messages);
});
@@ -390,12 +448,23 @@
* extraHeaders: Record<string, string>,
* signal: AbortSignal,
* apiKey: string,
* model: 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, messages, signal, apiKey = window.env.OPENAI_API_KEY, model, extraHeaders = {} }) {
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: {
@@ -407,10 +476,17 @@
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();
@@ -422,7 +498,7 @@
const lines = text
.split("\n\n")
.filter((line) => !!line.trim())
.map((line) => line.replace("data: ", ""));
.map((line) => line.trim().replace("data: ", ""));
for (const line of lines) {
if (line === "[DONE]") return;
@@ -440,6 +516,7 @@
/*** @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,
@@ -447,34 +524,181 @@
"anthropic-dangerous-direct-browser-access": "true",
},
apiKey: window.env.ANTHROPIC_API_KEY,
...args,
});
}
/*** @param {ChatArgs} args - The arguments for the chatWithGemini function. */
async function chatWithGemini(args) {
return chatWithOpenAI({
baseUrl: "https://generativelanguage.googleapis.com/v1beta/openai",
apiKey: window.env.GEMINI_API_KEY,
...args,
});
/**
* 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(systemMessage);
this.parser = smd.parser(renderer);
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>