Skip to content
Merged
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
79 changes: 61 additions & 18 deletions apps/code/src/renderer/components/CodeBlock.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { Check, Copy } from "@phosphor-icons/react";
import { IconButton } from "@radix-ui/themes";
import type { ReactNode } from "react";
import { useCallback, useState } from "react";

type CodeBlockSize = "1" | "1.5" | "2" | "3";

Expand Down Expand Up @@ -29,27 +32,67 @@ const sizeStyles: Record<
},
};

function extractText(children: ReactNode): string {
if (typeof children === "string") return children;
if (Array.isArray(children)) return children.map(extractText).join("");
if (children && typeof children === "object" && "props" in children) {
return extractText(
(children as { props: { children?: ReactNode } }).props.children,
);
}
return "";
}

export function CodeBlock({ children, size = "1" }: CodeBlockProps) {
const styles = sizeStyles[size];
const [copied, setCopied] = useState(false);

const handleCopy = useCallback(() => {
const text = extractText(children);
navigator.clipboard.writeText(text);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}, [children]);

return (
<pre
style={{
margin: 0,
marginBottom: "var(--space-3)",
padding: "var(--space-3)",
backgroundColor: "var(--gray-2)",
borderRadius: "var(--radius-2)",
border: "1px solid var(--gray-4)",
fontFamily: "var(--code-font-family)",
fontSize: styles.fontSize,
lineHeight: styles.lineHeight,
color: "var(--gray-12)",
overflowX: "auto",
whiteSpace: "pre",
}}
>
{children}
</pre>
<div className="group" style={{ position: "relative" }}>
<pre
style={{
margin: 0,
marginBottom: "var(--space-3)",
padding: "var(--space-3)",
paddingRight: "var(--space-7)",
backgroundColor: "var(--gray-2)",
borderRadius: "var(--radius-2)",
border: "1px solid var(--gray-4)",
fontFamily: "var(--code-font-family)",
fontSize: styles.fontSize,
lineHeight: styles.lineHeight,
color: "var(--gray-12)",
overflowX: "auto",
whiteSpace: "pre",
}}
>
{children}
</pre>
<IconButton
size="1"
variant="ghost"
color="gray"
onClick={handleCopy}
style={{
position: "absolute",
top: "var(--space-1)",
right: "var(--space-1)",
opacity: 0,
transition: "opacity 0.15s",
cursor: "pointer",
}}
className="group-hover:!opacity-100 [&]:hover:!opacity-100"
aria-label="Copy code"
>
{copied ? <Check size={14} /> : <Copy size={14} />}
</IconButton>
</div>
);
}
Loading