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 (
{/* 先占位,避免微信 Image widthFix 加载前高度为 0 把后面章节挤跑 */}
{
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?.()
}
}}
/>
{alt ? (
{alt}
) : null}
)
}
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 (
暂无内容
)
}
return (
{blocks.map((b, i) => {
if (b.type === 'html') {
return (
)
}
return (
)
})}
)
}