33 lines
1.8 KiB
TypeScript
33 lines
1.8 KiB
TypeScript
import type { ReactElement } from 'react'
|
|
import type { MarkdownKind } from './markdown'
|
|
import type { PreviewText } from './types'
|
|
import { createContext, memo, useContext, useMemo } from 'react'
|
|
import { cn } from '@/lib/utils'
|
|
import { renderMarkdown } from './markdown'
|
|
import { SegmentText } from './SegmentText'
|
|
|
|
/** 卡片里的 Markdown 说明按哪种渲染:页面上是注释;定义卡片浮窗里是 peek(别的文件的注释,不认不带路径的引用)。 */
|
|
export const MarkdownKindContext = createContext<Exclude<MarkdownKind, 'answer'>>('comment')
|
|
|
|
/**
|
|
* 预览里的一段文字:着色的词按源码排版;Markdown 说明渲染成段落、列表、代码块。
|
|
* `find` 是卡片上这段字的记号(见 [textKey](vscode/webview-ui/src/codeReader/viewState.ts#textKey)),查找栏按它找到这段字画高亮。
|
|
*/
|
|
export const TextPreview = memo(({ text, className, find }: { text: PreviewText, className?: string, find?: string }): ReactElement => {
|
|
const kind = useContext(MarkdownKindContext)
|
|
if ('markdown' in text)
|
|
return <MarkdownPreview html={renderMarkdown(text.markdown, kind)} className={className} find={find} />
|
|
return (
|
|
<p className={cn('cr-code', className)} data-find={find}>
|
|
<SegmentText segments={text} />
|
|
</p>
|
|
)
|
|
})
|
|
TextPreview.displayName = 'TextPreview'
|
|
|
|
export function MarkdownPreview({ html, className, find, streaming }: { html: string, className?: string, find?: string, streaming?: boolean }): ReactElement {
|
|
// 同一段 HTML 用同一个对象:React 见到新对象就整段重设 innerHTML,里面的链接都换成新元素,悬停着的那个就脱离了页面
|
|
const content = useMemo(() => ({ __html: html }), [html])
|
|
return <div className={cn('cr-markdown', className)} data-find={find} data-streaming={streaming ? '' : undefined} dangerouslySetInnerHTML={content} />
|
|
}
|