nomadro/apps/miniprogram/h5/src/components/MarkdownView.tsx
eric 3e5b7c2098 Monorepo super-optimize: src layout, workspace scripts, docs.
Collapse portal under src/, unify pnpm workspace/scripts, thin VIP topic re-exports, drop orphan vip scaffolds and one-shot scripts, ignore xhs/release, document root commands.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 00:34:04 +08:00

122 lines
3.1 KiB
TypeScript

import { View, Text, RichText, Image } from '@tarojs/components'
import { useMemo, useState } from 'react'
import { markdownToBlocks } from '../utils/markdown'
import type { ReaderPrefs } from '../utils/readerPrefs'
import { fontFamilyCss, themeColors } from '../utils/readerPrefs'
import {
DEFAULT_IMG_RATIO,
getCachedImageRatio,
setCachedImageRatio,
} from '../utils/imageSizeCache'
import './MarkdownView.scss'
type Props = {
markdown: string
prefs?: ReaderPrefs
dropCap?: boolean
/** 任意图片加载导致高度变化时回调(用于章节回钉) */
onImageLayout?: () => void
}
function MdImage({
src,
alt,
borderColor,
surface,
muted,
onImageLayout,
}: {
src: string
alt: string
borderColor: string
surface: string
muted: string
onImageLayout?: () => void
}) {
const [ratio, setRatio] = useState(
() => getCachedImageRatio(src) || DEFAULT_IMG_RATIO
)
return (
<View className='md-img-wrap'>
<View
className='md-img-frame'
style={{ borderColor, background: surface }}
>
{/* 先占位,避免微信 Image widthFix 加载前高度为 0 把后面章节挤跑 */}
<View className='md-img-slot' style={{ paddingBottom: `${ratio * 100}%` }}>
<Image
className='md-img'
src={src}
mode='aspectFit'
lazyLoad
showMenuByLongpress
onLoad={(e) => {
const w = Number(e.detail?.width || 0)
const h = Number(e.detail?.height || 0)
const next = setCachedImageRatio(src, w, h)
if (Math.abs(next - ratio) > 0.01) {
setRatio(next)
onImageLayout?.()
}
}}
/>
</View>
{alt ? (
<Text className='md-img-alt' style={{ color: muted }}>
{alt}
</Text>
) : null}
</View>
</View>
)
}
export function MarkdownView({ markdown, prefs, dropCap, onImageLayout }: Props) {
const blocks = useMemo(() => {
if (!markdown) return []
return markdownToBlocks(markdown, {
fontSize: prefs?.fontSize,
lineHeight: prefs?.lineHeight,
theme: prefs?.theme,
dropCap,
})
}, [markdown, prefs?.fontSize, prefs?.lineHeight, prefs?.theme, dropCap])
const family = fontFamilyCss(prefs?.fontFamily || 'sans')
const colors = themeColors(prefs?.theme || 'dark')
if (!markdown) {
return (
<View className='md' style={{ fontFamily: family }}>
<Text className='empty'>暂无内容</Text>
</View>
)
}
return (
<View className='md' style={{ fontFamily: family }}>
{blocks.map((b, i) => {
if (b.type === 'html') {
return (
<View key={`h-${i}`} className='md-html'>
<RichText nodes={b.html} />
</View>
)
}
return (
<MdImage
key={`i-${i}-${b.src}`}
src={b.src}
alt={b.alt}
borderColor={colors.border}
surface={colors.surface}
muted={colors.muted}
onImageLayout={onImageLayout}
/>
)
})}
</View>
)
}