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:
@@ -6,26 +6,21 @@
|
|||||||
<title>Cet ci pi ti</title>
|
<title>Cet ci pi ti</title>
|
||||||
<style>
|
<style>
|
||||||
:root {
|
:root {
|
||||||
/* Light theme variables */
|
color-scheme: light dark;
|
||||||
--bg-primary: #ffffff;
|
--bg-primary: Canvas;
|
||||||
--bg-secondary: hsl(220, 20%, 90%);
|
--bg-secondary: #ccc;
|
||||||
--bg-user-message: hsl(220, 58%, 80%);
|
--bg-input: #f0f0f0;
|
||||||
--bg-code: #f8f8f8;
|
--bg-user-message: Highlight;
|
||||||
--text-primary: #2c3e50;
|
--bg-code: Field;
|
||||||
--text-user: hsl(220, 78%, 22%);
|
--text-primary: CanvasText;
|
||||||
--border-color: #e1e1e1;
|
--text-user: HighlightText;
|
||||||
|
--border-color: #aaa;
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (prefers-color-scheme: dark) {
|
@media (prefers-color-scheme: dark) {
|
||||||
:root {
|
:root {
|
||||||
/* Dark theme variables */
|
--bg-secondary: #555;
|
||||||
--bg-primary: #1a1a1a;
|
--bg-input: #444;
|
||||||
--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;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -38,12 +33,11 @@
|
|||||||
|
|
||||||
body {
|
body {
|
||||||
margin: 0;
|
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;
|
font-family: "JetBrains Mono", Consolas, Menlo, monospace;
|
||||||
line-height: 1.6;
|
line-height: 1.6;
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
background-color: var(--bg-primary);
|
/* color: var(--text-primary); */
|
||||||
color: var(--text-primary);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
a {
|
a {
|
||||||
@@ -78,6 +72,13 @@
|
|||||||
textarea,
|
textarea,
|
||||||
button {
|
button {
|
||||||
font-size: inherit;
|
font-size: inherit;
|
||||||
|
font-family: inherit;
|
||||||
|
appearance: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.button {
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.05em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.message + .message {
|
.message + .message {
|
||||||
@@ -97,14 +98,36 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.system-message pre,
|
.system-message pre,
|
||||||
.system-message code {
|
.system-message code,
|
||||||
|
.system-message pre {
|
||||||
font-family: menlo, consolas, monospace;
|
font-family: menlo, consolas, monospace;
|
||||||
background: var(--bg-code);
|
background: var(--bg-code);
|
||||||
padding: 0.5rem;
|
|
||||||
border-radius: 0.4rem;
|
border-radius: 0.4rem;
|
||||||
|
}
|
||||||
|
.system-message pre {
|
||||||
|
position: relative;
|
||||||
|
padding: 0.5rem 2.5rem 0.5rem 0.5rem;
|
||||||
white-space: pre;
|
white-space: pre;
|
||||||
overflow-x: auto;
|
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 {
|
.system-message code {
|
||||||
padding: 2px 4px;
|
padding: 2px 4px;
|
||||||
@@ -114,20 +137,20 @@
|
|||||||
grid-area: prompt;
|
grid-area: prompt;
|
||||||
min-height: 40px;
|
min-height: 40px;
|
||||||
padding: 0.8rem;
|
padding: 0.8rem;
|
||||||
border: 1px solid var(--border-color);
|
border: none;
|
||||||
border-radius: 0.4rem;
|
border-radius: 0.4rem;
|
||||||
background: var(--bg-primary);
|
/* background: var(--bg-input); */
|
||||||
color: var(--text-primary);
|
/* color: var(--text-primary); */
|
||||||
resize: vertical;
|
resize: vertical;
|
||||||
}
|
}
|
||||||
|
|
||||||
.submit {
|
.submit {
|
||||||
grid-area: submit;
|
grid-area: submit;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
padding: 0.8rem 1.6rem;
|
padding: 0.8rem 2rem;
|
||||||
background: var(--bg-secondary);
|
background: var(--bg-secondary);
|
||||||
color: var(--text-primary);
|
/* color: var(--text-primary); */
|
||||||
border: 1px solid var(--border-color);
|
border: none;
|
||||||
border-radius: 0.4rem;
|
border-radius: 0.4rem;
|
||||||
transition: background-color 0.2s ease;
|
transition: background-color 0.2s ease;
|
||||||
}
|
}
|
||||||
@@ -161,12 +184,32 @@
|
|||||||
anchor-name: --submit;
|
anchor-name: --submit;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@keyframes pulse {
|
||||||
|
20% {
|
||||||
|
opacity: 0.8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.submit.busy {
|
||||||
|
animation: both pulse 1s;
|
||||||
|
}
|
||||||
|
|
||||||
#model-selector {
|
#model-selector {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
position-anchor: --submit;
|
position-anchor: --submit;
|
||||||
bottom: anchor(top);
|
bottom: anchor(top);
|
||||||
right: anchor(right);
|
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 {
|
.model-opt__label {
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
@@ -210,9 +253,9 @@
|
|||||||
<div id="app">
|
<div id="app">
|
||||||
<div class="chat-container">
|
<div class="chat-container">
|
||||||
<div id="messages" class="messages"></div>
|
<div id="messages" class="messages"></div>
|
||||||
<textarea rows="5" id="prompt" class="prompt" placeholder="Type your message..."></textarea>
|
<textarea rows="6" id="prompt" class="prompt" placeholder="Type your message..."></textarea>
|
||||||
<button id="submit" class="submit">Send</button>
|
<button id="submit" class="submit button">Send</button>
|
||||||
<details id="model-selector" popover>
|
<details id="model-selector">
|
||||||
<summary>Model</summary>
|
<summary>Model</summary>
|
||||||
</details>
|
</details>
|
||||||
</div>
|
</div>
|
||||||
@@ -224,10 +267,10 @@
|
|||||||
const models = [
|
const models = [
|
||||||
{ name: "gpt-4.1", chat: chatWithOpenAI },
|
{ name: "gpt-4.1", chat: chatWithOpenAI },
|
||||||
{ name: "gpt-4.1-mini", chat: chatWithOpenAI },
|
{ name: "gpt-4.1-mini", chat: chatWithOpenAI },
|
||||||
{ name: "gemini-2.5-flash", chat: chatWithGemini },
|
{ name: "gemini-3-flash-preview", chat: chatWithGemini },
|
||||||
{ name: "claude-3-7-sonnet-20250219", chat: chatWithClaude },
|
{ 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.
|
const systemPrompt = `You are a helpful AI assistant.
|
||||||
Do not preach about implications,
|
Do not preach about implications,
|
||||||
@@ -248,6 +291,18 @@
|
|||||||
const $submit = document.querySelector("#submit");
|
const $submit = document.querySelector("#submit");
|
||||||
const $modelSelector = document.querySelector("#model-selector");
|
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(
|
$modelSelector.append(
|
||||||
...models.map((model) => {
|
...models.map((model) => {
|
||||||
return Object.assign(document.createElement("label"), {
|
return Object.assign(document.createElement("label"), {
|
||||||
@@ -256,7 +311,7 @@
|
|||||||
});
|
});
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
$modelSelector.addEventListener("mouseover", (e) => {
|
$modelSelector.addEventListener("mouseenter", (e) => {
|
||||||
const open = $modelSelector.hasAttribute("open");
|
const open = $modelSelector.hasAttribute("open");
|
||||||
if (!open) {
|
if (!open) {
|
||||||
$modelSelector.setAttribute("open", "");
|
$modelSelector.setAttribute("open", "");
|
||||||
@@ -301,14 +356,14 @@
|
|||||||
$modelSelector.removeAttribute("open");
|
$modelSelector.removeAttribute("open");
|
||||||
|
|
||||||
// Add user message
|
// Add user message
|
||||||
const userMessage = createMessageElement(prompt, true);
|
const $userMessage = createMessageElement(prompt, true);
|
||||||
$messages.appendChild(userMessage);
|
$messages.appendChild($userMessage);
|
||||||
messages.push({ role: "user", content: prompt });
|
messages.push({ role: "user", content: prompt });
|
||||||
|
|
||||||
// Prepare for system response
|
// Prepare for system response
|
||||||
const systemMessage = createMessageElement("", false);
|
const $systemMessage = createMessageElement("", false);
|
||||||
const md = new StreamingMarkdown(systemMessage);
|
$messages.appendChild($systemMessage);
|
||||||
$messages.appendChild(systemMessage);
|
const md = new StreamingMarkdown($systemMessage);
|
||||||
let fullResponse = "";
|
let fullResponse = "";
|
||||||
|
|
||||||
$prompt.value = "";
|
$prompt.value = "";
|
||||||
@@ -326,14 +381,18 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
$submit.textContent = "Cancel";
|
$submit.textContent = "Cancel";
|
||||||
|
$submit.classList.add("busy");
|
||||||
try {
|
try {
|
||||||
await chat({
|
await chat({
|
||||||
model: pickedModel,
|
model: pickedModel,
|
||||||
onContent: (content) => {
|
onContent: (content) => {
|
||||||
fullResponse += content;
|
fullResponse += content;
|
||||||
smd.parser_write(parser, content);
|
md.append(content);
|
||||||
scrollToBottom($messages);
|
scrollToBottom($messages);
|
||||||
},
|
},
|
||||||
|
onError(e) {
|
||||||
|
md.append("ERROR:```\n" + e.message + "\n```");
|
||||||
|
},
|
||||||
messages,
|
messages,
|
||||||
signal: abortController.signal,
|
signal: abortController.signal,
|
||||||
});
|
});
|
||||||
@@ -349,6 +408,7 @@
|
|||||||
} finally {
|
} finally {
|
||||||
md.finish();
|
md.finish();
|
||||||
$submit.textContent = "Send";
|
$submit.textContent = "Send";
|
||||||
|
$submit.classList.remove("busy");
|
||||||
abortController = null;
|
abortController = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -371,14 +431,12 @@
|
|||||||
return $el.scrollHeight - $el.clientHeight - $el.scrollTop <= threshold;
|
return $el.scrollHeight - $el.clientHeight - $el.scrollTop <= threshold;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Function to scroll to bottom (only called when new content arrives)
|
const scrollToBottom = throttle(($el) => {
|
||||||
function scrollToBottom($el) {
|
|
||||||
if (!userHasScrolledUp) {
|
if (!userHasScrolledUp) {
|
||||||
$el.scrollTop = $el.scrollHeight;
|
$el.scrollTop = $el.scrollHeight;
|
||||||
}
|
}
|
||||||
}
|
}, 500);
|
||||||
|
|
||||||
// Listen for user scroll events to detect if they scrolled up
|
|
||||||
$messages.addEventListener("scroll", () => {
|
$messages.addEventListener("scroll", () => {
|
||||||
userHasScrolledUp = !isAtBottom($messages);
|
userHasScrolledUp = !isAtBottom($messages);
|
||||||
});
|
});
|
||||||
@@ -390,12 +448,23 @@
|
|||||||
* extraHeaders: Record<string, string>,
|
* extraHeaders: Record<string, string>,
|
||||||
* signal: AbortSignal,
|
* signal: AbortSignal,
|
||||||
* apiKey: string,
|
* apiKey: string,
|
||||||
* model: string
|
* model: string,
|
||||||
|
* [key: string]: any
|
||||||
* }} ChatArgs
|
* }} ChatArgs
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/** @param {ChatArgs} args - The arguments for the chatWithClaude function. */
|
/** @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`, {
|
const response = await fetch(`${baseUrl}/chat/completions`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
@@ -407,10 +476,17 @@
|
|||||||
model,
|
model,
|
||||||
messages,
|
messages,
|
||||||
stream: true,
|
stream: true,
|
||||||
|
...rest,
|
||||||
}),
|
}),
|
||||||
signal,
|
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 reader = response.body.getReader();
|
||||||
const decoder = new TextDecoder();
|
const decoder = new TextDecoder();
|
||||||
|
|
||||||
@@ -422,7 +498,7 @@
|
|||||||
const lines = text
|
const lines = text
|
||||||
.split("\n\n")
|
.split("\n\n")
|
||||||
.filter((line) => !!line.trim())
|
.filter((line) => !!line.trim())
|
||||||
.map((line) => line.replace("data: ", ""));
|
.map((line) => line.trim().replace("data: ", ""));
|
||||||
|
|
||||||
for (const line of lines) {
|
for (const line of lines) {
|
||||||
if (line === "[DONE]") return;
|
if (line === "[DONE]") return;
|
||||||
@@ -440,6 +516,7 @@
|
|||||||
/*** @param {ChatArgs} args - The arguments for the chatWithClaude function. */
|
/*** @param {ChatArgs} args - The arguments for the chatWithClaude function. */
|
||||||
async function chatWithClaude(args) {
|
async function chatWithClaude(args) {
|
||||||
return chatWithOpenAI({
|
return chatWithOpenAI({
|
||||||
|
...args,
|
||||||
baseUrl: "https://api.anthropic.com/v1",
|
baseUrl: "https://api.anthropic.com/v1",
|
||||||
extraHeaders: {
|
extraHeaders: {
|
||||||
"x-api-key": args.apiKey,
|
"x-api-key": args.apiKey,
|
||||||
@@ -447,34 +524,181 @@
|
|||||||
"anthropic-dangerous-direct-browser-access": "true",
|
"anthropic-dangerous-direct-browser-access": "true",
|
||||||
},
|
},
|
||||||
apiKey: window.env.ANTHROPIC_API_KEY,
|
apiKey: window.env.ANTHROPIC_API_KEY,
|
||||||
...args,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/*** @param {ChatArgs} args - The arguments for the chatWithGemini function. */
|
/*** @param {ChatArgs} args - The arguments for the chatWithGemini function. */
|
||||||
async function chatWithGemini(args) {
|
/**
|
||||||
return chatWithOpenAI({
|
* Native Gemini Implementation
|
||||||
baseUrl: "https://generativelanguage.googleapis.com/v1beta/openai",
|
* @param {ChatArgs} args
|
||||||
apiKey: window.env.GEMINI_API_KEY,
|
*/
|
||||||
...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 {
|
class StreamingMarkdown {
|
||||||
constructor($el) {
|
constructor($el) {
|
||||||
this.$el = $el;
|
this.$el = $el;
|
||||||
this.renderer = smd.default_renderer(systemMessage);
|
this.renderer = smd.default_renderer($el);
|
||||||
this.parser = smd.parser(renderer);
|
this.parser = smd.parser(this.renderer);
|
||||||
}
|
}
|
||||||
|
|
||||||
append(markdown) {
|
append(markdown) {
|
||||||
smd.parser_write(this.parser, markdown);
|
smd.parser_write(this.parser, markdown);
|
||||||
|
// Add copy buttons after rendering new markdown
|
||||||
|
addCopyButtonsToCodeBlocks(this.$el);
|
||||||
}
|
}
|
||||||
|
|
||||||
finish() {
|
finish() {
|
||||||
smd.parser_end(this.parser);
|
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>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
Reference in New Issue
Block a user