Skip to content

Commit d8110c0

Browse files
committed
feat: Add preview functionality to CodeBlock component with debounced value updates
1 parent 8eb9c1a commit d8110c0

File tree

1 file changed

+23
-4
lines changed

1 file changed

+23
-4
lines changed

src/components/Common/CodeBlock.tsx

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import {
77
EyeIcon,
88
CodeIcon
99
} from "lucide-react"
10-
import { FC, useState, useRef, useEffect } from "react"
10+
import { FC, useState, useRef, useEffect, useCallback } from "react"
1111
import { useTranslation } from "react-i18next"
1212
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter"
1313
import { coldarkDark } from "react-syntax-highlighter/dist/cjs/styles/prism"
@@ -20,6 +20,9 @@ interface Props {
2020

2121
export const CodeBlock: FC<Props> = ({ language, value }) => {
2222
const [isBtnPressed, setIsBtnPressed] = useState(false)
23+
const [previewValue, setPreviewValue] = useState(value)
24+
const debounceTimeoutRef = useRef<NodeJS.Timeout | null>(null)
25+
2326
const computeKey = () => {
2427
const base = `${language}::${value?.slice(0, 200)}`
2528
let hash = 0
@@ -61,8 +64,8 @@ export const CodeBlock: FC<Props> = ({ language, value }) => {
6164
(language || "").toLowerCase()
6265
)
6366

64-
const buildPreviewDoc = () => {
65-
const code = value || ""
67+
const buildPreviewDoc = useCallback(() => {
68+
const code = previewValue || ""
6669
if ((language || "").toLowerCase() === "svg") {
6770
const hasSvgTag = /<svg[\s>]/i.test(code)
6871
const svgMarkup = hasSvgTag
@@ -71,7 +74,7 @@ export const CodeBlock: FC<Props> = ({ language, value }) => {
7174
return `<!doctype html><html><head><meta charset='utf-8'/><style>html,body{margin:0;padding:0;display:flex;align-items:center;justify-content:center;background:#fff;height:100%;}</style></head><body>${svgMarkup}</body></html>`
7275
}
7376
return `<!doctype html><html><head><meta charset='utf-8'/></head><body>${code}</body></html>`
74-
}
77+
}, [previewValue, language])
7578

7679
const handleDownload = () => {
7780
const blob = new Blob([value], { type: "text/plain" })
@@ -89,6 +92,22 @@ export const CodeBlock: FC<Props> = ({ language, value }) => {
8992
globalStateMap.set(keyRef.current, showPreview)
9093
}, [showPreview])
9194

95+
useEffect(() => {
96+
if (debounceTimeoutRef.current) {
97+
clearTimeout(debounceTimeoutRef.current)
98+
}
99+
100+
debounceTimeoutRef.current = setTimeout(() => {
101+
setPreviewValue(value)
102+
}, 300)
103+
104+
return () => {
105+
if (debounceTimeoutRef.current) {
106+
clearTimeout(debounceTimeoutRef.current)
107+
}
108+
}
109+
}, [value])
110+
92111
useEffect(() => {
93112
const newKey = computeKey()
94113
if (newKey !== keyRef.current) {

0 commit comments

Comments
 (0)