Refactor copy buttons (#3456)

* refactor: moved copy logic to CopyButtonComponents.tsx

* refactor: simplified copy button components

* clean: format & cleanup code

* clean: removed comments

* fix: fixed aria labels

* clean: removed old comments

* clean: reduced deltas

* clean: deleted comment in ChatRow.tsx

* updates

* changeset

---------

Co-authored-by: Toshii <94262432+0xToshii@users.noreply.github.com>
This commit is contained in:
Hanzen ShouandToshii authored and GitHub committed 2025-06-12 10:50:59 -07:00
1 parent 8b4e8ce37f
commit 741b1edf73
4 files changed
+174 -98

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
update the copy button functionality
+16 -62
View File
@@ -1,6 +1,8 @@
import { VSCodeBadge, VSCodeButton, VSCodeProgressRing } from "@vscode/webview-ui-toolkit/react"
import deepEqual from "fast-deep-equal"
import React, { memo, MouseEvent, useCallback, useEffect, useMemo, useRef, useState } from "react"
import styled from "styled-components"
import { useEvent, useSize } from "react-use"
import CreditLimitError from "@/components/chat/CreditLimitError"
import { OptionsButtons } from "@/components/chat/OptionsButtons"
@@ -9,6 +11,8 @@ import { CheckmarkControl } from "@/components/common/CheckmarkControl"
import CodeBlock, { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock"
import MarkdownBlock from "@/components/common/MarkdownBlock"
import SuccessButton from "@/components/common/SuccessButton"
import { WithCopyButton } from "@/components/common/CopyButton"
import Thumbnails from "@/components/common/Thumbnails"
import McpResponseDisplay from "@/components/mcp/chat-display/McpResponseDisplay"
import McpResourceRow from "@/components/mcp/configuration/tabs/installed/server-row/McpResourceRow"
import McpToolRow from "@/components/mcp/configuration/tabs/installed/server-row/McpToolRow"
@@ -28,76 +32,19 @@ import {
} from "@shared/ExtensionMessage"
import { COMMAND_OUTPUT_STRING, COMMAND_REQ_APP_STRING } from "@shared/combineCommandSequences"
import { Int64Request, StringRequest } from "@shared/proto/common"
import { useEvent, useSize } from "react-use"
import styled from "styled-components"
import { CheckpointControls } from "../common/CheckpointControls"
import CodeAccordian, { cleanPathPrefix } from "../common/CodeAccordian"
import { CheckpointControls } from "../common/CheckpointControls"
import NewTaskPreview from "./NewTaskPreview"
import QuoteButton from "./QuoteButton"
import ReportBugPreview from "./ReportBugPreview"
import UserMessage from "./UserMessage"
interface CopyButtonProps {
textToCopy: string | undefined
}
import QuoteButton from "./QuoteButton"
const normalColor = "var(--vscode-foreground)"
const errorColor = "var(--vscode-errorForeground)"
const successColor = "var(--vscode-charts-green)"
const cancelledColor = "var(--vscode-descriptionForeground)"
const CopyButtonStyled = styled(VSCodeButton)`
position: absolute;
bottom: 2px;
right: 2px;
z-index: 1;
opacity: 0;
`
interface WithCopyButtonProps {
children: React.ReactNode
textToCopy?: string
style?: React.CSSProperties
ref?: React.Ref<HTMLDivElement>
onMouseUp?: (event: MouseEvent<HTMLDivElement>) => void
}
const StyledContainer = styled.div`
position: relative;
&:hover ${CopyButtonStyled} {
opacity: 1;
}
`
const WithCopyButton = React.forwardRef<HTMLDivElement, WithCopyButtonProps>(
({ children, textToCopy, style, onMouseUp, ...props }, ref) => {
const [copied, setCopied] = useState(false)
const handleCopy = () => {
if (!textToCopy) return
navigator.clipboard.writeText(textToCopy).then(() => {
setCopied(true)
setTimeout(() => {
setCopied(false)
}, 1500)
})
}
return (
<StyledContainer ref={ref} onMouseUp={onMouseUp} style={style} {...props}>
{children}
{textToCopy && (
<CopyButtonStyled appearance="icon" onClick={handleCopy} aria-label={copied ? "Copied" : "Copy"}>
<span className={`codicon codicon-${copied ? "check" : "copy"}`}></span>
</CopyButtonStyled>
)}
</StyledContainer>
)
},
)
const ChatRowContainer = styled.div`
padding: 10px 6px 10px 15px;
position: relative;
@@ -1086,7 +1033,11 @@ export const ChatRowContent = ({
)
case "text":
return (
<WithCopyButton ref={contentRef} onMouseUp={handleMouseUp} textToCopy={message.text}>
<WithCopyButton
ref={contentRef}
onMouseUp={handleMouseUp}
textToCopy={message.text}
position="bottom-right">
<Markdown markdown={message.text} />
{quoteButtonState.visible && (
<QuoteButton
@@ -1323,6 +1274,7 @@ export const ChatRowContent = ({
ref={contentRef}
onMouseUp={handleMouseUp}
textToCopy={text}
position="bottom-right"
style={{
color: "var(--vscode-charts-green)",
paddingTop: 10,
@@ -1487,6 +1439,7 @@ export const ChatRowContent = ({
ref={contentRef}
onMouseUp={handleMouseUp}
textToCopy={text}
position="bottom-right"
style={{
color: "var(--vscode-charts-green)",
paddingTop: 10,
@@ -1557,6 +1510,7 @@ export const ChatRowContent = ({
ref={contentRef}
onMouseUp={handleMouseUp}
textToCopy={question}
position="bottom-right"
style={{ paddingTop: 10 }}>
<Markdown markdown={question} />
<OptionsButtons
@@ -1640,7 +1594,7 @@ export const ChatRowContent = ({
response = message.text
}
return (
<WithCopyButton ref={contentRef} onMouseUp={handleMouseUp} textToCopy={response}>
<WithCopyButton ref={contentRef} onMouseUp={handleMouseUp} textToCopy={response} position="bottom-right">
<Markdown markdown={response} />
<OptionsButtons
options={options}
@@ -0,0 +1,138 @@
import React, { useState, useRef, forwardRef } from "react"
import { VSCodeButton } from "@vscode/webview-ui-toolkit/react"
import styled from "styled-components"
// ======== Interfaces ========
interface CopyButtonProps {
textToCopy?: string
onCopy?: () => string | void | null
className?: string
ariaLabel?: string
}
interface WithCopyButtonProps {
children: React.ReactNode
textToCopy?: string
onCopy?: () => string | void | null
position?: "top-right" | "bottom-right"
style?: React.CSSProperties
className?: string
onMouseUp?: (event: React.MouseEvent<HTMLDivElement>) => void
ariaLabel?: string
}
// ======== Styled Components ========
const StyledButton = styled(VSCodeButton)`
z-index: 1;
`
// Unified container component
const ContentContainer = styled.div`
position: relative;
`
// Unified button container with flexible positioning
const ButtonContainer = styled.div<{ $position?: "top-right" | "bottom-right" }>`
position: absolute;
${(props) => {
switch (props.$position) {
case "bottom-right":
return "bottom: 2px; right: 2px;"
case "top-right":
default:
return "top: 5px; right: 5px;"
}
}}
z-index: 1;
opacity: 0;
${ContentContainer}:hover & {
opacity: 1;
}
`
// ======== Component Implementations ========
/**
* Base copy button component with clipboard functionality
*/
export const CopyButton: React.FC<CopyButtonProps> = ({ textToCopy, onCopy, className = "", ariaLabel }) => {
const [copied, setCopied] = useState(false)
const handleCopy = () => {
if (!textToCopy && !onCopy) return
let textToCopyFinal = textToCopy
if (onCopy) {
const result = onCopy()
if (typeof result === "string") {
textToCopyFinal = result
}
}
if (textToCopyFinal) {
navigator.clipboard
.writeText(textToCopyFinal)
.then(() => {
setCopied(true)
setTimeout(() => setCopied(false), 1500)
})
.catch((err) => console.error("Copy failed", err))
}
}
return (
<StyledButton
appearance="icon"
onClick={handleCopy}
className={className}
aria-label={copied ? "Copied" : ariaLabel || "Copy"}>
<span className={`codicon codicon-${copied ? "check" : "copy"}`}></span>
</StyledButton>
)
}
/**
* Container component that wraps content with a copy button
*/
export const WithCopyButton = forwardRef<HTMLDivElement, WithCopyButtonProps>(
(
{
children,
textToCopy,
onCopy,
position = "top-right",
style,
className,
onMouseUp,
ariaLabel, // Destructure ariaLabel
...props
},
ref,
) => {
return (
<ContentContainer ref={ref} onMouseUp={onMouseUp} style={style} className={className} {...props}>
{children}
{(textToCopy || onCopy) && (
<ButtonContainer $position={position}>
<CopyButton
textToCopy={textToCopy}
onCopy={onCopy}
ariaLabel={ariaLabel} // Pass through the ariaLabel prop directly
/>
</ButtonContainer>
)}
</ContentContainer>
)
},
)
// Default export for convenience if needed, though named exports are preferred for clarity
const CopyButtonComponents = {
CopyButton,
WithCopyButton,
}
export default CopyButtonComponents
@@ -1,17 +1,18 @@
import { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock"
import MermaidBlock from "@/components/common/MermaidBlock"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { StateServiceClient } from "@/services/grpc-client"
import { PlanActMode, TogglePlanActModeRequest } from "@shared/proto/state"
import type { ComponentProps } from "react"
import React, { memo, useEffect, useRef, useState } from "react"
import type { ComponentProps } from "react"
import { useRemark } from "react-remark"
import rehypeHighlight, { Options } from "rehype-highlight"
import rehypeKatex from "rehype-katex"
import remarkMath from "remark-math"
import styled from "styled-components"
import type { Node } from "unist"
import { visit } from "unist-util-visit"
import type { Node } from "unist"
import { useExtensionState } from "@/context/ExtensionStateContext"
import CodeBlock, { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock"
import MermaidBlock from "@/components/common/MermaidBlock"
import { WithCopyButton } from "./CopyButton"
import { StateServiceClient } from "@/services/grpc-client"
import { PlanActMode, TogglePlanActModeRequest } from "@shared/proto/state"
// Styled component for Act Mode text with more specific styling
const ActModeHighlight: React.FC = () => (
@@ -178,24 +179,6 @@ const remarkPreventBoldFilenames = () => {
}
}
import { VSCodeButton } from "@vscode/webview-ui-toolkit/react"
const CopyButton = styled(VSCodeButton)`
position: absolute;
top: 5px;
right: 5px;
z-index: 1;
opacity: 0;
`
const CodeBlockContainer = styled.div`
position: relative;
&:hover ${CopyButton} {
opacity: 1;
}
`
const StyledMarkdown = styled.div`
pre {
background-color: ${CODE_BLOCK_BG_COLOR};
@@ -337,7 +320,6 @@ const PreWithCopyButton = ({
...preProps
}: { theme: Record<string, string> } & React.HTMLAttributes<HTMLPreElement>) => {
const preRef = useRef<HTMLPreElement>(null)
const [copied, setCopied] = useState(false)
const handleCopy = () => {
if (preRef.current) {
@@ -345,22 +327,19 @@ const PreWithCopyButton = ({
const textToCopy = codeElement ? codeElement.textContent : preRef.current.textContent
if (!textToCopy) return
navigator.clipboard.writeText(textToCopy).then(() => {
setCopied(true)
setTimeout(() => setCopied(false), 1500)
})
return textToCopy
}
return null
}
const styledPreProps = theme ? { ...preProps, theme } : preProps
return (
<CodeBlockContainer>
<CopyButton appearance="icon" onClick={handleCopy} aria-label={copied ? "Copied" : "Copy"}>
<span className={`codicon codicon-${copied ? "check" : "copy"}`}></span>
</CopyButton>
<StyledPre {...preProps} theme={theme} ref={preRef}>
<WithCopyButton onCopy={handleCopy} position="top-right" ariaLabel="Copy code">
<StyledPre {...styledPreProps} ref={preRef}>
{children}
</StyledPre>
</CodeBlockContainer>
</WithCopyButton>
)
}