✨ 迁移 Markdown 渲染并添加 Mermaid 预览和文章目录

This commit is contained in:
2026-11-15 22:05:13 +08:00
parent 293b743e50
commit 9d13e9aac2
14 changed files with 535 additions and 101 deletions
+171
View File
@@ -0,0 +1,171 @@
<script setup lang="ts">
import Panzoom, { type PanzoomObject } from '@panzoom/panzoom';
const props = defineProps<{ mermaidCode: string }>();
const diagramId = `mermaid-${useId()}`;
const svg = ref('');
const svgUrl = computed(() =>
svg.value
? `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg.value)}`
: '',
);
const errorMessage = ref('');
const scale = ref(1);
const svgWidth = ref(0);
const hover = ref(false);
onMounted(async () => {
try {
const { default: mermaid } = await import('mermaid');
mermaid.initialize({
startOnLoad: false,
securityLevel: 'strict',
theme: colorModeStore().isDarkMode ? 'dark' : 'default',
darkMode: colorModeStore().isDarkMode,
});
const result = await mermaid.render(diagramId, props.mermaidCode);
const doc = new DOMParser().parseFromString(
result.svg,
'image/svg+xml',
);
svgWidth.value = doc.querySelector('svg')?.viewBox.baseVal.width ?? 0;
svg.value = result.svg;
} catch (error) {
errorMessage.value
= error instanceof Error ? error.message : String(error);
}
});
const isFullscreen = ref(false);
const modalReady = ref(false);
let viewer: ReturnType<typeof Panzoom> | null = null;
const mermaidImage = ref<HTMLImageElement | null>(null);
function initializeViewer() {
if (
!modalReady.value
|| viewer
|| !mermaidImage.value?.complete
|| !mermaidImage.value.naturalWidth
) {
return;
}
viewer = Panzoom(mermaidImage.value, {
canvas: true,
minScale: 0.25,
maxScale: 6,
step: 0.2,
});
}
let startX = 0;
let startY = 0;
let moved = false;
function onPointerDown(event: PointerEvent) {
startX = event.clientX;
startY = event.clientY;
moved = false;
}
function onPointerMove(event: PointerEvent) {
if (Math.hypot(event.clientX - startX, event.clientY - startY) > 5) {
moved = true;
}
}
function onPreviewClick() {
if (!moved) {
isFullscreen.value = false;
}
}
const { copy, copied, isSupported: copySupported } = useClipboard();
</script>
<template>
<div class="my-5 overflow-x-auto">
<pre v-if="errorMessage" class="text-red-500 whitespace-pre-wrap">{{ errorMessage }}</pre>
<div v-else-if="svgUrl" class="relative" @mouseenter="hover=true" @mouseleave="hover=false">
<EasyScrollBar class="max-h-[60dvh] overflow-auto">
<img
:src="svgUrl"
:style="{ width: `${svgWidth * scale}px`}"
alt="Mermaid 图表"
class="block max-w-none mx-auto"
@click="isFullscreen = true"
/>
</EasyScrollBar>
<Transition
enter-active-class="transition-opacity duration-500"
enter-from-class="opacity-0"
enter-to-class="opacity-100"
leave-active-class="transition-opacity duration-100"
leave-from-class="opacity-100"
leave-to-class="opacity-0"
>
<div
v-show="copySupported && hover"
class="absolute inset-y-0 right-10"
>
<div v-if="copied">
copied!
</div>
<Icon
v-else
name="lucide:copy" class="w-6 h-6 text-gray-500 dark:text-gray-400 cursor-pointer"
mode="svg"
@click="copy(mermaidCode)"/>
</div>
</Transition>
<UModal
v-model:open="isFullscreen"
fullscreen
:ui="{
overlay: 'bg-black/70',
title: 'Mermaid 图表预览',
description: '使用鼠标滚轮缩放,拖动平移,点击空白处退出预览',
content: 'bg-transparent shadow-none ring-0',
}"
@after:enter="() => { modalReady = true; initializeViewer(); }"
@after:leave="() => { modalReady = false; (viewer! as PanzoomObject).destroy(); viewer = null; }"
>
<template #content>
<div
class="flex size-full items-center justify-center overflow-hidden p-6"
@pointerdown.capture="onPointerDown"
@pointermove.capture="onPointerMove"
@click="onPreviewClick"
@wheel.prevent="(e)=>{
console.log(e);
(viewer! as PanzoomObject).zoomWithWheel(e)
}"
>
<img
ref="mermaidImage"
:src="svgUrl"
:style="{ width: `${svgWidth}px` }"
class="block m-auto max-h-full max-w-full shrink-0 select-none object-contain"
alt="Mermaid 图表"
draggable="false"
@load="initializeViewer"
/>
</div>
</template>
</UModal>
</div>
<div v-else class="text-gray-500 dark:text-gray-400">正在渲染 Mermaid 图表...</div>
</div>
</template>
<style scoped>
</style>
-79
View File
@@ -1,79 +0,0 @@
<script setup lang="ts">
import { MdPreview } from 'md-editor-v3';
import 'md-editor-v3/lib/preview.css';
import useColorModeStore from '~/stores/colorModeStore';
const props = withDefaults(defineProps<{
editorId: string;
markdown?: string;
}>(), {
markdown: () => '## Hello World!',
});
const eraseHeaderMarkdown = computed(() => props.markdown.replace(/^---[\s\S]*?---\n?/, ''));
const { colorMode } = storeToRefs(useColorModeStore());
const mounted = ref(false);
onMounted(() => {
mounted.value = true;
});
</script>
<template>
<div class="pt-0 bg-old-neutral-200 dark:bg-old-neutral-800">
<MdPreview
v-if="mounted"
:key="editorId + '-' + colorMode"
:editor-id="editorId"
:theme="colorMode"
:model-value="eraseHeaderMarkdown"
class="max-w-full"
/>
<div v-else class="w-5/6">
<USkeleton class="h-4 mb-3 w-full bg-old-neutral-600"/>
<USkeleton class="h-4 mb-3 w-full bg-old-neutral-600"/>
<USkeleton class="h-4 mb-3 w-full bg-old-neutral-600"/>
<USkeleton class="h-4 mb-3 w-full bg-old-neutral-600"/>
</div>
</div>
</template>
<style scoped>
:deep(.md-editor) {
--md-bk-color: #e5e5e5;
--md-theme-heading-1-color: #fff;
transition-property: all;
transition-duration: 500ms;
--tw-ease: cubic-bezier(0.4, 0, 0.2, 1);
transition-timing-function: var(--tw-ease, var(--default-transition-timing-function));
}
:deep(.md-editor-preview blockquote) {
transition-property: all;
transition-duration: 500ms;
--tw-ease: cubic-bezier(0.4, 0, 0.2, 1);
transition-timing-function: var(--tw-ease, var(--default-transition-timing-function));
}
:deep(.md-editor-preview .md-editor-code .md-editor-code-head) {
z-index: 5;
}
:deep(ul) {
list-style-type: disc;
}
:deep(ol) {
list-style-type: decimal;
}
:global(.dark .md-editor) {
--md-bk-color: #262626;
--md-theme-heading-1-color: #fff;
}
:global(.dark .md-editor-preview) {
--md-color: var(--ui-text);
}
</style>
@@ -0,0 +1,9 @@
<template>
<code
class="px-1.5 py-0.5 text-sm font-mono font-medium rounded-md inline-block border
bg-gray-100 dark:bg-old-neutral-900 border-gray-300 dark:border-old-neutral-700
text-gray-800 dark:text-gray-200">
<slot/>
</code>
</template>
@@ -0,0 +1,18 @@
<script setup lang="ts">
import DefaultProsePre from '@nuxt/ui/components/prose/Pre.vue';
const props = defineProps<{
code?: string; // 原始代码文本(以后做"复制按钮"会用到)
language?: string; // 语言,如 'ts'
filename?: string; // 代码块文件名(如果 md 里写了)
highlights?: number[];
meta?: string;
}>();
</script>
<template>
<MermaidDiagram v-if="props.language === 'mermaid'" :mermaid-code="props.code ?? ''" />
<DefaultProsePre v-else v-bind="props" :ui="{base: 'bg-white dark:bg-old-neutral-700 border-gray-300 dark:border-old-neutral-700'}">
<slot />
</DefaultProsePre>
</template>
+9
View File
@@ -0,0 +1,9 @@
const KEY: InjectionKey<Ref<number>> = Symbol('navbarHeight');
export function provideNavbarHeight(h: Ref<number>) {
provide(KEY, h);
}
export function injectNavbarHeight(): Ref<number> {
return inject(KEY, ref(48));
}
+1 -1
Submodule content updated: 2865b12ed9...78c45544b3
+9 -2
View File
@@ -1,6 +1,7 @@
<script setup lang="ts">
import type { NavigationMenuItem } from '@nuxt/ui';
import useColorModeStore from '~/stores/colorModeStore';
import { provideNavbarHeight } from '~/composables/useNavbarHeight';
const { colorMode } = storeToRefs(useColorModeStore());
@@ -63,6 +64,11 @@ const mounted = ref(false);
onMounted(() => {
mounted.value = true;
});
const navbarEl = ref<HTMLDivElement>();
const { height: navbarHeight } = useElementSize(navbarEl);
provideNavbarHeight(navbarHeight);
</script>
<template>
@@ -73,8 +79,8 @@ onMounted(() => {
class="flex flex-col relative transition-[height] duration-500 max-h-80 min-h-40">
<!-- header -->
<div
v-if="mounted"
@mouseenter="() => {
v-if="mounted"
@mouseenter="() => {
if(scrollY === 0) {
collapsed = false;
}
@@ -101,6 +107,7 @@ onMounted(() => {
</div>
<!-- navbar -->
<div
ref="navbarEl"
class="fixed z-10 w-full transition-all duration-500 dark:bg-gray-800/60 bg-old-neutral-50/40 backdrop-blur-sm dark:backdrop-blur-md">
<div class="flex justify-center items-center h-full">
<div class="flex-1 overflow-hidden">
+16 -2
View File
@@ -18,7 +18,6 @@ export default defineNuxtConfig({
],
css: ['~/assets/css/main.css'],
ui: {
colorMode: false,
fonts: false,
},
app: {
@@ -30,7 +29,22 @@ export default defineNuxtConfig({
meta: [
{ name: 'description', content: 'Lichx 个人博客' },
],
script: [{ src: '/darkVerify.js' }],
},
},
content: {
build: {
markdown: {
highlight: {
theme: {
default: 'github-light',
dark: 'github-dark',
},
},
toc: {
depth: 4,
searchDepth: 4,
},
},
},
},
icon: {
-1
View File
@@ -25,7 +25,6 @@
"eslint": "^9.39.5",
"gsap": "^3.15.1",
"highcharts": "^12.6.2",
"md-editor-v3": "^6.0.1",
"mermaid": "^12.3.0",
"nuxt": "^4.6.4",
"overlayscrollbars-vue": "^0.5.10",
@@ -0,0 +1,28 @@
<script setup lang="ts">
import type { Collections } from '@nuxt/content';
import ProsePre from '~/components/theme/classic/markdown/ProsePre.vue';
import ProseCode from '~/components/theme/classic/markdown/ProseCode.vue';
type Article = Collections['content'] & {};
defineProps<{
article: Article | null | undefined;
noPadding?: boolean;
}>();
const themeComponents = {
classic: {
pre: ProsePre,
code: ProseCode,
},
};
</script>
<template>
<ContentRenderer
v-if="article" class="px-6 pb-6 pt-0.5 bg-old-neutral-200 dark:bg-old-neutral-800" :value="article!"
:class="{ 'p-0! [&_p]:m-0! [&_p]:leading-6': true }"
:components="themeComponents['classic']"/>
</template>
<style scoped>
</style>
@@ -0,0 +1,59 @@
<script setup lang="ts">
import type { TocLink } from '@nuxt/content';
import TocList from '~/pages/index/article/[articleID]/components/TocList.vue';
const props = defineProps<{ links: TocLink[] }>();
const activeIds = ref<string[]>([]);
const { height } = useWindowSize();
const navBarHeight = injectNavbarHeight();
const flattenedLinks = ref<TocLink[]>(flatten(props.links));
function flatten(links: TocLink[]): TocLink[] {
return links.flatMap((l) => [l, ...(l.children ? flatten(l.children as TocLink[]) : [])]);
}
function onScroll() {
const localActiveIds: string[] = [];
flattenedLinks.value = flatten(props.links);
const links = flattenedLinks.value;
const topBias = 66;
const navBarHeightVal = navBarHeight.value + topBias;
for (let i = 0; i < links.length; i++) {
const element = document.getElementById(links[i]!.id);
if (!element) {
continue;
}
const elTop = element.getBoundingClientRect().top;
if (i == links.length - 1) {
if ((elTop > navBarHeightVal && elTop < height.value)
|| (elTop < navBarHeightVal)) {
localActiveIds.push(links[i]!.id);
}
continue;
}
const nextElement = document.getElementById(links[i + 1]!.id);
if (!element || !nextElement) {
continue;
}
const nextElTop = nextElement.getBoundingClientRect().top;
if ((elTop > navBarHeightVal && elTop < height.value)
|| (elTop < navBarHeightVal && nextElTop > navBarHeightVal)
|| (nextElTop > navBarHeightVal && nextElTop < height.value)) {
localActiveIds.push(links[i]!.id);
}
}
activeIds.value = localActiveIds;
}
onNuxtReady(() => {
window.addEventListener('scroll', onScroll);
onScroll();
});
onUnmounted(() => window.removeEventListener('scroll', onScroll));
</script>
<template>
<!-- 把整棵树和算好的 activeId 交给递归渲染组件 -->
<TocList :links="flattenedLinks" :active-ids="activeIds"/>
</template>
@@ -0,0 +1,207 @@
<script setup lang="ts">
import type { TocLink } from '@nuxt/content';
// 2 6
// 24 20
// 2 6
// 24 20
// 2 6
const props = defineProps<{ links: TocLink[]; activeIds: string[] }>();
// const flattenedLinks = computed(() => {
// props.links.forEach(link => {
// })
function getClassNames(index: number) {
if (index < 0 || index > props.links.length) {
return '';
}
const link = props.links[index]!;
let className = '';
if (props.activeIds.includes(link.id)) {
className += 'text-sky-400 dark:text-[#cccaff] font-medium border-l-sky-400 dark:border-l-[#cccaff]';
} else {
className += 'text-old-neutral-500 border-l-old-neutral-800';
}
return className;
}
let currentStart = 0;
let currentEnd = 0;
let targetStart = 0;
let targetEnd = 0;
const tocHeight = 26;
const maxedHeight = computed(() => props.links.length * tocHeight);
const targetPoints: Ref<number[]> = ref([]);
const points = ref('');
let animationFrameId = 0;
const startCx = ref(0), startCy = ref(0), endCx = ref(0), endCy = ref(0);
function updateSvgPoints() {
if (props.activeIds.length == 0) {
return [];
}
const points: number[] = [];
const gapHeight = 6, tocHeight = 20;
const yBias = -3;
const xBias = 5;
function isIntersect(ab: number, ae: number, bb: number, be: number): boolean {
return Math.max(ab, bb) < Math.min(ae, be);
}
function getIntersects(ab: number, ae: number, bb: number, be: number): [number, number] {
return [Math.max(ab, bb), Math.min(ae, be)];
}
for (let i = 0; i < props.links.length; i++) {
const link = props.links[i]!;
const linkStart = i * tocHeight + (i + 1) * gapHeight + yBias;
const linkEnd = (i + 1) * tocHeight + (i + 1) * gapHeight + yBias;
if (isIntersect(linkStart, linkEnd, currentStart, currentEnd)) {
const [yStart, yEnd] = getIntersects(linkStart, linkEnd, currentStart, currentEnd);
points.push((link.depth - 2) * 12 + xBias);
points.push(yStart);
points.push((link.depth - 2) * 12 + xBias);
points.push(yEnd);
}
if (i < props.links.length - 1) {
const nextLinkStart = (i + 1) * tocHeight + (i + 2) * gapHeight + yBias;
if (isIntersect(currentStart, currentEnd, linkEnd, nextLinkStart)) {
const [xFullStart, xFullEnd] = [(link.depth - 2) * 12 + xBias, (props.links[i + 1]!.depth - 2) * 12 + xBias];
if (currentStart > linkEnd && currentStart < nextLinkStart) {
const x = xFullStart + (xFullEnd - xFullStart) * (currentStart - linkEnd) / (nextLinkStart - linkEnd);
points.push(x);
points.push(currentStart);
}
if (currentEnd > linkEnd && currentEnd < nextLinkStart) {
const x = xFullEnd - (xFullEnd - xFullStart) * (nextLinkStart - currentEnd) / (nextLinkStart - linkEnd);
points.push(x);
points.push(currentEnd);
}
}
}
}
[startCx.value, startCy.value] = [points[0] ?? -100, points[1] ?? -100];
[endCx.value, endCy.value] = [points[points.length - 2] ?? -100, points[points.length - 1] ?? -100];
return points;
}
function getTarget(): [number, number] {
if (props.activeIds.length == 0) {
return [-1, -1];
}
const points: number[] = [];
const gapHeight = 6, tocHeight = 20;
const bias = -3;
for (let i = 0; i < props.links.length; i++) {
const link = props.links[i]!;
if (props.activeIds.includes(link.id)) {
points.push((link.depth - 2) * 12 + 1);
points.push(i * tocHeight + (i + 1) * gapHeight);
points.push((link.depth - 2) * 12 + 1);
points.push((i + 1) * tocHeight + (i + 1) * gapHeight);
}
}
const edgeBias = 2;
if (points.length > 1 && props.activeIds.includes(props.links[0]!.id)) {
points[1]! += edgeBias;
}
if (points.length > 1 && props.activeIds.includes(props.links[props.links.length - 1]!.id)) {
points[points.length - 1]! -= edgeBias;
}
points.forEach((x, i, arr) => {
arr[i] = i % 2 == 0 ? x : x + bias;
});
targetPoints.value = points;
if (points.length >= 2) {
return [points[1]!, points[points.length - 1]!];
}
return [-1, -1];
}
function doUpdate() {
[targetStart, targetEnd] = getTarget();
const factor = 0.1;
function updateSvg() {
points.value = updateSvgPoints().join(',');
const startDelta = (targetStart - currentStart) * factor;
const endDelta = (targetEnd - currentEnd) * factor;
currentStart += startDelta;
currentEnd += endDelta;
if (Math.abs(currentStart - targetStart) < 0.2 && Math.abs(currentEnd - targetEnd) < 0.2) {
currentStart = targetStart;
currentEnd = targetEnd;
points.value = updateSvgPoints().join(',');
return;
}
animationFrameId = requestAnimationFrame(updateSvg);
}
animationFrameId = requestAnimationFrame(updateSvg);
}
// 外面在 onNuxtReady 更新数据 里面在onMounted时设置钩子
onMounted(() => {
watchEffect(() => {
doUpdate();
});
});
onUnmounted(() => {
cancelAnimationFrame(animationFrameId);
});
</script>
<template>
<div class="relative">
<svg
class="absolute pointer-events-none" :viewBox="`0 0 100 ${maxedHeight}`" width="100"
:height="`${links.length * tocHeight}`">
<circle
v-if="startCx != -100 || startCy != -100"
:cx="startCx" :cy="startCy"
r="1" fill="none"
stroke-width="3"
class="stroke-old-neutral-400 dark:stroke-white"/>
<circle
v-if="endCx != -100 || endCy == -100"
:cx="endCx" :cy="endCy"
r="1" fill="none"
stroke-width="3"
class="stroke-old-neutral-400 dark:stroke-white"/>
<polyline
:points="points" fill="none" class="stroke-old-neutral-400 dark:stroke-white" stroke-width="2"
stroke-linejoin="round"></polyline>
</svg>
<ul>
<li
v-for="(link,idx) in links" :key="link.id"
class="not-last:mb-0.5 not-first:mt-0.5"
:style="{ marginLeft: `${ (link.depth - 2) * 12}px` }"
>
<a
:href="`#${link.id}`"
class="transition-colors duration-300"
:class="getClassNames(idx)">
<div class="text-sm text-nowrap truncate max-w-full pl-4 h-6 pt-0.75">
{{ link.text }}
</div>
</a>
</li>
</ul>
</div>
</template>
<style scoped>
</style>
+5 -5
View File
@@ -1,11 +1,12 @@
<script setup lang="ts">
import { toMetaDataType } from '~/types/PostMetaData';
import { MdCatalog } from 'md-editor-v3';
import ArticleHeader from '~/pages/index/article/[articleID]/components/ArticleHeader.vue';
import ArticleToc from './components/ArticleToc.vue';
import ArticleContent from '~/pages/index/article/[articleID]/components/ArticleContent.vue';
const articleId = useRoute().params.articleID as string;
const { data: article } = useAsyncData(async () => await queryCollection('content').where('id', '=', articleId).first());
const editorId = 'article-previewer';
</script>
<template>
@@ -15,14 +16,13 @@ const editorId = 'article-previewer';
<div class="relative duration-500 transition-[width] xl:w-80 w-0 mr-2/3 overflow-hidden">
<div class="w-80 top-0 left-0 text-gray-800 dark:text-white p-5">
<div class="text-3xl mb-2">目录</div>
<MdCatalog :editor-id="editorId" :scroll-element="'html'" class=""/>
<ArticleToc :links="article?.body?.toc?.links ?? []" />
</div>
</div>
</div>
<div class="transition-[width] duration-500 float-right xl:w-[calc(100%-20rem-40px)] w-full max-w-full">
<ArticleHeader v-if="article" class="w-full" :meta-data="toMetaDataType(article)"/>
<!-- <ArticleCard v-if="article" class=" w-full" :article="toArticleMetaDataType(article)"/>-->
<ReadonlyMdEditor :editor-id="editorId" :markdown="article?.rawbody" class="p-5 max-w-full"/>
<ArticleContent :article="article"/>
</div>
</div>
</div>
+3 -11
View File
@@ -9,7 +9,7 @@ const props = withDefaults(defineProps<{
{
metaData: () => defaultMetaData,
});
const { data: rawbody } = useAsyncData('simpleCard:' + props.metaData.id, async () => (await queryCollection('content').where('id', '=', props.metaData.id).first())?.rawbody);
const { data: article } = useAsyncData('simpleCard:' + props.metaData.id, async () => (await queryCollection('content').where('id', '=', props.metaData.id).first()));
const collapsed = ref(true);
const typeChinese = new Map<string | undefined, string>([
['rambling', '絮语'],
@@ -47,12 +47,6 @@ function getCostTime(length: number | DataAnomaly) {
}
}
const safeEditorId = computed(() => {
const encoded = btoa(encodeURIComponent(props.metaData.id))
.replace(/[+/=]/g, '_'); // 替换 Base64 中的特殊字符
return `rambling_${encoded}`;
});
const showShadow = ref(true);
function reverseCollapsed() {
@@ -76,7 +70,7 @@ function reverseCollapsed() {
<div class="text-4xl">
{{ (typeChinese.get(metaData?.type) || 'unknown Type') + ':' }}{{ props.metaData.title }}
</div>
<div class="flex items-center mt-2 max-w-[400px] overflow-hidden">
<div class="flex items-center mt-2 max-w-100 overflow-hidden">
<div title="发布时间" class="flex items-center">
<Icon name="lucide:clock-arrow-up"/>
@@ -117,9 +111,7 @@ function reverseCollapsed() {
<div
class="relative flex mt-2 justify-between overflow-hidden duration-300 ease-in-out min-h-34"
:class="{'max-h-34' : collapsed, 'max-h-screen':!collapsed}">
<ReadonlyMdEditor
v-if="rawbody" :editor-id="safeEditorId" :markdown="rawbody!"
class="w-full"/>
<ArticleContent v-if="article" :article="article" class="w-full"/>
<div
class="absolute bottom-0 left-0 right-0 h-14 bg-linear-to-t from-old-neutral-200 dark:from-old-neutral-800 to-transparent pointer-events-none transition-opacity duration-300"
:class="collapsed && showShadow?'opacity-100':'opacity-0'"