Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix copy button invalid & copy button (invisible) duplication bug in chatbot #4350

Merged
merged 10 commits into from
Jun 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
- Prevent path traversal in `/file` routes by [@abidlabs](https://github.com/abidlabs) in [PR 4370](https://github.com/gradio-app/gradio/pull/4370).
- Do not send HF token to other domains via `/proxy` route by [@abidlabs](https://github.com/abidlabs) in [PR 4368](https://github.com/gradio-app/gradio/pull/4368).
- Replace default `markedjs` sanitize function with DOMPurify sanitizer for `gr.Chatbot()` by [@dawoodkhan82](https://github.com/dawoodkhan82) in [PR 4360](https://github.com/gradio-app/gradio/pull/4360)
- Prevent the creation of duplicate copy buttons in the chatbot and ensure copy buttons work in non-secure contexts by [@binary-husky](https://github.com/binary-husky) in [PR 4350](https://github.com/gradio-app/gradio/pull/4350).

## Other Changes:

Expand Down
2 changes: 1 addition & 1 deletion demo/chatbot_simple/run.ipynb
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: chatbot_simple"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import random\n", "import time\n", "\n", "with gr.Blocks() as demo:\n", " chatbot = gr.Chatbot()\n", " msg = gr.Textbox()\n", " clear = gr.Button(\"Clear\")\n", "\n", " def respond(message, chat_history):\n", " bot_message = random.choice([\"How are you?\", \"I love you\", \"I'm very hungry\"])\n", " chat_history.append((message, bot_message))\n", " time.sleep(1)\n", " return \"\", chat_history\n", "\n", " msg.submit(respond, [msg, chatbot], [msg, chatbot])\n", " clear.click(lambda: None, None, chatbot, queue=False)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: chatbot_simple"]}, {"cell_type": "code", "execution_count": null, "id": 272996653310673477252411125948039410165, "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": 288918539441861185822528903084949547379, "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import random\n", "import time\n", "\n", "md = \"\"\"This is some code:\n", "\n", "<h1>hello</h1>\n", "\n", "```py\n", "def fn(x, y, z):\n", " print(x, y, z)\n", "\"\"\"\n", "\n", "with gr.Blocks() as demo:\n", " chatbot = gr.Chatbot()\n", " msg = gr.Textbox()\n", " clear = gr.Button(\"Clear\")\n", "\n", " def respond(message, chat_history):\n", " bot_message = random.choice([\"How are you?\", \"I love you\", \"I'm very hungry\"])\n", " chat_history.append((message, md))\n", " time.sleep(1)\n", " return \"\", chat_history\n", "\n", " msg.submit(respond, [msg, chatbot], [msg, chatbot])\n", " clear.click(lambda: None, None, chatbot, queue=False)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
11 changes: 10 additions & 1 deletion demo/chatbot_simple/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,23 @@
import random
import time

md = """This is some code:

<h1>hello</h1>

```py
def fn(x, y, z):
print(x, y, z)
"""

with gr.Blocks() as demo:
chatbot = gr.Chatbot()
msg = gr.Textbox()
clear = gr.Button("Clear")

def respond(message, chat_history):
bot_message = random.choice(["How are you?", "I love you", "I'm very hungry"])
chat_history.append((message, bot_message))
chat_history.append((message, md))
time.sleep(1)
return "", chat_history

Expand Down
11 changes: 6 additions & 5 deletions js/chatbot/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,17 @@
"license": "ISC",
"private": true,
"dependencies": {
"@gradio/icons": "workspace:^0.0.1",
"@gradio/theme": "workspace:^0.0.1",
"@gradio/utils": "workspace:^0.0.1",
"@gradio/upload": "workspace:^0.0.1",
"@gradio/icons": "workspace:^0.0.1",
"marked": "^5.0.1",
"@gradio/utils": "workspace:^0.0.1",
"@types/katex": "^0.16.0",
"@types/marked": "^4.3.0",
"prismjs": "1.29.0",
"@types/prismjs": "1.26.0",
"katex": "^0.16.7",
"@types/katex": "^0.16.0",
"marked": "^5.0.1",
"marked-highlight": "^2.0.1",
"prismjs": "1.29.0",
"dompurify": "^3.0.3",
"@types/dompurify": "^3.0.2"
}
Expand Down
103 changes: 53 additions & 50 deletions js/chatbot/src/ChatBot.svelte
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
<script lang="ts">
import { marked } from "marked";
import Prism from "prismjs";
import "prismjs/components/prism-python";
import "prismjs/components/prism-latex";
import { marked, copy } from "./utils";
import "katex/dist/katex.min.css";
import DOMPurify from "dompurify";
import render_math_in_element from "katex/dist/contrib/auto-render.js";
import { beforeUpdate, afterUpdate, createEventDispatcher } from "svelte";
import type { Styles, SelectData } from "@gradio/utils";
import type { ThemeMode } from "js/app/src/components/types";
import type { FileData } from "@gradio/upload";
import Copy from "./Copy.svelte";

const code_highlight_css = {
light: () => import("prismjs/themes/prism.css"),
Expand All @@ -34,26 +30,6 @@
} else {
code_highlight_css.light();
}
const marked_renderer = new marked.Renderer();
marked.setOptions({
renderer: marked_renderer,
gfm: true,
breaks: true,
pedantic: false,
sanitize: false,
smartLists: true,
smartypants: false
});

marked.setOptions({
highlight: (code: string, lang: string) => {
if (Prism.languages[lang]) {
return Prism.highlight(code, Prism.languages[lang], lang);
} else {
return code;
}
}
});

let div: HTMLDivElement;
let autoscroll: Boolean;
Expand All @@ -77,25 +53,6 @@
});
});
}
div.querySelectorAll("pre > code").forEach((n) => {
let code_node = n as HTMLElement;
const copy_div = document.createElement("div");
new Copy({
target: copy_div,
props: {
value: code_node.innerText.trimEnd()
}
});
let node = n.parentElement as HTMLElement;
copy_div.style.position = "absolute";
copy_div.style.right = "0";
copy_div.style.top = "0";
copy_div.style.zIndex = "1";
copy_div.style.padding = "var(--spacing-md)";
copy_div.style.borderBottomLeftRadius = "var(--radius-sm)";
node.style.position = "relative";
node.appendChild(copy_div);
});

render_math_in_element(div, {
delimiters: [
Expand All @@ -112,6 +69,17 @@
dispatch("change");
}
}

function handle_select(
i: number,
j: number,
message: string | FileData | null
) {
dispatch("select", {
index: [i, j],
value: message
});
}
</script>

<div
Expand All @@ -120,7 +88,7 @@
style:max-height={`${style.height}px`}
bind:this={div}
>
<div class="message-wrap">
<div class="message-wrap" use:copy>
{#if value !== null}
{#each value as message_pair, i}
{#each message_pair as message, j}
Expand All @@ -131,11 +99,7 @@
class="message {j == 0 ? 'user' : 'bot'}"
class:hide={message === null}
class:selectable
on:click={() =>
dispatch("select", {
index: [i, j],
value: message
})}
on:click={() => handle_select(i, j, message)}
>
{#if typeof message === "string"}
{@html DOMPurify.sanitize(marked.parse(message))}
Expand Down Expand Up @@ -371,4 +335,43 @@
.message-wrap :global(span.katex) {
font-size: var(--text-lg);
}

/* Copy button */
.message-wrap :global(code > button) {
position: absolute;
top: var(--spacing-md);
right: var(--spacing-md);
z-index: 1;
cursor: pointer;
border-bottom-left-radius: var(--radius-sm);
padding: 5px;
padding: var(--spacing-md);
width: 22px;
height: 22px;
}

.message-wrap :global(code > button > span) {
position: absolute;
top: var(--spacing-md);
right: var(--spacing-md);
width: 12px;
height: 12px;
}
.message-wrap :global(.check) {
position: absolute;
top: 0;
right: 0;
opacity: 0;
z-index: var(--layer-top);
transition: opacity 0.2s;
background: var(--background-fill-primary);
padding: var(--size-1);
width: 100%;
height: 100%;
color: var(--body-text-color);
}

.message-wrap :global(pre) {
position: relative;
}
</style>
20 changes: 18 additions & 2 deletions js/chatbot/src/Copy.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,24 @@
if ("clipboard" in navigator) {
await navigator.clipboard.writeText(value);
copy_feedback();
} else {
const textArea = document.createElement("textarea");
textArea.value = value;

textArea.style.position = "absolute";
textArea.style.left = "-999999px";

document.body.prepend(textArea);
textArea.select();

try {
document.execCommand("copy");
copy_feedback();
} catch (error) {
console.error(error);
} finally {
textArea.remove();
}
}
}

Expand All @@ -28,9 +46,7 @@
</script>

<button on:click={handle_copy} title="copy">
<!-- {#if !copied} -->
<span class="copy-text" class:copied><Copy /> </span>
<!-- {/if} -->
{#if copied}
<span class="check" transition:fade><Check /></span>
{/if}
Expand Down
Loading