-
Notifications
You must be signed in to change notification settings - Fork 254
Expand file tree
/
Copy pathcodeBlock.tsx
More file actions
67 lines (60 loc) · 2.34 KB
/
codeBlock.tsx
File metadata and controls
67 lines (60 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
'use client';
import { LightweightCodeHighlighter } from '@/app/[domain]/components/lightweightCodeHighlighter';
import { cn } from '@/lib/utils';
import { DoubleArrowDownIcon, DoubleArrowUpIcon } from '@radix-ui/react-icons';
import { useMemo, useState } from 'react';
interface CodeBlockComponentProps {
code: string;
language?: string;
}
const MAX_LINES_TO_DISPLAY = 14;
export const CodeBlock = ({
code,
language = "text",
}: CodeBlockComponentProps) => {
const [isExpanded, setIsExpanded] = useState(false);
const lineCount = useMemo(() => {
return code.split('\n').length;
}, [code]);
const isExpandButtonVisible = useMemo(() => {
return lineCount > MAX_LINES_TO_DISPLAY;
}, [lineCount]);
return (
<div className="flex flex-col rounded-md border overflow-hidden not-prose my-4">
<div
className={cn(
"overflow-hidden transition-all duration-300 ease-in-out",
{
"max-h-[350px]": !isExpanded && isExpandButtonVisible, // Roughly 14 lines
"max-h-none": isExpanded || !isExpandButtonVisible
}
)}
>
<LightweightCodeHighlighter
language={language}
lineNumbers={true}
renderWhitespace={true}
isCopyButtonVisible={true}
>
{code}
</LightweightCodeHighlighter>
</div>
{isExpandButtonVisible && (
<div
tabIndex={0}
className="flex flex-row items-center justify-center w-full bg-accent py-1 cursor-pointer text-muted-foreground hover:text-foreground"
onClick={() => setIsExpanded(!isExpanded)}
onKeyDown={(e) => {
if (e.key !== "Enter") {
return;
}
setIsExpanded(!isExpanded);
}}
>
{isExpanded ? <DoubleArrowUpIcon className="w-3 h-3" /> : <DoubleArrowDownIcon className="w-3 h-3" />}
<span className="text-sm ml-1">{isExpanded ? 'Show less' : 'Show more'}</span>
</div>
)}
</div>
);
};