feat(ui): add Markdown rendering components
Add CodeBlock, Markdown, StreamingMarkdown components with Shiki syntax highlighting, GFM support, and linkify utility. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
parent
2a96fc9227
commit
9b87cd789e
9 changed files with 2130 additions and 53 deletions
|
|
@ -1,7 +1,56 @@
|
|||
"use client"
|
||||
|
||||
import { ComponentExample } from "@multica/ui/components/component-example";
|
||||
import { Markdown } from "@multica/ui/components/markdown"
|
||||
|
||||
const MOCK_MD = `# Markdown 渲染器示例
|
||||
|
||||
这是一个 **Markdown** 渲染组件的演示页面,支持多种常见语法。
|
||||
|
||||
## 代码高亮
|
||||
|
||||
\`\`\`typescript
|
||||
interface User {
|
||||
id: string
|
||||
name: string
|
||||
email: string
|
||||
}
|
||||
|
||||
async function fetchUser(id: string): Promise<User> {
|
||||
const res = await fetch(\`/api/users/\${id}\`)
|
||||
return res.json()
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
## 列表
|
||||
|
||||
- React 组件化架构
|
||||
- Shiki 语法高亮
|
||||
- GFM 表格和任务列表支持
|
||||
|
||||
## 表格
|
||||
|
||||
| 功能 | 状态 | 说明 |
|
||||
|------|------|------|
|
||||
| 代码高亮 | ✅ | 基于 Shiki |
|
||||
| GFM 表格 | ✅ | remark-gfm |
|
||||
| 流式渲染 | ✅ | StreamingMarkdown |
|
||||
|
||||
## 引用
|
||||
|
||||
> 好的设计是尽可能少的设计。
|
||||
> — Dieter Rams
|
||||
|
||||
行内代码示例:使用 \`cn()\` 工具函数合并 class。
|
||||
|
||||
这是一个 [链接示例](https://github.com)。
|
||||
`
|
||||
|
||||
export default function Page() {
|
||||
return <ComponentExample />;
|
||||
}
|
||||
return (
|
||||
<div className="min-h-screen bg-background text-foreground flex items-center justify-center p-8">
|
||||
<div className="max-w-2xl w-full">
|
||||
<Markdown mode="full">{MOCK_MD}</Markdown>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,6 +9,8 @@
|
|||
"./lib/*": "./src/lib/*.ts",
|
||||
"./components/*": "./src/components/*.tsx",
|
||||
"./components/ui/*": "./src/components/ui/*.tsx",
|
||||
"./components/markdown": "./src/components/markdown/index.ts",
|
||||
"./components/markdown/*": "./src/components/markdown/*.tsx",
|
||||
"./hooks/*": "./src/hooks/*.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
|
|
@ -23,12 +25,18 @@
|
|||
"shadcn": "^3.7.0",
|
||||
"tailwind-merge": "^3.4.0",
|
||||
"tailwindcss": "^4",
|
||||
"tw-animate-css": "^1.4.0"
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"rehype-raw": "^7.0.0",
|
||||
"shiki": "^3.21.0",
|
||||
"linkify-it": "^5.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"@types/react": "catalog:",
|
||||
"@types/react-dom": "catalog:",
|
||||
"@types/linkify-it": "^5.0.0",
|
||||
"typescript": "catalog:"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
250
packages/ui/src/components/markdown/CodeBlock.tsx
Normal file
250
packages/ui/src/components/markdown/CodeBlock.tsx
Normal file
|
|
@ -0,0 +1,250 @@
|
|||
import * as React from 'react'
|
||||
import { codeToHtml, bundledLanguages, type BundledLanguage } from 'shiki'
|
||||
import { cn } from '@multica/ui/lib/utils'
|
||||
|
||||
export interface CodeBlockProps {
|
||||
code: string
|
||||
language?: string
|
||||
className?: string
|
||||
/**
|
||||
* Render mode affects code block styling:
|
||||
* - 'terminal': Minimal, keeps control chars visible
|
||||
* - 'minimal': Clean code, basic styling
|
||||
* - 'full': Rich styling with background, copy button, etc.
|
||||
*/
|
||||
mode?: 'terminal' | 'minimal' | 'full'
|
||||
}
|
||||
|
||||
// Map common aliases to Shiki language names
|
||||
const LANGUAGE_ALIASES: Record<string, BundledLanguage> = {
|
||||
js: 'javascript',
|
||||
ts: 'typescript',
|
||||
py: 'python',
|
||||
sh: 'bash',
|
||||
zsh: 'bash',
|
||||
yml: 'yaml',
|
||||
rb: 'ruby',
|
||||
rs: 'rust',
|
||||
kt: 'kotlin',
|
||||
'objective-c': 'objc',
|
||||
objc: 'objc'
|
||||
}
|
||||
|
||||
// Simple LRU cache for highlighted code
|
||||
const highlightCache = new Map<string, string>()
|
||||
const CACHE_MAX_SIZE = 200
|
||||
|
||||
function getCacheKey(code: string, lang: string): string {
|
||||
return `${lang}:${code}`
|
||||
}
|
||||
|
||||
function isValidLanguage(lang: string): lang is BundledLanguage {
|
||||
const normalized = LANGUAGE_ALIASES[lang] || lang
|
||||
return normalized in bundledLanguages
|
||||
}
|
||||
|
||||
/**
|
||||
* CodeBlock - Syntax highlighted code block using Shiki
|
||||
*
|
||||
* Uses Shiki dual themes with CSS variables for light/dark switching.
|
||||
* No JS-based dark mode detection needed — theme switching is handled
|
||||
* entirely via CSS (see globals.css for .shiki/.dark .shiki rules).
|
||||
*
|
||||
* @see https://shiki.style/guide/dual-themes
|
||||
*/
|
||||
export function CodeBlock({
|
||||
code,
|
||||
language = 'text',
|
||||
className,
|
||||
mode = 'full'
|
||||
}: CodeBlockProps): React.JSX.Element {
|
||||
const [highlighted, setHighlighted] = React.useState<string | null>(null)
|
||||
const [isLoading, setIsLoading] = React.useState(true)
|
||||
const [copied, setCopied] = React.useState(false)
|
||||
|
||||
// Resolve language alias - keep as string to allow 'text' fallback
|
||||
const langLower = language.toLowerCase()
|
||||
const resolvedLang: string = LANGUAGE_ALIASES[langLower] || langLower
|
||||
|
||||
React.useEffect(() => {
|
||||
let cancelled = false
|
||||
|
||||
async function highlight(): Promise<void> {
|
||||
const cacheKey = getCacheKey(code, resolvedLang)
|
||||
|
||||
const cached = highlightCache.get(cacheKey)
|
||||
if (cached) {
|
||||
if (!cancelled) {
|
||||
setHighlighted(cached)
|
||||
setIsLoading(false)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
// Use valid language or fallback to plaintext
|
||||
const lang = isValidLanguage(resolvedLang) ? resolvedLang : 'text'
|
||||
|
||||
// Dual themes: Shiki outputs CSS variables for both themes in one pass.
|
||||
// CSS handles switching via .dark selector (see globals.css).
|
||||
const html = await codeToHtml(code, {
|
||||
lang,
|
||||
themes: {
|
||||
light: 'github-light',
|
||||
dark: 'github-dark',
|
||||
},
|
||||
defaultColor: false,
|
||||
})
|
||||
|
||||
// Cache the result
|
||||
if (highlightCache.size >= CACHE_MAX_SIZE) {
|
||||
const firstKey = highlightCache.keys().next().value
|
||||
if (firstKey) highlightCache.delete(firstKey)
|
||||
}
|
||||
highlightCache.set(cacheKey, html)
|
||||
|
||||
if (!cancelled) {
|
||||
setHighlighted(html)
|
||||
setIsLoading(false)
|
||||
}
|
||||
} catch (error) {
|
||||
// Fallback to plain text on error
|
||||
console.warn(`Shiki highlighting failed for language "${resolvedLang}":`, error)
|
||||
if (!cancelled) {
|
||||
setHighlighted(null)
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
highlight()
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [code, resolvedLang])
|
||||
|
||||
const handleCopy = React.useCallback(async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(code)
|
||||
setCopied(true)
|
||||
setTimeout(() => setCopied(false), 2000)
|
||||
} catch (err) {
|
||||
console.error('Failed to copy code:', err)
|
||||
}
|
||||
}, [code])
|
||||
|
||||
// Terminal mode: raw monospace with minimal styling
|
||||
if (mode === 'terminal') {
|
||||
return (
|
||||
<pre className={cn('font-mono text-sm whitespace-pre-wrap', className)}>
|
||||
<code>{code}</code>
|
||||
</pre>
|
||||
)
|
||||
}
|
||||
|
||||
// Minimal mode: just syntax highlighting, no chrome
|
||||
if (mode === 'minimal') {
|
||||
if (isLoading || !highlighted) {
|
||||
return (
|
||||
<pre className={cn('font-mono text-sm whitespace-pre-wrap', className)}>
|
||||
<code>{code}</code>
|
||||
</pre>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'font-mono text-sm [&_pre]:!bg-transparent [&_pre]:!p-0 [&_pre]:whitespace-pre-wrap [&_pre]:break-all [&_code]:!bg-transparent',
|
||||
className
|
||||
)}
|
||||
dangerouslySetInnerHTML={{ __html: highlighted }}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Full mode: rich styling with header and copy button
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'relative group rounded-lg overflow-hidden border bg-muted/30 mb-4 last:mb-0',
|
||||
className
|
||||
)}
|
||||
>
|
||||
{/* Language label + copy button */}
|
||||
<div className="flex items-center justify-between px-3 py-1.5 bg-muted/50 border-b text-xs">
|
||||
<span className="text-muted-foreground font-medium uppercase tracking-wide">
|
||||
{resolvedLang !== 'text' ? resolvedLang : 'plain text'}
|
||||
</span>
|
||||
<button
|
||||
onClick={handleCopy}
|
||||
className="opacity-0 group-hover:opacity-100 transition-opacity text-muted-foreground hover:text-foreground"
|
||||
aria-label="Copy code"
|
||||
>
|
||||
{copied ? (
|
||||
<svg
|
||||
className="w-4 h-4 text-green-500"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M5 13l4 4L19 7"
|
||||
/>
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"
|
||||
/>
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Code content */}
|
||||
<div className="p-3 overflow-x-auto">
|
||||
{isLoading || !highlighted ? (
|
||||
<pre className="font-mono text-sm whitespace-pre-wrap break-all">
|
||||
<code>{code}</code>
|
||||
</pre>
|
||||
) : (
|
||||
<div
|
||||
className="font-mono text-sm [&_pre]:!bg-transparent [&_pre]:!m-0 [&_pre]:!p-0 [&_pre]:whitespace-pre-wrap [&_pre]:break-all [&_code]:!bg-transparent"
|
||||
dangerouslySetInnerHTML={{ __html: highlighted }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* InlineCode - Styled inline code span
|
||||
* Features: subtle background (3%), subtle border (5%), 75% opacity text
|
||||
*/
|
||||
export function InlineCode({
|
||||
children,
|
||||
className
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
className?: string
|
||||
}): React.JSX.Element {
|
||||
return (
|
||||
<code
|
||||
className={cn(
|
||||
'px-1.5 py-0.5 rounded bg-foreground/[0.03] border border-foreground/[0.05] font-mono text-sm text-foreground/75',
|
||||
className
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</code>
|
||||
)
|
||||
}
|
||||
301
packages/ui/src/components/markdown/Markdown.tsx
Normal file
301
packages/ui/src/components/markdown/Markdown.tsx
Normal file
|
|
@ -0,0 +1,301 @@
|
|||
import * as React from 'react'
|
||||
import ReactMarkdown, { type Components } from 'react-markdown'
|
||||
import rehypeRaw from 'rehype-raw'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
import { cn } from '@multica/ui/lib/utils'
|
||||
import { CodeBlock, InlineCode } from './CodeBlock'
|
||||
import { preprocessLinks } from './linkify'
|
||||
|
||||
/**
|
||||
* Render modes for markdown content:
|
||||
*
|
||||
* - 'terminal': Raw output with minimal formatting, control chars visible
|
||||
* Best for: Debug output, raw logs, when you want to see exactly what's there
|
||||
*
|
||||
* - 'minimal': Clean rendering with syntax highlighting but no extra chrome
|
||||
* Best for: Chat messages, inline content, when you want readability without clutter
|
||||
*
|
||||
* - 'full': Rich rendering with beautiful tables, styled code blocks, proper typography
|
||||
* Best for: Documentation, long-form content, when presentation matters
|
||||
*/
|
||||
export type RenderMode = 'terminal' | 'minimal' | 'full'
|
||||
|
||||
export interface MarkdownProps {
|
||||
children: string
|
||||
/**
|
||||
* Render mode controlling formatting level
|
||||
* @default 'minimal'
|
||||
*/
|
||||
mode?: RenderMode
|
||||
className?: string
|
||||
/**
|
||||
* Message ID for memoization (optional)
|
||||
* When provided, memoizes parsed blocks to avoid re-parsing during streaming
|
||||
*/
|
||||
id?: string
|
||||
/**
|
||||
* Callback when a URL is clicked
|
||||
*/
|
||||
onUrlClick?: (url: string) => void
|
||||
/**
|
||||
* Callback when a file path is clicked
|
||||
*/
|
||||
onFileClick?: (path: string) => void
|
||||
}
|
||||
|
||||
// File path detection regex - matches paths starting with /, ~/, or ./
|
||||
const FILE_PATH_REGEX =
|
||||
/^(?:\/|~\/|\.\/)[\w\-./@]+\.(?:ts|tsx|js|jsx|mjs|cjs|md|json|yaml|yml|py|go|rs|css|scss|less|html|htm|txt|log|sh|bash|zsh|swift|kt|java|c|cpp|h|hpp|rb|php|xml|toml|ini|cfg|conf|env|sql|graphql|vue|svelte|astro|prisma)$/i
|
||||
|
||||
/**
|
||||
* Create custom components based on render mode
|
||||
*/
|
||||
function createComponents(
|
||||
mode: RenderMode,
|
||||
onUrlClick?: (url: string) => void,
|
||||
onFileClick?: (path: string) => void
|
||||
): Partial<Components> {
|
||||
const baseComponents: Partial<Components> = {
|
||||
// Links: Make clickable with callbacks
|
||||
a: ({ href, children }) => {
|
||||
const handleClick = (e: React.MouseEvent): void => {
|
||||
e.preventDefault()
|
||||
if (href) {
|
||||
// Check if it's a file path
|
||||
if (FILE_PATH_REGEX.test(href) && onFileClick) {
|
||||
onFileClick(href)
|
||||
} else if (onUrlClick) {
|
||||
onUrlClick(href)
|
||||
} else {
|
||||
// Default: open in new window
|
||||
window.open(href, '_blank', 'noopener,noreferrer')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<a
|
||||
href={href}
|
||||
onClick={handleClick}
|
||||
className="text-primary hover:underline cursor-pointer"
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Terminal mode: minimal formatting
|
||||
if (mode === 'terminal') {
|
||||
return {
|
||||
...baseComponents,
|
||||
// No special code handling - just monospace
|
||||
code: ({ children }) => <code className="font-mono">{children}</code>,
|
||||
pre: ({ children }) => <pre className="font-mono whitespace-pre-wrap my-2">{children}</pre>,
|
||||
// Minimal paragraph spacing
|
||||
p: ({ children }) => <p className="my-1">{children}</p>,
|
||||
// Simple lists
|
||||
ul: ({ children }) => <ul className="list-disc list-inside my-1">{children}</ul>,
|
||||
ol: ({ children }) => <ol className="list-decimal list-inside my-1">{children}</ol>,
|
||||
li: ({ children }) => <li className="my-0.5">{children}</li>,
|
||||
// Plain tables
|
||||
table: ({ children }) => <table className="my-2 font-mono text-sm">{children}</table>,
|
||||
th: ({ children }) => <th className="text-left pr-4">{children}</th>,
|
||||
td: ({ children }) => <td className="pr-4">{children}</td>
|
||||
}
|
||||
}
|
||||
|
||||
// Minimal mode: clean with syntax highlighting
|
||||
if (mode === 'minimal') {
|
||||
return {
|
||||
...baseComponents,
|
||||
// Inline code
|
||||
code: ({ className, children, ...props }) => {
|
||||
const match = /language-(\w+)/.exec(className || '')
|
||||
const isBlock =
|
||||
'node' in props && props.node?.position?.start.line !== props.node?.position?.end.line
|
||||
|
||||
// Block code - use CodeBlock with full mode
|
||||
if (match || isBlock) {
|
||||
const code = String(children).replace(/\n$/, '')
|
||||
return <CodeBlock code={code} language={match?.[1]} mode="full" className="my-1" />
|
||||
}
|
||||
|
||||
// Inline code
|
||||
return <InlineCode>{children}</InlineCode>
|
||||
},
|
||||
pre: ({ children }) => <>{children}</>,
|
||||
// Comfortable paragraph spacing
|
||||
p: ({ children }) => <p className="my-2 leading-relaxed">{children}</p>,
|
||||
// Styled lists
|
||||
ul: ({ children }) => (
|
||||
<ul className="my-2 space-y-1 ps-[16px] pe-2 list-disc marker:text-muted-foreground">
|
||||
{children}
|
||||
</ul>
|
||||
),
|
||||
ol: ({ children }) => <ol className="my-2 space-y-1 pl-6 list-decimal">{children}</ol>,
|
||||
li: ({ children }) => <li>{children}</li>,
|
||||
// Clean tables
|
||||
table: ({ children }) => (
|
||||
<div className="my-3 overflow-x-auto">
|
||||
<table className="min-w-full text-sm">{children}</table>
|
||||
</div>
|
||||
),
|
||||
thead: ({ children }) => <thead className="border-b">{children}</thead>,
|
||||
th: ({ children }) => (
|
||||
<th className="text-left py-2 px-3 font-semibold text-muted-foreground">{children}</th>
|
||||
),
|
||||
td: ({ children }) => <td className="py-2 px-3 border-b border-border/50">{children}</td>,
|
||||
// Headings - H1/H2 same size, differentiated by weight
|
||||
h1: ({ children }) => <h1 className="font-sans text-base font-bold mt-5 mb-3">{children}</h1>,
|
||||
h2: ({ children }) => (
|
||||
<h2 className="font-sans text-base font-semibold mt-4 mb-3">{children}</h2>
|
||||
),
|
||||
h3: ({ children }) => (
|
||||
<h3 className="font-sans text-sm font-semibold mt-4 mb-2">{children}</h3>
|
||||
),
|
||||
// Blockquotes
|
||||
blockquote: ({ children }) => (
|
||||
<blockquote className="border-l-2 border-muted-foreground/30 pl-3 my-2 text-muted-foreground italic">
|
||||
{children}
|
||||
</blockquote>
|
||||
),
|
||||
// Horizontal rules
|
||||
hr: () => <hr className="my-4 border-border" />,
|
||||
// Strong/emphasis
|
||||
strong: ({ children }) => <strong className="font-semibold">{children}</strong>,
|
||||
em: ({ children }) => <em className="italic">{children}</em>
|
||||
}
|
||||
}
|
||||
|
||||
// Full mode: rich styling
|
||||
return {
|
||||
...baseComponents,
|
||||
// Full code blocks with copy button
|
||||
code: ({ className, children, ...props }) => {
|
||||
const match = /language-(\w+)/.exec(className || '')
|
||||
const isBlock =
|
||||
'node' in props && props.node?.position?.start.line !== props.node?.position?.end.line
|
||||
|
||||
if (match || isBlock) {
|
||||
const code = String(children).replace(/\n$/, '')
|
||||
return <CodeBlock code={code} language={match?.[1]} mode="full" className="my-1" />
|
||||
}
|
||||
|
||||
return <InlineCode>{children}</InlineCode>
|
||||
},
|
||||
pre: ({ children }) => <>{children}</>,
|
||||
// Rich paragraph spacing
|
||||
p: ({ children }) => <p className="my-3 leading-relaxed">{children}</p>,
|
||||
// Styled lists
|
||||
ul: ({ children }) => (
|
||||
<ul className="my-3 space-y-1.5 ps-[16px] pe-2 list-disc marker:text-muted-foreground">
|
||||
{children}
|
||||
</ul>
|
||||
),
|
||||
ol: ({ children }) => <ol className="my-3 space-y-1.5 pl-6 list-decimal">{children}</ol>,
|
||||
li: ({ children }) => <li className="leading-relaxed">{children}</li>,
|
||||
// Beautiful tables
|
||||
table: ({ children }) => (
|
||||
<div className="my-4 overflow-x-auto rounded-md border">
|
||||
<table className="min-w-full divide-y divide-border">{children}</table>
|
||||
</div>
|
||||
),
|
||||
thead: ({ children }) => <thead className="bg-muted/50">{children}</thead>,
|
||||
tbody: ({ children }) => <tbody className="divide-y divide-border">{children}</tbody>,
|
||||
th: ({ children }) => <th className="text-left py-3 px-4 font-semibold text-sm">{children}</th>,
|
||||
td: ({ children }) => <td className="py-3 px-4 text-sm">{children}</td>,
|
||||
tr: ({ children }) => <tr className="hover:bg-muted/30 transition-colors">{children}</tr>,
|
||||
// Rich headings
|
||||
h1: ({ children }) => <h1 className="font-sans text-base font-bold mt-7 mb-4">{children}</h1>,
|
||||
h2: ({ children }) => (
|
||||
<h2 className="font-sans text-base font-semibold mt-6 mb-3">{children}</h2>
|
||||
),
|
||||
h3: ({ children }) => <h3 className="font-sans text-sm font-semibold mt-5 mb-3">{children}</h3>,
|
||||
h4: ({ children }) => <h4 className="text-sm font-semibold mt-3 mb-1">{children}</h4>,
|
||||
// Styled blockquotes
|
||||
blockquote: ({ children }) => (
|
||||
<blockquote className="border-l-4 border-foreground/30 bg-muted/30 pl-4 pr-3 py-2 my-3 rounded-r-md">
|
||||
{children}
|
||||
</blockquote>
|
||||
),
|
||||
// Task lists (GFM)
|
||||
input: ({ type, checked }) => {
|
||||
if (type === 'checkbox') {
|
||||
return (
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
readOnly
|
||||
className="mr-2 rounded border-muted-foreground"
|
||||
/>
|
||||
)
|
||||
}
|
||||
return <input type={type} />
|
||||
},
|
||||
// Horizontal rules
|
||||
hr: () => <hr className="my-6 border-border" />,
|
||||
// Strong/emphasis
|
||||
strong: ({ children }) => <strong className="font-semibold">{children}</strong>,
|
||||
em: ({ children }) => <em className="italic">{children}</em>,
|
||||
del: ({ children }) => <del className="line-through text-muted-foreground">{children}</del>
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Markdown - Customizable markdown renderer with multiple render modes
|
||||
*
|
||||
* Features:
|
||||
* - Three render modes: terminal, minimal, full
|
||||
* - Syntax highlighting via Shiki
|
||||
* - GFM support (tables, task lists, strikethrough)
|
||||
* - Clickable links and file paths
|
||||
* - Memoization for streaming performance
|
||||
*/
|
||||
export function Markdown({
|
||||
children,
|
||||
mode = 'minimal',
|
||||
className,
|
||||
onUrlClick,
|
||||
onFileClick
|
||||
}: MarkdownProps): React.JSX.Element {
|
||||
const components = React.useMemo(
|
||||
() => createComponents(mode, onUrlClick, onFileClick),
|
||||
[mode, onUrlClick, onFileClick]
|
||||
)
|
||||
|
||||
// Preprocess to convert raw URLs and file paths to markdown links
|
||||
const processedContent = React.useMemo(() => preprocessLinks(children), [children])
|
||||
|
||||
return (
|
||||
<div className={cn('markdown-content text-sm', className)}>
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
rehypePlugins={[rehypeRaw]}
|
||||
components={components}
|
||||
>
|
||||
{processedContent}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* MemoizedMarkdown - Optimized for streaming scenarios
|
||||
*
|
||||
* Splits content into blocks and memoizes each block separately,
|
||||
* so only new/changed blocks re-render during streaming.
|
||||
*/
|
||||
export const MemoizedMarkdown = React.memo(Markdown, (prevProps, nextProps) => {
|
||||
// If id is provided, use it for memoization
|
||||
if (prevProps.id && nextProps.id) {
|
||||
return (
|
||||
prevProps.id === nextProps.id &&
|
||||
prevProps.children === nextProps.children &&
|
||||
prevProps.mode === nextProps.mode
|
||||
)
|
||||
}
|
||||
// Otherwise compare content and mode
|
||||
return prevProps.children === nextProps.children && prevProps.mode === nextProps.mode
|
||||
})
|
||||
MemoizedMarkdown.displayName = 'MemoizedMarkdown'
|
||||
186
packages/ui/src/components/markdown/StreamingMarkdown.tsx
Normal file
186
packages/ui/src/components/markdown/StreamingMarkdown.tsx
Normal file
|
|
@ -0,0 +1,186 @@
|
|||
import * as React from 'react'
|
||||
import { Markdown, type RenderMode } from './Markdown'
|
||||
|
||||
export interface StreamingMarkdownProps {
|
||||
content: string
|
||||
isStreaming: boolean
|
||||
mode?: RenderMode
|
||||
onUrlClick?: (url: string) => void
|
||||
onFileClick?: (path: string) => void
|
||||
}
|
||||
|
||||
interface Block {
|
||||
content: string
|
||||
isCodeBlock: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple hash function for cache keys
|
||||
* Uses djb2 algorithm - fast and produces good distribution
|
||||
*/
|
||||
function simpleHash(str: string): string {
|
||||
let hash = 5381
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
hash = ((hash << 5) + hash) ^ str.charCodeAt(i)
|
||||
}
|
||||
return (hash >>> 0).toString(36)
|
||||
}
|
||||
|
||||
/**
|
||||
* Split content into blocks (paragraphs and code blocks)
|
||||
*
|
||||
* Block boundaries:
|
||||
* - Double newlines (paragraph separators)
|
||||
* - Code fences (```)
|
||||
*
|
||||
* This is intentionally simple - just string scanning, no regex per line.
|
||||
*/
|
||||
function splitIntoBlocks(content: string): Block[] {
|
||||
const blocks: Block[] = []
|
||||
const lines = content.split('\n')
|
||||
let currentBlock = ''
|
||||
let inCodeBlock = false
|
||||
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i]
|
||||
|
||||
// Check for code fence (``` at start of line, optionally followed by language)
|
||||
if (line.startsWith('```')) {
|
||||
if (!inCodeBlock) {
|
||||
// Starting a code block - flush current paragraph first
|
||||
if (currentBlock.trim()) {
|
||||
blocks.push({ content: currentBlock.trim(), isCodeBlock: false })
|
||||
currentBlock = ''
|
||||
}
|
||||
inCodeBlock = true
|
||||
currentBlock = line + '\n'
|
||||
} else {
|
||||
// Ending a code block
|
||||
currentBlock += line
|
||||
blocks.push({ content: currentBlock, isCodeBlock: true })
|
||||
currentBlock = ''
|
||||
inCodeBlock = false
|
||||
}
|
||||
} else if (inCodeBlock) {
|
||||
// Inside code block - append line
|
||||
currentBlock += line + '\n'
|
||||
} else if (line === '') {
|
||||
// Empty line outside code block = paragraph boundary
|
||||
if (currentBlock.trim()) {
|
||||
blocks.push({ content: currentBlock.trim(), isCodeBlock: false })
|
||||
currentBlock = ''
|
||||
}
|
||||
} else {
|
||||
// Regular text line
|
||||
if (currentBlock) {
|
||||
currentBlock += '\n' + line
|
||||
} else {
|
||||
currentBlock = line
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Flush remaining content
|
||||
if (currentBlock) {
|
||||
blocks.push({
|
||||
content: inCodeBlock ? currentBlock : currentBlock.trim(),
|
||||
isCodeBlock: inCodeBlock // Unclosed code block = still streaming
|
||||
})
|
||||
}
|
||||
|
||||
return blocks
|
||||
}
|
||||
|
||||
/**
|
||||
* Memoized block component
|
||||
*
|
||||
* Only re-renders if content or mode changes.
|
||||
* The key is assigned by the parent based on content hash,
|
||||
* so identical content won't even attempt to render.
|
||||
*/
|
||||
const MemoizedBlock = React.memo(
|
||||
function Block({
|
||||
content,
|
||||
mode,
|
||||
onUrlClick,
|
||||
onFileClick
|
||||
}: {
|
||||
content: string
|
||||
mode: RenderMode
|
||||
onUrlClick?: (url: string) => void
|
||||
onFileClick?: (path: string) => void
|
||||
}) {
|
||||
return (
|
||||
<Markdown mode={mode} onUrlClick={onUrlClick} onFileClick={onFileClick}>
|
||||
{content}
|
||||
</Markdown>
|
||||
)
|
||||
},
|
||||
(prev, next) => {
|
||||
// Only re-render if content actually changed
|
||||
return prev.content === next.content && prev.mode === next.mode
|
||||
}
|
||||
)
|
||||
MemoizedBlock.displayName = 'MemoizedBlock'
|
||||
|
||||
/**
|
||||
* StreamingMarkdown - Optimized markdown renderer for streaming content
|
||||
*
|
||||
* Splits content into blocks (paragraphs, code blocks) and memoizes each block
|
||||
* independently. Only the last (active) block re-renders during streaming.
|
||||
*
|
||||
* Key insight: Completed blocks get a content-hash as their React key.
|
||||
* Same content = same key = React skips re-render entirely.
|
||||
*
|
||||
* @example
|
||||
* Content: "Hello\n\n```js\ncode\n```\n\nMore..."
|
||||
*
|
||||
* Block 1: "Hello" -> key="block-abc123" -> memoized
|
||||
* Block 2: "```js\ncode\n```" -> key="block-xyz789" -> memoized
|
||||
* Block 3: "More..." -> key="active-2" -> re-renders
|
||||
*/
|
||||
export function StreamingMarkdown({
|
||||
content,
|
||||
isStreaming,
|
||||
mode = 'minimal',
|
||||
onUrlClick,
|
||||
onFileClick
|
||||
}: StreamingMarkdownProps): React.JSX.Element {
|
||||
// Split into blocks - memoized to avoid recomputation
|
||||
// Must be called unconditionally to satisfy Rules of Hooks
|
||||
const blocks = React.useMemo(
|
||||
() => (isStreaming ? splitIntoBlocks(content) : []),
|
||||
[content, isStreaming]
|
||||
)
|
||||
|
||||
// Not streaming - use simple Markdown (no block splitting needed)
|
||||
if (!isStreaming) {
|
||||
return (
|
||||
<Markdown mode={mode} onUrlClick={onUrlClick} onFileClick={onFileClick}>
|
||||
{content}
|
||||
</Markdown>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{blocks.map((block, i) => {
|
||||
const isLastBlock = i === blocks.length - 1
|
||||
|
||||
// Complete blocks use content hash as key -> stable identity -> memoized
|
||||
// Last block uses "active" prefix -> always re-renders on content change
|
||||
const key = isLastBlock ? `active-${i}` : `block-${simpleHash(block.content)}`
|
||||
|
||||
return (
|
||||
<MemoizedBlock
|
||||
key={key}
|
||||
content={block.content}
|
||||
mode={mode}
|
||||
onUrlClick={onUrlClick}
|
||||
onFileClick={onFileClick}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</>
|
||||
)
|
||||
}
|
||||
4
packages/ui/src/components/markdown/index.ts
Normal file
4
packages/ui/src/components/markdown/index.ts
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
export { Markdown, MemoizedMarkdown, type MarkdownProps, type RenderMode } from './Markdown'
|
||||
export { CodeBlock, InlineCode, type CodeBlockProps } from './CodeBlock'
|
||||
export { StreamingMarkdown, type StreamingMarkdownProps } from './StreamingMarkdown'
|
||||
export { preprocessLinks, detectLinks, hasLinks } from './linkify'
|
||||
195
packages/ui/src/components/markdown/linkify.ts
Normal file
195
packages/ui/src/components/markdown/linkify.ts
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
import LinkifyIt from 'linkify-it'
|
||||
|
||||
/**
|
||||
* Linkify - URL and file path detection for markdown preprocessing
|
||||
*
|
||||
* Uses linkify-it (12M downloads/week) for battle-tested URL detection,
|
||||
* plus custom regex for local file paths.
|
||||
*/
|
||||
|
||||
// Initialize linkify-it with default settings (fuzzy URLs, emails enabled)
|
||||
const linkify = new LinkifyIt()
|
||||
|
||||
// File path regex - detects /path, ~/path, ./path with common extensions
|
||||
// Matches paths that start with /, ~/, or ./ followed by path chars and a file extension
|
||||
const FILE_PATH_REGEX =
|
||||
/(?:^|[\s([{<])((\/|~\/|\.\/)[\w\-./@]+\.(?:ts|tsx|js|jsx|mjs|cjs|md|json|yaml|yml|py|go|rs|css|scss|less|html|htm|txt|log|sh|bash|zsh|swift|kt|java|c|cpp|h|hpp|rb|php|xml|toml|ini|cfg|conf|env|sql|graphql|vue|svelte|astro|prisma|dockerfile|makefile|gitignore))(?=[\s)\]}.,;:!?>]|$)/gi
|
||||
|
||||
interface DetectedLink {
|
||||
type: 'url' | 'email' | 'file'
|
||||
text: string
|
||||
url: string
|
||||
start: number
|
||||
end: number
|
||||
}
|
||||
|
||||
interface CodeRange {
|
||||
start: number
|
||||
end: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Find all code block and inline code ranges in text
|
||||
* These ranges should be excluded from link detection
|
||||
*/
|
||||
function findCodeRanges(text: string): CodeRange[] {
|
||||
const ranges: CodeRange[] = []
|
||||
|
||||
// Find fenced code blocks (```...```)
|
||||
const fencedRegex = /```[\s\S]*?```/g
|
||||
let match
|
||||
while ((match = fencedRegex.exec(text)) !== null) {
|
||||
ranges.push({ start: match.index, end: match.index + match[0].length })
|
||||
}
|
||||
|
||||
// Find inline code (`...`)
|
||||
// But skip escaped backticks and code inside fenced blocks
|
||||
const inlineRegex = /(?<!`)`(?!`)([^`\n]+)`(?!`)/g
|
||||
while ((match = inlineRegex.exec(text)) !== null) {
|
||||
const pos = match.index
|
||||
// Check if this is inside a fenced block
|
||||
const insideFenced = ranges.some((r) => pos >= r.start && pos < r.end)
|
||||
if (!insideFenced) {
|
||||
ranges.push({ start: pos, end: pos + match[0].length })
|
||||
}
|
||||
}
|
||||
|
||||
return ranges
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a position is inside any code range
|
||||
*/
|
||||
function isInsideCode(pos: number, ranges: CodeRange[]): boolean {
|
||||
return ranges.some((r) => pos >= r.start && pos < r.end)
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a link at given position is already a markdown link
|
||||
* Looks for patterns like [text](url) or [text][ref]
|
||||
*/
|
||||
function isAlreadyLinked(text: string, linkStart: number, linkEnd: number): boolean {
|
||||
// Check if preceded by ]( which indicates we're inside a markdown link href
|
||||
// Pattern: [text](URL) - we're checking if URL is our link
|
||||
const before = text.slice(Math.max(0, linkStart - 2), linkStart)
|
||||
if (before.endsWith('](')) return true
|
||||
|
||||
// Check if preceded by ][ for reference links
|
||||
if (before.endsWith('][')) return true
|
||||
|
||||
// Check if the link text is wrapped in []
|
||||
// Pattern: [URL](href) - URL is being used as link text
|
||||
const charBefore = text[linkStart - 1]
|
||||
const charAfter = text[linkEnd]
|
||||
if (charBefore === '[' && charAfter === ']') return true
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if ranges overlap
|
||||
*/
|
||||
function rangesOverlap(
|
||||
a: { start: number; end: number },
|
||||
b: { start: number; end: number }
|
||||
): boolean {
|
||||
return a.start < b.end && b.start < a.end
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect all links (URLs, emails, file paths) in text
|
||||
*/
|
||||
export function detectLinks(text: string): DetectedLink[] {
|
||||
const links: DetectedLink[] = []
|
||||
|
||||
// 1. Detect URLs and emails with linkify-it
|
||||
const urlMatches = linkify.match(text) || []
|
||||
for (const match of urlMatches) {
|
||||
links.push({
|
||||
type: match.schema === 'mailto:' ? 'email' : 'url',
|
||||
text: match.text,
|
||||
url: match.url,
|
||||
start: match.index,
|
||||
end: match.lastIndex
|
||||
})
|
||||
}
|
||||
|
||||
// 2. Detect file paths with custom regex
|
||||
// Reset regex state
|
||||
FILE_PATH_REGEX.lastIndex = 0
|
||||
let fileMatch
|
||||
while ((fileMatch = FILE_PATH_REGEX.exec(text)) !== null) {
|
||||
const path = fileMatch[1]
|
||||
if (!path) continue // Skip if no capture group
|
||||
|
||||
// Calculate actual start position (after any leading whitespace/punctuation)
|
||||
const fullMatch = fileMatch[0]
|
||||
const pathOffset = fullMatch.indexOf(path)
|
||||
const start = fileMatch.index + pathOffset
|
||||
|
||||
// Check for overlaps with URL matches (URLs take precedence)
|
||||
const pathRange = { start, end: start + path.length }
|
||||
const overlapsUrl = links.some((link) => rangesOverlap(pathRange, link))
|
||||
if (overlapsUrl) continue
|
||||
|
||||
links.push({
|
||||
type: 'file',
|
||||
text: path,
|
||||
url: path, // File paths are passed as-is to onFileClick handler
|
||||
start,
|
||||
end: start + path.length
|
||||
})
|
||||
}
|
||||
|
||||
// Sort by position
|
||||
return links.sort((a, b) => a.start - b.start)
|
||||
}
|
||||
|
||||
/**
|
||||
* Preprocess text to convert raw URLs and file paths into markdown links
|
||||
* Skips code blocks and already-linked content
|
||||
*/
|
||||
export function preprocessLinks(text: string): string {
|
||||
// Quick check - if no potential links, return early
|
||||
if (!linkify.pretest(text) && !/[~/.]\//.test(text)) {
|
||||
return text
|
||||
}
|
||||
|
||||
const codeRanges = findCodeRanges(text)
|
||||
const links = detectLinks(text)
|
||||
|
||||
if (links.length === 0) return text
|
||||
|
||||
// Build result, converting raw links to markdown links
|
||||
let result = ''
|
||||
let lastIndex = 0
|
||||
|
||||
for (const link of links) {
|
||||
// Skip if inside code block
|
||||
if (isInsideCode(link.start, codeRanges)) continue
|
||||
|
||||
// Skip if already a markdown link
|
||||
if (isAlreadyLinked(text, link.start, link.end)) continue
|
||||
|
||||
// Add text before this link
|
||||
result += text.slice(lastIndex, link.start)
|
||||
|
||||
// Convert to markdown link
|
||||
result += `[${link.text}](${link.url})`
|
||||
|
||||
lastIndex = link.end
|
||||
}
|
||||
|
||||
// Add remaining text
|
||||
result += text.slice(lastIndex)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Test if text contains any detectable links
|
||||
* Useful for optimization - skip preprocessing if no links present
|
||||
*/
|
||||
export function hasLinks(text: string): boolean {
|
||||
return linkify.pretest(text) || /[~/.]\/[\w]/.test(text)
|
||||
}
|
||||
|
|
@ -119,6 +119,20 @@
|
|||
--sidebar-ring: oklch(0.552 0.016 285.938);
|
||||
}
|
||||
|
||||
/* Shiki dual themes: CSS-only light/dark switching via CSS variables */
|
||||
/* @see https://shiki.style/guide/dual-themes */
|
||||
.shiki,
|
||||
.shiki span {
|
||||
color: var(--shiki-light);
|
||||
background-color: var(--shiki-light-bg);
|
||||
}
|
||||
|
||||
.dark .shiki,
|
||||
.dark .shiki span {
|
||||
color: var(--shiki-dark) !important;
|
||||
background-color: var(--shiki-dark-bg) !important;
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
|
|
|
|||
1168
pnpm-lock.yaml
generated
1168
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue