fix: optimize code string parser

Signed-off-by: Innei <i@innei.in>
This commit is contained in:
Innei
2024-08-12 21:25:54 +08:00
parent bca627696e
commit b3d32d09fd
2 changed files with 49 additions and 5 deletions
+32
View File
@@ -198,6 +198,7 @@ const MediaImpl: FC<MediaProps> = ({
type,
])
if (hidden) return <FallbackMedia {...props} />
return (
<div className={cn("overflow-hidden rounded", className)} style={style}>
{InnerContent}
@@ -208,3 +209,34 @@ const MediaImpl: FC<MediaProps> = ({
export const Media: FC<MediaProps> = memo((props) => (
<MediaImpl {...props} key={props.src} />
))
const FallbackMedia: FC<MediaProps> = ({
type,
mediaContainerClassName,
...props
}) => (
<div
className={cn(
!(props.width || props.height) && "size-full",
"center relative h-24 rounded bg-zinc-100 object-cover dark:bg-neutral-900",
"not-prose flex max-h-full flex-col space-y-1",
mediaContainerClassName,
)}
style={{
height: props.height ? `${props.height}px` : "",
width: props.width ? `${props.width}px` : "100%",
...props.style,
}}
>
<p>Media loaded failed</p>
<p className="flex items-center gap-1">
Go to
{" "}
<a href={props.src} target="_blank" rel="noreferrer" className="follow-link--underline">
{props.src}
</a>
<i className="i-mgc-external-link-cute-re" />
</p>
</div>
)
+17 -5
View File
@@ -44,6 +44,7 @@ export const parseHtml = async (
"video": ["src", "poster"],
},
})
.use(rehypeInferDescriptionMeta)
.use(rehypeStringify)
@@ -165,16 +166,27 @@ function extractCodeFromHtml(htmlString: string) {
const tempDiv = document.createElement("div")
tempDiv.innerHTML = htmlString
// 1. line break via <div />
const divElements = tempDiv.querySelectorAll("div")
let code = ""
divElements.forEach((div) => {
code += `${div.textContent}\n`
})
if (divElements.length > 0) {
divElements.forEach((div) => {
code += `${div.textContent}\n`
})
return code
}
if (divElements.length === 0) {
return tempDiv.textContent
// 2. line wrapper like <span><span>...</span></span>
const spanElements = tempDiv.querySelectorAll("span > span")
if (spanElements.length > 0) {
for (const node of tempDiv.children) {
code += `${node.textContent}\n`
}
return code
}
return code