Skip to content

Commit

Permalink
feat: copy button for code block
Browse files Browse the repository at this point in the history
  • Loading branch information
urmauur committed Dec 18, 2023
1 parent c22eea9 commit aa69bc5
Show file tree
Hide file tree
Showing 3 changed files with 105 additions and 39 deletions.
33 changes: 33 additions & 0 deletions web/hooks/useClipboard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { useState } from 'react'

export function useClipboard({ timeout = 2000 } = {}) {
const [error, setError] = useState<Error | null>(null)
const [copied, setCopied] = useState(false)
const [copyTimeout, setCopyTimeout] = useState<number | null>(null)

const handleCopyResult = (value: boolean) => {
window.clearTimeout(copyTimeout!)
setCopyTimeout(window.setTimeout(() => setCopied(false), timeout))
setCopied(value)
}

const copy = (valueToCopy: any) => {
if ('clipboard' in navigator) {
navigator.clipboard
.writeText(valueToCopy)
.then(() => handleCopyResult(true))
.catch((err) => setError(err))
} else {
setError(new Error('useClipboard: navigator.clipboard is not supported'))
}
}

const reset = () => {
setCopied(false)
setError(null)
window.clearTimeout(copyTimeout!)
}

return { copy, reset, error, copied }
}
17 changes: 9 additions & 8 deletions web/screens/Chat/MessageToolbar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,11 @@ import {
} from '@janhq/core'
import { ConversationalExtension } from '@janhq/core'
import { useAtomValue, useSetAtom } from 'jotai'
import { RefreshCcw, Copy, Trash2Icon } from 'lucide-react'
import { RefreshCcw, CopyIcon, Trash2Icon, CheckIcon } from 'lucide-react'

import { twMerge } from 'tailwind-merge'

import { toaster } from '@/containers/Toast'

import { useClipboard } from '@/hooks/useClipboard'
import useSendChatMessage from '@/hooks/useSendChatMessage'

import { extensionManager } from '@/extension'
Expand All @@ -26,6 +25,7 @@ const MessageToolbar = ({ message }: { message: ThreadMessage }) => {
const thread = useAtomValue(activeThreadAtom)
const messages = useAtomValue(getCurrentChatMessagesAtom)
const { resendChatMessage } = useSendChatMessage()
const clipboard = useClipboard({ timeout: 1000 })

const onDeleteClick = async () => {
deleteMessage(message.id ?? '')
Expand Down Expand Up @@ -63,13 +63,14 @@ const MessageToolbar = ({ message }: { message: ThreadMessage }) => {
<div
className="cursor-pointer border-r border-border px-2 py-2 hover:bg-background/80"
onClick={() => {
navigator.clipboard.writeText(message.content[0]?.text?.value ?? '')
toaster({
title: 'Copied to clipboard',
})
clipboard.copy(message.content[0]?.text?.value ?? '')
}}
>
<Copy size={14} />
{clipboard.copied ? (
<CheckIcon size={14} className="text-green-600" />
) : (
<CopyIcon size={14} />
)}
</div>
<div
className="cursor-pointer px-2 py-2 hover:bg-background/80"
Expand Down
94 changes: 63 additions & 31 deletions web/screens/Chat/SimpleTextMessage/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import React, { useContext, useEffect, useState } from 'react'
import React, { useEffect, useRef, useState } from 'react'

import { ChatCompletionRole, MessageStatus, ThreadMessage } from '@janhq/core'

Expand All @@ -16,46 +15,58 @@ import LogoMark from '@/containers/Brand/Logo/Mark'

import BubbleLoader from '@/containers/Loader/Bubble'

import { useClipboard } from '@/hooks/useClipboard'

import { displayDate } from '@/utils/datetime'

import MessageToolbar from '../MessageToolbar'

import { getCurrentChatMessagesAtom } from '@/helpers/atoms/ChatMessage.atom'

const marked = new Marked(
markedHighlight({
langPrefix: 'hljs',
highlight(code, lang) {
if (lang === undefined || lang === '') {
return hljs.highlightAuto(code).value
}
try {
return hljs.highlight(code, { language: lang }).value
} catch (err) {
return hljs.highlight(code, { language: 'javascript' }).value
}
},
}),
{
renderer: {
code(code, lang, escaped) {
// Make a copy paste
return `
<pre class="hljs">
<code class="language-${lang ?? ''}">${
escaped ? code : decodeURIComponent(code)
}</code>
</pre>`
},
},
}
)

const SimpleTextMessage: React.FC<ThreadMessage> = (props) => {
let text = ''
if (props.content && props.content.length > 0) {
text = props.content[0]?.text?.value ?? ''
}
const clipboard = useClipboard({ timeout: 1000 })

const marked = new Marked(
markedHighlight({
langPrefix: 'hljs',
highlight(code, lang) {
if (lang === undefined || lang === '') {
return hljs.highlightAuto(code).value
}
try {
return hljs.highlight(code, { language: lang }).value
} catch (err) {
return hljs.highlight(code, { language: 'javascript' }).value
}
},
}),
{
renderer: {
code(code, lang, escaped) {
return `
<div class="relative code-block group/item">
<button class='text-xs copy-action hidden group-hover/item:block bg-gray-950 hover:bg-gray-950/90 text-gray-200 p-2 rounded-lg absolute top-6 right-2' >
${
clipboard.copied
? `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-check pointer-events-none text-green-600"><path d="M20 6 9 17l-5-5"/></svg>`
: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-copy pointer-events-none text-gray-400"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>`
}
</button>
<pre class="hljs">
<code class="language-${lang ?? ''}">${
escaped ? code : decodeURIComponent(code)
}</code>
</pre>
</div>
`
},
},
}
)

const parsedText = marked.parse(text)
const isUser = props.role === ChatCompletionRole.User
Expand All @@ -66,6 +77,27 @@ const SimpleTextMessage: React.FC<ThreadMessage> = (props) => {
const [tokenSpeed, setTokenSpeed] = useState(0)
const messages = useAtomValue(getCurrentChatMessagesAtom)

const codeBlockCopyEvent = useRef((e: Event) => {
const target: HTMLElement = e.target as HTMLElement
if (typeof target.className !== 'string') return null
const isCopyActionClassName = target?.className.includes('copy-action')
const isCodeBlockParent =
target.parentElement?.parentElement?.className.includes('code-block')

if (isCopyActionClassName || isCodeBlockParent) {
const content = target?.parentNode?.querySelector('code')?.innerText ?? ''
clipboard.copy(content)
}
})

useEffect(() => {
document.addEventListener('click', codeBlockCopyEvent.current)
return () => {
// eslint-disable-next-line react-hooks/exhaustive-deps
document.removeEventListener('click', codeBlockCopyEvent.current)
}
}, [])

useEffect(() => {
if (props.status === MessageStatus.Ready) {
return
Expand Down

0 comments on commit aa69bc5

Please sign in to comment.