feat: improve archive frontend and open-source docs

This commit is contained in:
YGC
2026-07-02 21:38:42 +08:00
parent 97d29e1135
commit e2e7cf85b1
27 changed files with 922 additions and 223 deletions
+5
View File
@@ -0,0 +1,5 @@
# Browser requests stay same-origin and are forwarded by Next.js rewrites.
NEXT_PUBLIC_API_BASE_URL=/api
# Used by Server Components and the development rewrite target.
SERVER_API_BASE_URL=http://localhost:8080/api
+5
View File
@@ -0,0 +1,5 @@
# Keep the browser on the public site origin. OpenResty forwards /api to Java.
NEXT_PUBLIC_API_BASE_URL=/api
# Internal address used only by the Next.js server on the production host.
SERVER_API_BASE_URL=http://127.0.0.1:8080/api
+2
View File
@@ -4,6 +4,8 @@ out/
.DS_Store
*.log
.env*
!.env.development
!.env.production
.pnp
.pnp.*
.yarn/*
+180
View File
@@ -0,0 +1,180 @@
# My House · 生活档案馆(Blog)
一个面向个人博客与私人生活归档的前台站点。它不只承载文章,也用于整理影像、足迹、近况、恋爱记录、时间信件、成就与访客反馈。
![Next.js](https://img.shields.io/badge/Next.js-16.2.9-000000?logo=nextdotjs)
![React](https://img.shields.io/badge/React-19.2-149ECA?logo=react&logoColor=white)
![TypeScript](https://img.shields.io/badge/TypeScript-5-3178C6?logo=typescript&logoColor=white)
![Tailwind CSS](https://img.shields.io/badge/Tailwind_CSS-4-06B6D4?logo=tailwindcss&logoColor=white)
## 项目预览
<!--
将桌面端截图保存为 docs/images/home-desktop.png 后,用下面这行替换截图占位:
<img src="./docs/images/home-desktop.png" alt="生活档案馆首页桌面端预览" width="100%" />
-->
<div align="center">
<br />
<strong>📷 截图占位 · 首页桌面端</strong>
<br />
<sub>建议尺寸:1600 × 900</sub>
<br /><br /><br />
</div>
<!--
将移动端截图保存为 docs/images/home-mobile.png 后,用下面这行替换截图占位:
<img src="./docs/images/home-mobile.png" alt="生活档案馆首页移动端预览" width="360" />
-->
<div align="center">
<br />
<strong>📱 截图占位 · 首页移动端</strong>
<br />
<sub>建议尺寸:390 × 844</sub>
<br /><br /><br />
</div>
## 三端组成
| 项目 | 职责 | 仓库 |
| --- | --- | --- |
| Blog | 面向访客的博客与生活档案前台 | **当前仓库** |
| Admin | 内容与站点配置管理后台 | [spring_admin](https://github.com/RRTiamo/spring_admin) |
| Server | API、鉴权、数据库与文件存储 | [spring_server](https://github.com/RRTiamo/spring_server) |
```mermaid
flowchart LR
visitor["访客"] --> blog["Blog · Next.js"]
manager["管理员"] --> admin["Admin · Vue"]
blog --> api["Server · /api"]
admin --> api
api --> mysql[("MySQL")]
api --> storage["本地 / MinIO / 七牛云"]
```
## 主要功能
- 文章列表、分类、归档、搜索与 Markdown 正文阅读
- 照片墙、足迹地图、随笔便签与个人成就
- “此时此刻”、关于作者和可动态配置的站点信息
- 恋爱纪实、愿望清单、时间胶囊与岁月信箱
- 鱼塘反馈、点赞、回复及友情链接
- 响应式布局、明暗主题和基于 GSAP / Lenis 的页面动效
- 服务端与浏览器端分离的 API 地址配置
## 技术栈
- Next.js 16 App Router
- React 19 + TypeScript 5
- Tailwind CSS 4
- Axios
- GSAP + ScrollTrigger、Lenis、Framer Motion
- Leaflet、Highlight.js
## 本地运行
### 环境要求
- Node.js `>= 20.9.0`
- npm
- 已启动的 [spring_server](https://github.com/RRTiamo/spring_server),默认地址为 `http://localhost:8080/api`
### 1. 获取项目
```bash
git clone https://github.com/RRTiamo/spring_blogs.git
cd spring_blogs
npm ci
```
### 2. 配置开发环境
项目根目录创建或修改 `.env.development`:
```dotenv
# 浏览器请求地址。开发环境使用同源 /api,由 Next.js 转发。
NEXT_PUBLIC_API_BASE_URL=/api
# Server Component、SSR 和 Next.js rewrites 访问后端的地址。
SERVER_API_BASE_URL=http://localhost:8080/api
```
### 3. 启动
```bash
npm run dev
```
访问 [http://localhost:3000](http://localhost:3000)。
## 环境变量
| 变量 | 用途 | 开发环境建议值 |
| --- | --- | --- |
| `NEXT_PUBLIC_API_BASE_URL` | 浏览器端 API 基础路径,会暴露在前端构建产物中 | `/api` |
| `SERVER_API_BASE_URL` | 服务端渲染与 rewrites 使用的后端地址 | `http://localhost:8080/api` |
生产环境建议让浏览器继续访问同源 `/api`,再由反向代理转发至后端;`SERVER_API_BASE_URL` 应填写 Next.js 服务器能够访问的内部 API 地址。
## 可用命令
| 命令 | 说明 |
| --- | --- |
| `npm run dev` | 启动开发服务器 |
| `npm run lint` | 运行 ESLint |
| `npm run build` | 创建生产构建 |
| `npm run start` | 启动生产服务器 |
提交前至少运行:
```bash
npm run lint
npm run build
```
## 目录结构
```text
src/
├─ api/ # 统一 API 请求与接口封装
├─ app/ # App Router 页面和布局
├─ components/ # 页面区块与可复用组件
├─ hooks/ # 客户端状态与数据逻辑
├─ icon/ # 图标映射
├─ interface/ # 核心 TypeScript 类型
├─ mock/ # 静态兜底数据
└─ data/ # 页面使用的轻量数据
```
## 生产部署
```bash
npm ci
npm run build
npm run start
```
项目已启用 Next.js `standalone` 输出。无论采用 Node 进程托管还是独立产物部署,都需要确保:
1. `SERVER_API_BASE_URL` 在构建和运行环境中可访问。
2. 公网 `/api` 被正确转发到 Server 的 `/api`。
3. 上传文件或对象存储域名允许被浏览器访问。
4. Blog、Admin 与 Server 全部使用 HTTPS,避免混合内容。
## 开源与隐私检查
这是生活归档类项目,公开仓库前请重点检查:
- `.env*` 中不得包含令牌、数据库密码或云存储密钥。
- `public/`、`assets/`、Mock 数据和默认内容中不得保留不准备公开的照片或个人信息。
- 地图坐标、恋爱记录、时间信件等内容应由部署者替换为自己的数据。
- 第三方图片、字体、音乐和地图服务应确认授权及使用条款。
## 参与贡献
欢迎通过 Issue 提交问题,或通过 Pull Request 改进功能。请保持 API 请求、类型、Mock 数据和图标配置分别位于现有的 `api/`、`interface/`、`mock/` 与 `icon/` 目录中。
## 许可证
当前仓库尚未附带开源许可证。在仓库根目录补充明确的 `LICENSE` 前,代码默认保留全部权利。
+1 -1
View File
@@ -1,6 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
import "./.next/dev/types/routes.d.ts";
import "./.next/types/routes.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
+16
View File
@@ -1,6 +1,22 @@
import type { NextConfig } from "next";
const serverApiBaseUrl = (
process.env.SERVER_API_BASE_URL ??
(process.env.NODE_ENV === "production"
? "http://127.0.0.1:8080/api"
: "http://localhost:8080/api")
).replace(/\/+$/, "");
const nextConfig: NextConfig = {
output: "standalone",
async rewrites() {
return [
{
source: "/api/:path*",
destination: `${serverApiBaseUrl}/:path*`,
},
];
},
images: {
unoptimized: true,
remotePatterns: [
+6 -1
View File
@@ -1,5 +1,10 @@
import request from './request'
import request, { getServerApiURL } from './request'
export function getPublicConfig() {
return request.get('/config/public')
}
export async function fetchPublicConfigForServer(init?: Parameters<typeof fetch>[1]) {
const response = await fetch(getServerApiURL('/config/public'), init)
return response.json()
}
+25 -1
View File
@@ -1,7 +1,31 @@
import axios from 'axios'
const browserApiBaseUrl = (process.env.NEXT_PUBLIC_API_BASE_URL || '/api').replace(/\/+$/, '')
function getServerApiBaseURL() {
return (
process.env.SERVER_API_BASE_URL ||
(process.env.NODE_ENV === 'production'
? 'http://127.0.0.1:8080/api'
: 'http://localhost:8080/api')
).replace(/\/+$/, '')
}
export function getApiBaseURL() {
if (typeof window !== 'undefined') {
return browserApiBaseUrl
}
return getServerApiBaseURL()
}
export function getServerApiURL(path: string) {
const normalizedPath = path.startsWith('/') ? path : `/${path}`
return `${getServerApiBaseURL()}${normalizedPath}`
}
const request = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:8080/api',
baseURL: getApiBaseURL(),
timeout: 15000,
})
-21
View File
@@ -2,7 +2,6 @@ import React from "react";
import AchievementsPageClient from "@/components/achievements/AchievementsPageClient";
import { Achievement } from "@/components/achievements/CertificateCard";
import { getAchievementsList, getAchievementMetasList } from "@/api/achievements";
import { getPublicConfig } from "@/api/config";
export interface AchievementMeta {
id: number;
@@ -38,34 +37,14 @@ async function getAchievementMetas(): Promise<AchievementMeta[]> {
return [];
}
async function getPublicConfigs(): Promise<Record<string, string>> {
try {
const res = await getPublicConfig();
const data = res.data;
if (data && data.code === 200 && Array.isArray(data.data)) {
const configMap: Record<string, string> = {};
data.data.forEach((item: any) => {
configMap[item.configKey] = item.configValue;
});
return configMap;
}
} catch (err) {
console.warn("Achievements Page SSR configs: API offline, using empty configuration.", err);
}
return {};
}
export default async function AchievementsPage() {
const achievements = await getAchievements();
const metas = await getAchievementMetas();
const configs = await getPublicConfigs();
return (
<AchievementsPageClient
initialItems={achievements}
initialMetas={metas}
configs={configs}
/>
);
}
+10 -12
View File
@@ -9,6 +9,7 @@ import StyleConsole from "@/components/ui/StyleConsole";
import BackToTop from "@/components/ui/BackToTop";
import TapeStation from "@/components/ui/TapeStation";
import ThemeApplier from "@/components/ui/ThemeApplier";
import { fetchPublicConfigForServer } from "@/api/config";
const inter = Inter({
variable: "--font-inter",
@@ -65,18 +66,15 @@ export async function generateMetadata(): Promise<Metadata> {
let title = "春风不解别离 | 个人生活档案馆";
let faviconUrl = "/icon.png";
try {
const res = await fetch("http://localhost:8080/api/config/public", { next: { revalidate: 10 } });
if (res.ok) {
const data = await res.json();
if (data.code === 200 && Array.isArray(data.data)) {
const titleItem = data.data.find((c: any) => c.configKey === "site.title.default");
if (titleItem?.configValue) {
title = titleItem.configValue;
}
const favItem = data.data.find((c: any) => c.configKey === "site.favicon.url");
if (favItem?.configValue) {
faviconUrl = favItem.configValue;
}
const data = await fetchPublicConfigForServer({ next: { revalidate: 10 } });
if (data.code === 200 && Array.isArray(data.data)) {
const titleItem = data.data.find((c: any) => c.configKey === "site.title.default");
if (titleItem?.configValue) {
title = titleItem.configValue;
}
const favItem = data.data.find((c: any) => c.configKey === "site.favicon.url");
if (favItem?.configValue) {
faviconUrl = favItem.configValue;
}
}
} catch (e) {
-5
View File
@@ -2,11 +2,6 @@ import { notFound } from "next/navigation";
import LovePageClient from "@/components/love/LovePageClient";
import { getPublicConfig } from "@/api/config";
interface PublicConfig {
configKey: string;
configValue: string;
}
async function getPublicConfigs(): Promise<Record<string, string>> {
try {
const response = await getPublicConfig();
+1 -3
View File
@@ -7,7 +7,6 @@ import gsap from "gsap";
import {
Fish,
Heart,
Clock,
Lightbulb,
Sparkle,
Bug,
@@ -164,7 +163,7 @@ const FeedbackCard = ({ fb, onLike, dbTypes }: { fb: PondFeedback; onLike: (id:
};
}, []);
const handleLocalLike = (e: React.MouseEvent) => {
const handleLocalLike = () => {
if (liked) return;
setLiked(true);
onLike(fb.id);
@@ -521,7 +520,6 @@ export default function PondPage() {
useEffect(() => {
fetchFeedbacks(true);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activePool]);
// 水面心情融合流体背景 GSAP 缓动逻辑
+31 -4
View File
@@ -30,10 +30,21 @@ export default function PostPage() {
const res = response.data;
if (res && res.code === 200) {
const item = res.data;
let formattedDate = new Date().toISOString().split("T")[0];
if (item.createTime) {
if (item.createTime.includes("T")) {
formattedDate = item.createTime.split("T")[0];
} else if (item.createTime.includes(" ")) {
formattedDate = item.createTime.split(" ")[0];
} else {
formattedDate = item.createTime;
}
}
const formatted: Post = {
slug: item.slug || `post-${item.id}`,
title: item.title,
date: item.createTime ? item.createTime.split("T")[0] : new Date().toISOString().split("T")[0],
date: formattedDate,
category: item.category || "Thoughts",
mood: item.mood || "quiet",
visibility: (item.visibility as any) || "public",
@@ -46,6 +57,7 @@ export default function PostPage() {
throw new Error("Post not found in API");
}
} catch (err) {
console.error("Detail page fetch error detail:", err);
console.warn("Detail page: API unavailable, using local writingData static fallback.", err);
const local = writingData.find((p) => p.slug === slug);
setPost(local || null);
@@ -56,6 +68,15 @@ export default function PostPage() {
fetchPost();
}, [slug]);
// 种子为 42 的伪随机发生器 (Linear Congruential Generator)
const seededRandom = (seed: number) => {
let s = seed;
return () => {
s = (s * 9301 + 49297) % 233280;
return s / 233280;
};
};
// 解析并生成大纲 (TOC)
useEffect(() => {
if (!post || (post.visibility === "private" && !unlocked)) return;
@@ -65,7 +86,7 @@ export default function PostPage() {
const items: { id: string; text: string; level: number }[] = [];
headings.forEach((heading) => {
const id = heading.id;
if (id && id.startsWith("heading-")) {
if (id) {
const text = heading.textContent || "";
const level = parseInt(heading.tagName.substring(1), 10);
items.push({ id, text, level });
@@ -106,11 +127,17 @@ export default function PostPage() {
return () => window.removeEventListener("scroll", handleScroll);
}, [toc]);
// 挑选当前文章之外的 3 篇推荐文章
// 使用 seed = 42 进行伪随机算法推荐 3 篇文章
useEffect(() => {
if (!post) return;
const filtered = writingData.filter((p) => p.slug !== slug);
setRecommendations(filtered.slice(0, 3));
const rng = seededRandom(42);
const shuffled = [...filtered];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(rng() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
setRecommendations(shuffled.slice(0, 3));
}, [post, slug]);
if (loading) {
-2
View File
@@ -3,7 +3,6 @@
import { useState, useEffect, useRef } from "react";
import { Search, Lock, ArrowRight, ArrowLeft, Calendar, Tag, Smile } from "lucide-react";
import Link from "next/link";
import { writingData } from "@/data/writing";
import { useArticles } from "@/hooks/useArticles";
import Image from "next/image";
import gsap from "gsap";
@@ -346,4 +345,3 @@ export default function WritingPage() {
</div>
);
}
+8 -1
View File
@@ -197,7 +197,14 @@ export default function Navbar() {
{/* Logo 标志性小图标 */}
{logoUrl ? (
<span className="logo-a-icon relative flex h-5 w-5 items-center justify-center overflow-hidden rounded bg-transparent">
<img src={logoUrl} alt="Logo" className="w-full h-full object-contain" />
<Image
src={logoUrl}
alt="Logo"
fill
sizes="20px"
unoptimized
className="object-contain"
/>
</span>
) : (
<span className="logo-a-icon relative flex h-5 w-5 items-center justify-center overflow-hidden rounded bg-charcoal text-cream dark:bg-cream dark:text-charcoal transition-colors">
@@ -28,10 +28,9 @@ const defaultMetas: AchievementMeta[] = [
interface AchievementsPageClientProps {
initialItems: Achievement[];
initialMetas: AchievementMeta[];
configs: Record<string, string>;
}
export default function AchievementsPageClient({ initialItems, initialMetas, configs }: AchievementsPageClientProps) {
export default function AchievementsPageClient({ initialItems, initialMetas }: AchievementsPageClientProps) {
const [activeFilter, setActiveFilter] = useState<string>("all");
const [activeAchievement, setActiveAchievement] = useState<Achievement | null>(null);
const [items, setItems] = useState<Achievement[]>(initialItems);
@@ -1,7 +1,6 @@
"use client";
import React, { useRef, useEffect } from "react";
import Image from "next/image";
import { GraduationCap, Briefcase, Trophy, Medal, Heart, BookOpen } from "lucide-react";
import gsap from "gsap";
@@ -2,7 +2,7 @@
import { useEffect, useRef, useState, useMemo } from "react";
import Image from "next/image";
import { Compass, Calendar, MapPin, Camera, BookOpen, X, Info } from "lucide-react";
import { Compass, Calendar, MapPin, X, Info } from "lucide-react";
import * as Icons from "lucide-react";
import gsap from "gsap";
import { DynamicIcon } from "@/icon/love";
@@ -67,7 +67,7 @@ const resolveMapCredentials = (str: string): string => {
decrypted += String.fromCharCode(charCode);
}
return decrypted;
} catch (e) {
} catch {
return str;
}
}
@@ -76,7 +76,7 @@ const resolveMapCredentials = (str: string): string => {
const payload = str.substring(4);
const shifted = decodeURIComponent(atob(payload));
return shifted.split("").map((c) => String.fromCharCode(c.charCodeAt(0) - 3)).join("");
} catch (e) {
} catch {
return str;
}
}
+2
View File
@@ -122,6 +122,8 @@ export default function GalleryCard({ photo, index, onClick }: GalleryCardProps)
{/* 极轻微的暗角与网格纹理叠加层 */}
<div className="absolute inset-0 bg-radial-vignette opacity-15 pointer-events-none z-10 transition-opacity group-hover:opacity-5" />
{/* Admin-managed images have unknown intrinsic dimensions and may use arbitrary storage origins. */}
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={photo.src}
alt={photo.title}
+2
View File
@@ -72,6 +72,8 @@ export default function Lightbox({ photo, onClose }: LightboxProps) {
className="max-w-full max-h-[50vh] object-contain rounded-xs border border-charcoal/5 dark:border-white/5"
/>
) : (
// Preserve the original intrinsic ratio for arbitrary admin-managed lightbox media.
// eslint-disable-next-line @next/next/no-img-element
<img
src={photo.src}
alt={photo.title}
+6 -2
View File
@@ -1,6 +1,7 @@
"use client";
import { useEffect, useRef } from "react";
import Image from "next/image";
import { BookOpen } from "lucide-react";
import gsap from "gsap";
@@ -126,10 +127,13 @@ export default function ReadingCard({ data }: { data?: ReadingData }) {
{/* 书本封面 (Front Cover) */}
<div className="absolute inset-0 bg-stone-900 border border-zinc-800 rounded-l flex flex-col justify-between overflow-hidden select-none transform translate-z-[1px]">
{coverUrl ? (
<img
<Image
src={coverUrl}
alt={title}
className="w-full h-full object-cover rounded-l animate-fade-in"
fill
sizes="72px"
unoptimized
className="object-cover rounded-l animate-fade-in"
/>
) : (
<div className="absolute inset-0 p-2 flex flex-col justify-between h-full w-full">
+555 -136
View File
@@ -1,29 +1,154 @@
"use client";
import React from "react";
import React, { useState, useEffect } from "react";
import { createPortal } from "react-dom";
import hljs from "highlight.js";
import "highlight.js/styles/github-dark.css";
import {
Copy,
Check,
Info,
Lightbulb,
AlertTriangle,
AlertCircle,
X,
Link as LinkIcon,
Square,
CheckSquare
} from "lucide-react";
// Recursive inline markdown parser for Bold, Italic, Code, and Links
export function parseInline(text: string, offset: number = 0): React.ReactNode[] {
// Types for Callout / Alert
export type CalloutType = "NOTE" | "TIP" | "IMPORTANT" | "WARNING" | "CAUTION";
interface CalloutConfig {
icon: React.ElementType;
title: string;
borderColorClass: string;
bgColorClass: string;
textColorClass: string;
iconColorClass: string;
}
const CALLOUT_MAP: Record<CalloutType, CalloutConfig> = {
NOTE: {
icon: Info,
title: "NOTE",
borderColorClass: "border-sky-500/30 dark:border-sky-400/30",
bgColorClass: "bg-sky-500/10 dark:bg-sky-500/15",
textColorClass: "text-sky-900 dark:text-sky-200",
iconColorClass: "text-sky-600 dark:text-sky-400",
},
TIP: {
icon: Lightbulb,
title: "TIP",
borderColorClass: "border-emerald-500/30 dark:border-emerald-400/30",
bgColorClass: "bg-emerald-500/10 dark:bg-emerald-500/15",
textColorClass: "text-emerald-900 dark:text-emerald-200",
iconColorClass: "text-emerald-600 dark:text-emerald-400",
},
IMPORTANT: {
icon: Info,
title: "IMPORTANT",
borderColorClass: "border-purple-500/30 dark:border-purple-400/30",
bgColorClass: "bg-purple-500/10 dark:bg-purple-500/15",
textColorClass: "text-purple-900 dark:text-purple-200",
iconColorClass: "text-purple-600 dark:text-purple-400",
},
WARNING: {
icon: AlertTriangle,
title: "WARNING",
borderColorClass: "border-amber-500/30 dark:border-amber-400/30",
bgColorClass: "bg-amber-500/10 dark:bg-amber-500/15",
textColorClass: "text-amber-900 dark:text-amber-200",
iconColorClass: "text-amber-600 dark:text-amber-400",
},
CAUTION: {
icon: AlertCircle,
title: "CAUTION",
borderColorClass: "border-rose-500/30 dark:border-rose-400/30",
bgColorClass: "bg-rose-500/10 dark:bg-rose-500/15",
textColorClass: "text-rose-900 dark:text-rose-200",
iconColorClass: "text-rose-600 dark:text-rose-400",
},
};
// Copy button for code blocks with rich micro-interactions
function CopyButton({ code }: { code: string }) {
const [copied, setCopied] = useState(false);
const handleCopy = async (e: React.MouseEvent) => {
e.stopPropagation();
try {
await navigator.clipboard.writeText(code);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch (err) {
console.error("Failed to copy code: ", err);
}
};
return (
<button
type="button"
onClick={handleCopy}
className={`group relative flex items-center gap-1.5 px-3 py-1 text-[11px] font-sans font-medium rounded-lg transition-all duration-300 border backdrop-blur-md cursor-pointer active:scale-95 select-none ${
copied
? "bg-emerald-500/20 text-emerald-300 border-emerald-500/40 shadow-[0_0_12px_rgba(16,185,129,0.25)]"
: "bg-white/[0.06] text-white/70 hover:text-white hover:bg-white/[0.12] border-white/10 hover:border-white/25 shadow-xs"
}`}
title="复制代码到剪贴板"
>
{copied ? (
<>
<Check className="w-3.5 h-3.5 text-emerald-400 animate-in zoom-in-50 duration-200" />
<span className="text-emerald-300 font-semibold tracking-wide">已复制</span>
</>
) : (
<>
<Copy className="w-3.5 h-3.5 text-white/50 group-hover:text-white/90 transition-colors" />
<span className="tracking-wide">复制</span>
</>
)}
</button>
);
}
// Recursive inline markdown parser for Bold, Italic, Strikethrough, Highlight, Kbd, Code, Links, Task checkbox, Images
export function parseInline(text: string, onImageClick?: (url: string, alt: string) => void, offset: number = 0): React.ReactNode[] {
if (!text) return [];
let minIndex = Infinity;
let matchType: "bold" | "italic" | "code" | "link" | "image" | null = null;
let matchType: "image" | "bold" | "italic" | "strike" | "highlight" | "kbd" | "code" | "link" | "task_checked" | "task_unchecked" | null = null;
let matchedString = "";
let matchData: string | { text: string; url: string } | null = null;
let matchData: any = null;
// 0. Image (![alt](url))
// 0. Task Checkboxes ([x] or [ ])
const taskCheckedRegex = /^\[([xX])\]\s+/;
const taskUncheckedRegex = /^\[\s\]\s+/;
const taskCheckedMatch = taskCheckedRegex.exec(text);
if (taskCheckedMatch && taskCheckedMatch.index < minIndex) {
minIndex = taskCheckedMatch.index;
matchType = "task_checked";
matchedString = taskCheckedMatch[0];
}
const taskUncheckedMatch = taskUncheckedRegex.exec(text);
if (taskUncheckedMatch && taskUncheckedMatch.index < minIndex) {
minIndex = taskUncheckedMatch.index;
matchType = "task_unchecked";
matchedString = taskUncheckedMatch[0];
}
// 1. Image (![alt](url))
const imageRegex = /!\[([^\]]*)\]\(([^)]+)\)/;
const imageMatch = imageRegex.exec(text);
if (imageMatch && imageMatch.index < minIndex) {
minIndex = imageMatch.index;
matchType = "image";
matchedString = imageMatch[0];
matchData = { text: imageMatch[1], url: imageMatch[2] };
matchData = { alt: imageMatch[1], url: imageMatch[2] };
}
// 1. Bold (**text**)
// 2. Bold (**text**)
const boldRegex = /\*\*([^*]+)\*\*/;
const boldMatch = boldRegex.exec(text);
if (boldMatch && boldMatch.index < minIndex) {
@@ -33,7 +158,27 @@ export function parseInline(text: string, offset: number = 0): React.ReactNode[]
matchData = boldMatch[1];
}
// 2. Italic (*text*)
// 3. Highlight (==text==)
const highlightRegex = /==([^=]+)==/;
const highlightMatch = highlightRegex.exec(text);
if (highlightMatch && highlightMatch.index < minIndex) {
minIndex = highlightMatch.index;
matchType = "highlight";
matchedString = highlightMatch[0];
matchData = highlightMatch[1];
}
// 4. Strikethrough (~~text~~)
const strikeRegex = /~~([^~]+)~~/;
const strikeMatch = strikeRegex.exec(text);
if (strikeMatch && strikeMatch.index < minIndex) {
minIndex = strikeMatch.index;
matchType = "strike";
matchedString = strikeMatch[0];
matchData = strikeMatch[1];
}
// 5. Italic (*text*)
const italicRegex = /\*([^*]+)\*/;
const italicMatch = italicRegex.exec(text);
if (italicMatch && italicMatch.index < minIndex) {
@@ -43,7 +188,17 @@ export function parseInline(text: string, offset: number = 0): React.ReactNode[]
matchData = italicMatch[1];
}
// 3. Inline Code (`code`)
// 6. Inline Kbd (<kbd>Key</kbd>)
const kbdRegex = /<kbd>([^<]+)<\/kbd>/i;
const kbdMatch = kbdRegex.exec(text);
if (kbdMatch && kbdMatch.index < minIndex) {
minIndex = kbdMatch.index;
matchType = "kbd";
matchedString = kbdMatch[0];
matchData = kbdMatch[1];
}
// 7. Inline Code (`code`)
const codeRegex = /`([^`]+)`/;
const codeMatch = codeRegex.exec(text);
if (codeMatch && codeMatch.index < minIndex) {
@@ -53,7 +208,7 @@ export function parseInline(text: string, offset: number = 0): React.ReactNode[]
matchData = codeMatch[1];
}
// 4. Link ([text](url))
// 8. Link ([text](url))
const linkRegex = /\[([^\]]+)\]\(([^)]+)\)/;
const linkMatch = linkRegex.exec(text);
if (linkMatch && linkMatch.index < minIndex) {
@@ -72,27 +227,61 @@ export function parseInline(text: string, offset: number = 0): React.ReactNode[]
const result: React.ReactNode[] = [];
if (before) {
result.push(...parseInline(before, offset));
result.push(...parseInline(before, onImageClick, offset));
}
const key = `${matchType}-${offset + minIndex}`;
if (matchType === "bold" && typeof matchData === "string") {
if (matchType === "task_checked") {
result.push(
<strong key={key} className="font-bold text-charcoal dark:text-cream">
{parseInline(matchData, offset + minIndex + 2)}
<span key={key} className="inline-flex items-center align-middle mr-2 text-(--accent-color)">
<CheckSquare className="w-4 h-4" />
</span>
);
} else if (matchType === "task_unchecked") {
result.push(
<span key={key} className="inline-flex items-center align-middle mr-2 text-(--fg-color)/40">
<Square className="w-4 h-4" />
</span>
);
} else if (matchType === "bold" && typeof matchData === "string") {
result.push(
<strong key={key} className="font-bold text-(--fg-color)">
{parseInline(matchData, onImageClick, offset + minIndex + 2)}
</strong>
);
} else if (matchType === "italic" && typeof matchData === "string") {
result.push(
<em key={key} className="italic text-charcoal/90 dark:text-cream/90">
{parseInline(matchData, offset + minIndex + 1)}
<em key={key} className="italic text-(--fg-color)/90 font-serif">
{parseInline(matchData, onImageClick, offset + minIndex + 1)}
</em>
);
} else if (matchType === "strike" && typeof matchData === "string") {
result.push(
<del key={key} className="line-through text-(--fg-color)/50">
{parseInline(matchData, onImageClick, offset + minIndex + 2)}
</del>
);
} else if (matchType === "highlight" && typeof matchData === "string") {
result.push(
<mark key={key} className="bg-(--accent-color)/20 text-(--fg-color) px-1.5 py-0.5 rounded font-medium border-b-2 border-(--accent-color)/40">
{parseInline(matchData, onImageClick, offset + minIndex + 2)}
</mark>
);
} else if (matchType === "kbd" && typeof matchData === "string") {
result.push(
<kbd
key={key}
className="px-2 py-1 text-xs font-mono text-(--fg-color)/90 bg-(--bg-dark-color)/80 rounded-md border border-(--border-line-color) shadow-[0_2px_0_rgba(0,0,0,0.15)] dark:shadow-[0_2px_0_rgba(255,255,255,0.08)] inline-block mx-0.5"
>
{matchData}
</kbd>
);
} else if (matchType === "code" && typeof matchData === "string") {
result.push(
<code
key={key}
className="px-1.5 py-0.5 font-mono text-[0.8em] text-rose-600 bg-rose-500/10 dark:text-rose-400 dark:bg-rose-950/20 rounded border border-rose-500/20 dark:border-rose-900/50"
className="px-1.5 py-0.5 font-mono text-[0.85em] text-(--accent-color) bg-(--accent-color)/10 rounded border border-(--accent-color)/20 font-medium"
>
{matchData}
</code>
@@ -104,31 +293,46 @@ export function parseInline(text: string, offset: number = 0): React.ReactNode[]
href={matchData.url}
target="_blank"
rel="noopener noreferrer"
className="text-gold hover:underline border-b border-gold/20 pb-0.5 transition-all font-sans text-[0.95em]"
className="text-(--accent-color) hover:text-(--accent-light-color) underline underline-offset-4 decoration-(--accent-color)/30 hover:decoration-(--accent-color) transition-colors font-sans font-medium text-[0.95em] inline-inline-flex items-center gap-0.5"
>
{parseInline(matchData.text, offset + minIndex + 1)}
{parseInline(matchData.text, onImageClick, offset + minIndex + 1)}
</a>
);
} else if (matchType === "image" && matchData && typeof matchData === "object" && "text" in matchData) {
} else if (matchType === "image" && matchData && typeof matchData === "object" && "url" in matchData) {
const { url, alt } = matchData;
result.push(
<span key={key} className="block my-6 overflow-hidden rounded-2xl border border-charcoal/10 dark:border-white/10 bg-charcoal/5 dark:bg-white/5">
<img
src={matchData.url}
alt={matchData.text}
className="w-full h-auto max-h-[500px] object-cover hover:scale-[1.01] transition-transform duration-500"
loading="lazy"
/>
{matchData.text && (
<span className="block text-center text-xs tone-muted py-2.5 border-t border-charcoal/5 dark:border-white/5 bg-charcoal/[0.02] dark:bg-white/[0.01] font-sans">
{matchData.text}
</span>
<figure
key={key}
className="group relative my-8 overflow-hidden rounded-2xl border border-(--border-line-color) bg-(--bg-dark-color)/40 p-2 sm:p-3 transition-all duration-300 hover:shadow-xl"
>
<div
className="relative overflow-hidden rounded-xl cursor-zoom-in"
onClick={() => onImageClick?.(url, alt)}
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={url}
alt={alt || "Article Image"}
className="w-full h-auto max-h-[550px] object-cover rounded-xl group-hover:scale-[1.015] transition-transform duration-500 ease-out"
loading="lazy"
/>
<div className="absolute inset-0 bg-black/0 group-hover:bg-black/10 transition-colors duration-300 flex items-center justify-center opacity-0 group-hover:opacity-100">
<span className="px-3 py-1.5 bg-black/60 backdrop-blur-md text-white text-xs font-sans rounded-full shadow-lg flex items-center gap-1.5 border border-white/20">
点击放大预览
</span>
</div>
</div>
{alt && (
<figcaption className="text-center text-xs text-(--fg-color)/60 pt-3 pb-1 font-sans tracking-wide">
{alt}
</figcaption>
)}
</span>
</figure>
);
}
if (after) {
result.push(...parseInline(after, offset + minIndex + matchedString.length));
result.push(...parseInline(after, onImageClick, offset + minIndex + matchedString.length));
}
return result;
@@ -142,12 +346,12 @@ function parseTableLine(line: string): string[] {
if (trimmed.endsWith("|")) {
trimmed = trimmed.slice(0, -1);
}
return trimmed.split("|").map(cell => cell.trim());
return trimmed.split("|").map((cell) => cell.trim());
}
function parseTableAligns(line: string): ("left" | "center" | "right")[] {
const parts = parseTableLine(line);
return parts.map(part => {
return parts.map((part) => {
const trimmed = part.trim();
const left = trimmed.startsWith(":");
const right = trimmed.endsWith(":");
@@ -157,11 +361,26 @@ function parseTableAligns(line: string): ("left" | "center" | "right")[] {
});
}
interface Block {
type: "h1" | "h2" | "h3" | "h4" | "paragraph" | "blockquote" | "ul" | "ol" | "code" | "table";
export interface Block {
type:
| "h1"
| "h2"
| "h3"
| "h4"
| "h5"
| "h6"
| "paragraph"
| "blockquote"
| "callout"
| "ul"
| "ol"
| "code"
| "table"
| "hr";
content?: string;
lines?: string[];
lang?: string;
calloutType?: CalloutType;
tableData?: {
headers: string[];
aligns: ("left" | "center" | "right")[];
@@ -185,15 +404,14 @@ export function parseBlocks(content: string): Block[] {
currentBlock.tableData!.rows.push(row);
continue;
} else {
// Table ends
blocks.push(currentBlock);
currentBlock = null;
i--; // re-process current line
i--; // re-process line
continue;
}
}
// 0.5. Check Table Start
// 0.5. Table Start Check
if (line.includes("|") && i + 1 < lines.length) {
const nextLine = lines[i + 1];
const tableDividerRegex = /^\s*\|?\s*(:?-+:?)\s*(\|\s*(:?-+:?)\s*)*\|?\s*$/;
@@ -208,10 +426,10 @@ export function parseBlocks(content: string): Block[] {
tableData: {
headers,
aligns,
rows: []
}
rows: [],
},
};
i++; // skip divider line
i++; // skip divider
continue;
}
}
@@ -219,11 +437,9 @@ export function parseBlocks(content: string): Block[] {
// 1. Code Block (```lang)
if (trimmed.startsWith("```")) {
if (currentBlock && currentBlock.type === "code") {
// End of code block
blocks.push(currentBlock);
currentBlock = null;
} else {
// Start of code block
if (currentBlock) {
blocks.push(currentBlock);
}
@@ -238,7 +454,49 @@ export function parseBlocks(content: string): Block[] {
continue;
}
// 2. Unordered List (- or *)
// 2. Horizontal Rule (---, ***, ___)
if (/^(---|[*]{3,}|_{3,})$/.test(trimmed)) {
if (currentBlock) {
blocks.push(currentBlock);
currentBlock = null;
}
blocks.push({ type: "hr" });
continue;
}
// 3. Callout / Blockquote (>)
if (trimmed.startsWith(">")) {
const quoteContent = line.replace(/^\s*>\s?/, "");
// Check if this is the start of a Callout: > [!NOTE] etc.
const calloutMatch = quoteContent.match(/^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]/i);
if (calloutMatch) {
if (currentBlock) {
blocks.push(currentBlock);
}
const calloutType = calloutMatch[1].toUpperCase() as CalloutType;
const remainingText = quoteContent.replace(/^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*/i, "");
currentBlock = {
type: "callout",
calloutType,
lines: remainingText ? [remainingText] : [],
};
continue;
}
if (currentBlock && (currentBlock.type === "blockquote" || currentBlock.type === "callout")) {
currentBlock.lines!.push(quoteContent);
} else {
if (currentBlock) {
blocks.push(currentBlock);
}
currentBlock = { type: "blockquote", lines: [quoteContent] };
}
continue;
}
// 4. Unordered List (- or * or +)
const ulMatch = line.match(/^(\s*)([-*+])\s+(.*)$/);
if (ulMatch) {
const itemContent = ulMatch[3];
@@ -253,7 +511,7 @@ export function parseBlocks(content: string): Block[] {
continue;
}
// 3. Ordered List (1., 2.)
// 5. Ordered List (1., 2.)
const olMatch = line.match(/^(\s*)(\d+)\.\s+(.*)$/);
if (olMatch) {
const itemContent = olMatch[3];
@@ -268,42 +526,29 @@ export function parseBlocks(content: string): Block[] {
continue;
}
// 4. Blockquote (>)
if (trimmed.startsWith(">")) {
const quoteContent = line.replace(/^\s*>\s?/, "");
if (currentBlock && currentBlock.type === "blockquote") {
currentBlock.lines!.push(quoteContent);
} else {
if (currentBlock) {
blocks.push(currentBlock);
}
currentBlock = { type: "blockquote", lines: [quoteContent] };
}
continue;
}
// 5. Headings
// 6. Headings (# H1 ~ ###### H6)
if (trimmed.startsWith("#")) {
const hMatch = trimmed.match(/^(#{1,4})\s+(.*)$/);
const hMatch = trimmed.match(/^(#{1,6})\s+(.*)$/);
if (hMatch) {
if (currentBlock) {
blocks.push(currentBlock);
}
const level = hMatch[1].length;
const hContent = hMatch[2];
const hType = level === 1 ? "h1" : level === 2 ? "h2" : level === 3 ? "h3" : "h4";
const hType = `h${level}` as "h1" | "h2" | "h3" | "h4" | "h5" | "h6";
blocks.push({ type: hType, content: hContent });
currentBlock = null;
continue;
}
}
// 6. Blank line
// 7. Blank Line
if (trimmed === "") {
if (currentBlock) {
if (
currentBlock.type === "paragraph" ||
currentBlock.type === "blockquote" ||
currentBlock.type === "callout" ||
currentBlock.type === "ul" ||
currentBlock.type === "ol"
) {
@@ -314,7 +559,7 @@ export function parseBlocks(content: string): Block[] {
continue;
}
// 7. Paragraph
// 8. Paragraph
if (currentBlock && currentBlock.type === "paragraph") {
currentBlock.lines!.push(line);
} else {
@@ -332,41 +577,126 @@ export function parseBlocks(content: string): Block[] {
return blocks;
}
// Image Lightbox Modal using React Portal
function ImageLightbox({
src,
alt,
onClose,
}: {
src: string;
alt: string;
onClose: () => void;
}) {
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
// Lock background scroll when Lightbox is open
const originalStyle = document.body.style.overflow;
document.body.style.overflow = "hidden";
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
window.addEventListener("keydown", handleKeyDown);
return () => {
document.body.style.overflow = originalStyle;
window.removeEventListener("keydown", handleKeyDown);
};
}, [onClose]);
if (!mounted || typeof document === "undefined") return null;
return createPortal(
<div
className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/85 backdrop-blur-md p-4 sm:p-8 animate-fadeIn"
onClick={onClose}
>
<button
type="button"
onClick={onClose}
className="absolute top-6 right-6 p-2.5 rounded-full bg-white/15 text-white hover:bg-white/30 transition-colors border border-white/20 cursor-pointer z-[10000] shadow-lg"
title="关闭预览 (Esc)"
>
<X className="w-6 h-6" />
</button>
<div
className="relative max-w-6xl max-h-[90vh] overflow-hidden rounded-2xl border border-white/15 shadow-2xl bg-black/40"
onClick={(e) => e.stopPropagation()}
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={src}
alt={alt}
className="w-full h-auto max-h-[85vh] object-contain rounded-2xl"
/>
{alt && (
<div className="bg-black/80 backdrop-blur-md text-center text-xs sm:text-sm text-white/90 py-3 px-4 font-sans border-t border-white/10">
{alt}
</div>
)}
</div>
</div>,
document.body
);
}
export default function Markdown({ content }: { content: string }) {
const [activeImage, setActiveImage] = useState<{ url: string; alt: string } | null>(null);
const blocks = parseBlocks(content);
const handleImageClick = (url: string, alt: string) => {
setActiveImage({ url, alt });
};
return (
<div className="space-y-6">
<div className="space-y-6 text-(--fg-color)">
{blocks.map((block, idx) => {
const key = `${block.type}-${idx}`;
switch (block.type) {
case "hr":
return (
<div key={key} className="relative my-10 flex items-center justify-center">
<div className="absolute inset-0 flex items-center">
<div className="w-full border-t border-(--border-line-color)" />
</div>
<div className="relative bg-(--bg-color) px-4">
<span className="inline-block w-2 h-2 rotate-45 bg-(--accent-color)/40 rounded-[1px]" />
</div>
</div>
);
case "table": {
const data = block.tableData;
if (!data) return null;
return (
<div key={key} className="my-6 overflow-x-auto rounded-2xl border border-charcoal/10 dark:border-white/10 bg-charcoal/[0.02] dark:bg-white/[0.01]">
<table className="w-full border-collapse text-left text-xs md:text-sm font-sans tracking-wide text-charcoal/80 dark:text-cream/80">
<div
key={key}
className="my-8 overflow-x-auto rounded-2xl border border-(--border-line-color) bg-(--bg-dark-color)/30 shadow-sm"
>
<table className="w-full border-collapse text-left text-xs md:text-sm font-sans tracking-wide">
<thead>
<tr className="border-b border-charcoal/10 dark:border-white/10 bg-charcoal/5 dark:bg-white/5 text-charcoal dark:text-cream font-medium">
<tr className="border-b border-(--border-line-color) bg-(--accent-color)/10 text-(--fg-color) font-semibold">
{data.headers.map((header, i) => {
const align = data.aligns[i] || "left";
return (
<th
key={i}
style={{ textAlign: align }}
className="px-4 py-3 font-semibold text-[0.9em] uppercase tracking-wider"
className="px-4 py-3.5 uppercase tracking-wider text-[0.85em] text-(--accent-color)"
>
{parseInline(header)}
{parseInline(header, handleImageClick)}
</th>
);
})}
</tr>
</thead>
<tbody className="divide-y divide-charcoal/5 dark:divide-white/5">
<tbody className="divide-y divide-(--border-line-color)">
{data.rows.map((row, rIdx) => (
<tr
key={rIdx}
className="hover:bg-charcoal/[0.04] dark:hover:bg-white/[0.02] transition-colors"
className="hover:bg-(--accent-color)/5 transition-colors"
>
{row.map((cell, cIdx) => {
const align = data.aligns[cIdx] || "left";
@@ -374,9 +704,9 @@ export default function Markdown({ content }: { content: string }) {
<td
key={cIdx}
style={{ textAlign: align }}
className="px-4 py-3 leading-relaxed"
className="px-4 py-3 leading-relaxed text-(--fg-color)/85"
>
{parseInline(cell)}
{parseInline(cell, handleImageClick)}
</td>
);
})}
@@ -387,95 +717,171 @@ export default function Markdown({ content }: { content: string }) {
</div>
);
}
case "h1":
return (
<h1
key={key}
id={`heading-${idx}`}
className="font-serif text-2xl md:text-3xl font-light text-charcoal dark:text-cream mt-10 mb-4 border-b border-charcoal/10 dark:border-white/10 pb-2.5 tracking-wide leading-snug"
>
{parseInline(block.content || "")}
</h1>
);
case "h2":
return (
<h2
key={key}
id={`heading-${idx}`}
className="font-serif text-xl md:text-2xl font-light text-charcoal dark:text-cream mt-8 mb-4 border-b border-charcoal/5 dark:border-white/5 pb-1.5 tracking-wide leading-snug"
>
{parseInline(block.content || "")}
</h2>
);
case "h3":
return (
<h3
key={key}
id={`heading-${idx}`}
className="font-serif text-lg md:text-xl font-light text-charcoal dark:text-cream mt-6 mb-3 tracking-wide"
>
{parseInline(block.content || "")}
</h3>
);
case "h4":
case "h5":
case "h6": {
const textContent = block.content || "";
const slug = textContent
.toLowerCase()
.replace(/[^\w\u4e00-\u9fa5]+/g, "-")
.replace(/^-+|-+$/g, "");
const headingId = slug || `heading-${idx}`;
const baseHeadingClasses =
"group relative font-serif text-(--fg-color) tracking-wide leading-snug font-normal flex items-center gap-2.5";
if (block.type === "h1") {
return (
<h1
key={key}
id={headingId}
className={`${baseHeadingClasses} text-2xl md:text-3xl mt-12 mb-5 pb-3 border-b border-(--border-line-color)`}
>
<span className="w-1.5 h-6 rounded-full bg-(--accent-color) shrink-0" />
<span className="flex-1">{parseInline(textContent, handleImageClick)}</span>
<a
href={`#${headingId}`}
className="opacity-0 group-hover:opacity-100 transition-opacity text-(--accent-color)/60 hover:text-(--accent-color) p-1"
title="锚点链接"
>
<LinkIcon className="w-4 h-4" />
</a>
</h1>
);
}
if (block.type === "h2") {
return (
<h2
key={key}
id={headingId}
className={`${baseHeadingClasses} text-xl md:text-2xl mt-10 mb-4 pb-2 border-b border-(--border-line-color)/60`}
>
<span className="w-1.5 h-5 rounded-full bg-(--accent-color)/80 shrink-0" />
<span className="flex-1">{parseInline(textContent, handleImageClick)}</span>
<a
href={`#${headingId}`}
className="opacity-0 group-hover:opacity-100 transition-opacity text-(--accent-color)/60 hover:text-(--accent-color) p-1"
title="锚点链接"
>
<LinkIcon className="w-4 h-4" />
</a>
</h2>
);
}
if (block.type === "h3") {
return (
<h3
key={key}
id={headingId}
className={`${baseHeadingClasses} text-lg md:text-xl mt-8 mb-3`}
>
<span className="w-2 h-2 rounded-full bg-(--accent-color) shrink-0" />
<span className="flex-1">{parseInline(textContent, handleImageClick)}</span>
<a
href={`#${headingId}`}
className="opacity-0 group-hover:opacity-100 transition-opacity text-(--accent-color)/60 hover:text-(--accent-color) p-1"
title="锚点链接"
>
<LinkIcon className="w-3.5 h-3.5" />
</a>
</h3>
);
}
return (
<h4
key={key}
id={`heading-${idx}`}
className="font-serif text-base md:text-lg font-light text-charcoal dark:text-cream mt-4 mb-2 tracking-wide"
id={headingId}
className={`${baseHeadingClasses} text-base md:text-lg mt-6 mb-2 text-(--fg-color)/90`}
>
{parseInline(block.content || "")}
<span className="flex-1">{parseInline(textContent, handleImageClick)}</span>
</h4>
);
}
case "callout": {
const calloutType = block.calloutType || "NOTE";
const config = CALLOUT_MAP[calloutType];
const Icon = config.icon;
const calloutText = block.lines ? block.lines.join(" ") : "";
return (
<div
key={key}
className={`my-6 rounded-2xl border ${config.borderColorClass} ${config.bgColorClass} p-4.5 sm:p-5 shadow-sm transition-all`}
>
<div className="flex items-center gap-2.5 mb-2 font-sans font-semibold text-xs tracking-wider uppercase">
<Icon className={`w-4 h-4 ${config.iconColorClass}`} />
<span className={config.textColorClass}>{config.title}</span>
</div>
<div className={`font-serif text-sm md:text-base leading-relaxed ${config.textColorClass} opacity-95`}>
{parseInline(calloutText, handleImageClick)}
</div>
</div>
);
}
case "blockquote": {
const quoteText = block.lines ? block.lines.join(" ") : "";
return (
<blockquote
key={key}
className="font-serif italic text-base md:text-lg text-(--fg-color)/80 pl-5 border-l-4 border-(--accent-color) bg-(--accent-color)/5 px-5 py-3.5 rounded-r-2xl my-6 leading-relaxed shadow-xs"
>
{parseInline(quoteText, handleImageClick)}
</blockquote>
);
}
case "paragraph": {
const text = block.lines ? block.lines.join(" ") : "";
return (
<p
key={key}
className="text-justify leading-loose text-charcoal/85 dark:text-cream/85 text-sm md:text-base font-serif tracking-wide"
className="text-justify leading-loose text-(--fg-color)/85 text-base font-serif tracking-wide"
>
{parseInline(text)}
{parseInline(text, handleImageClick)}
</p>
);
}
case "blockquote": {
const text = block.lines ? block.lines.join(" ") : "";
return (
<blockquote
key={key}
className="font-serif italic text-base md:text-lg text-charcoal/70 dark:text-cream/70 pl-6 border-l-4 border-gold bg-gold/5 dark:bg-gold/10 px-6 py-4 rounded-r-2xl my-6 leading-relaxed shadow-sm"
>
{parseInline(text)}
</blockquote>
);
}
case "ul":
return (
<ul
key={key}
className="list-none pl-4 space-y-2.5 text-xs md:text-sm font-sans tracking-wider text-charcoal/75 dark:text-cream/75 my-6 bg-charcoal/5 dark:bg-white/5 p-6 rounded-2xl border border-charcoal/5 dark:border-white/5"
className="list-none pl-2 space-y-2.5 text-sm md:text-base font-serif tracking-wide text-(--fg-color)/85 my-6 bg-(--bg-dark-color)/30 p-5 rounded-2xl border border-(--border-line-color)"
>
{block.lines?.map((line, i) => (
<li key={i} className="flex items-start gap-2.5">
<span className="text-gold mt-1.5 inline-block w-1.5 h-1.5 shrink-0 rounded-full bg-gold" />
<span className="leading-relaxed">{parseInline(line)}</span>
</li>
))}
{block.lines?.map((line, i) => {
const isTask = /^\[([ xX])\]/.test(line.trim());
return (
<li key={i} className="flex items-start gap-2.5">
{!isTask && (
<span className="mt-2.5 inline-block w-1.5 h-1.5 shrink-0 rounded-full bg-(--accent-color)" />
)}
<span className="leading-relaxed flex-1">{parseInline(line, handleImageClick)}</span>
</li>
);
})}
</ul>
);
case "ol":
return (
<ol
key={key}
className="list-decimal pl-6 space-y-2.5 text-xs md:text-sm font-sans tracking-wider text-charcoal/75 dark:text-cream/75 my-6 bg-charcoal/5 dark:bg-white/5 p-6 rounded-2xl border border-charcoal/5 dark:border-white/5"
className="list-decimal pl-6 space-y-2.5 text-sm md:text-base font-serif tracking-wide text-(--fg-color)/85 my-6 bg-(--bg-dark-color)/30 p-5 rounded-2xl border border-(--border-line-color)"
>
{block.lines?.map((line, i) => (
<li key={i} className="pl-1 leading-relaxed">
<span>{parseInline(line)}</span>
<span>{parseInline(line, handleImageClick)}</span>
</li>
))}
</ol>
);
case "code": {
const codeText = block.lines ? block.lines.join("\n") : "";
const lang = block.lang;
@@ -493,29 +899,42 @@ export default function Markdown({ content }: { content: string }) {
return (
<div
key={key}
className="my-6 rounded-2xl overflow-hidden border border-charcoal/10 dark:border-white/10 bg-[#0d1117] shadow-xl font-mono text-xs"
className="my-8 rounded-2xl overflow-hidden border border-white/10 bg-[#0d1117] shadow-xl font-mono text-xs md:text-sm"
>
{/* Mac 风格三色窗口控制栏 */}
<div className="flex items-center justify-between px-4 py-3 bg-[#161b22] border-b border-charcoal/5 dark:border-white/5">
{/* Mac Terminal Topbar */}
<div className="flex items-center justify-between px-4 py-3 bg-[#161b22] border-b border-white/10 select-none">
<div className="flex items-center gap-2">
<span className="w-3 h-3 rounded-full bg-[#ff5f56] border border-[#e0443e] inline-block shrink-0" />
<span className="w-3 h-3 rounded-full bg-[#ffbd2e] border border-[#dab12d] inline-block shrink-0" />
<span className="w-3 h-3 rounded-full bg-[#27c93f] border border-[#1a9c2b] inline-block shrink-0" />
</div>
<span className="text-[10px] font-sans font-medium uppercase tracking-widest text-charcoal/50 dark:text-cream/50">
{block.lang || "code"}
</span>
<div className="flex items-center gap-3">
<span className="text-[11px] font-sans font-medium uppercase tracking-widest text-white/50 bg-white/5 px-2 py-0.5 rounded border border-white/10">
{block.lang || "code"}
</span>
<CopyButton code={codeText} />
</div>
</div>
<pre className="p-4 overflow-x-auto text-[#e6edf3] leading-relaxed font-mono bg-[#0d1117]">
<pre className="p-4 sm:p-5 overflow-x-auto text-[#e6edf3] leading-relaxed font-mono bg-[#0d1117]">
<code dangerouslySetInnerHTML={{ __html: highlightedCode }} />
</pre>
</div>
);
}
default:
return null;
}
})}
{/* Lightbox Modal */}
{activeImage && (
<ImageLightbox
src={activeImage.url}
alt={activeImage.alt}
onClose={() => setActiveImage(null)}
/>
)}
</div>
);
}
-2
View File
@@ -1,6 +1,4 @@
"use client";
/* eslint-disable react-hooks/set-state-in-effect */
/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable @typescript-eslint/no-unused-vars */
import React, { useState, useEffect, useRef } from "react";
+60 -19
View File
@@ -144,40 +144,81 @@ export const writingData: Post[] = [
visibility: "public",
cover: "/assets/writing-camera.png",
description: "这是一篇专门用来测试自定义 Markdown 渲染引擎排版与样式的测试文章。涵盖了标题、列表、引用、代码块以及行内标记等元素。",
content: `# 自定义 Markdown 引擎测试
content: `# Markdown 渲染引擎测试与排版全集
这是一个段落,包含 **粗体字**,*斜体字*,以及一个 [指向 GitHub](https://github.com) 的超链接。同时也可以包含 \`const test = "inline code"\` 这样的行内代码标记。
这是一篇专门用来验证 Markdown 渲染引擎排版、调色与交互体验的测试文章。文章包含了行内样式 **粗体字**、*斜体字*、~~删除线~~、==文本高亮==、按键提示 <kbd>Cmd</kbd> + <kbd>K</kbd> 以及 [个人档案馆](https://github.com) 外部链接。
这里测试一个无序列表:
- 这是一个包含 **加粗文本** 的列表项
- 这是第二个列表项,包含一个 [链接](https://google.com)
- 这是一个简单的列表项
---
接下来是一个有序列表:
1. 第一项:初始化个人生活档案馆
2. 第二项:编写零依赖 Markdown 解析器
3. 第三项:验证样式与系统性能
## 一、Alert 与 Callout 提示卡片测试
> 这里是一个引用块测试。
> 胶片的温度在于银盐的颗粒感,而数字文字的温度,则在于那些被记录下来的微小日常。—— 生活档案馆
> [!NOTE]
> 这是一个 **NOTE** 提示块。常用于提供背景补充信息或相关说明。
下面是代码块测试:
> [!TIP]
> 这是一个 **TIP** 技巧提示块。可以放置提高效率的小技巧或最佳实践。
> [!IMPORTANT]
> 这是一个 **IMPORTANT** 重要提示块。包含关键流程或容易遗漏的要点。
> [!WARNING]
> 这是一个 **WARNING** 警告提示块。提醒使用者注意可能的副作用或注意事项。
> [!CAUTION]
> 这是一个 **CAUTION** 危险/严禁提示块。高风险操作请务必仔细确认!
---
## 二、普通引用与任务列表
> 胶片的温度在于银盐的颗粒感,而数字文字的温度,则在于那些被记录下来的微小日常。
> —— *生活档案馆·Rrtiamo*
这里是系统运维与架构任务清单:
- [x] 重构 Markdown 渲染引擎,完美适配主题色
- [x] 支持各种 Callout 警示框与图片 Lightbox 模态框
- [x] 优化代码终端顶栏与一键复制功能
- [ ] 增加更多图文混排视觉组件
---
## 三、数据表格展示
| 功能特性 | 解析支持 | 样式匹配 | 交互扩展 |
| :--- | :---: | :---: | ---: |
| 标题与锚点 | 支持 H1-H6 | 暖色饰条点缀 | 悬停锚点图标 |
| 提示框 (Callouts) | NOTE/TIP/WARNING等 | 5色主题适调 | 专属 Lucide 图标 |
| 代码终端 | 高亮 (hljs) | Mac 三色卡片 | 一键复制代码 |
| 高清大图 | 胶片外框说明 | 悬停遮罩 hover | 弹出 Lightbox 预览 |
---
## 四、代码终端与复制功能
\`\`\`typescript
interface Post {
slug: string;
title: string;
category: string;
content: string;
}
const renderMarkdown = (post: Post) => {
console.log("Rendering post:", post.title);
return \`Rendering \${post.slug}...\`;
};
// 渲染流程示例函数
export function renderPost(post: Post): string {
console.log(\`Rendering post: \${post.title}\`);
return \`<article class="markdown-body">\${post.content}</article>\`;
}
\`\`\`
## 小结
---
如果所有区块如标题、列表、引用和代码块都排版美观、字体易读、且代码块显示为精致的深色终端样式,则说明渲染引擎表现符合预期。`
## 五、胶片影像与 Lightbox 放大
![生活档案馆·摄影记录](/assets/writing-camera.png)
## 六、小结
如果标题左侧带有暖色饰条、警示框色彩柔和且带有对应图标、代码块能够一键复制、图片点击可以弹出半透明全屏大图预览,则说明渲染引擎升级圆满完成!`
}
];
-1
View File
@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { useState, useEffect } from "react";
import { Post, writingData } from "@/data/writing";
import { getBlogsList } from "@/api/blogs";
-1
View File
@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { useState, useEffect } from "react";
import { GalleryPhoto, galleryData } from "@/data/gallery";
import { getGalleryList } from "@/api/gallery";
+3 -5
View File
@@ -1,4 +1,5 @@
import { useState, useEffect } from "react";
import { getPublicConfig } from "@/api/config";
export interface SysConfig {
configKey: string;
@@ -10,11 +11,8 @@ export function useSysConfig() {
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch("http://localhost:8080/api/config/public")
.then((res) => {
if (!res.ok) throw new Error("HTTP status " + res.status);
return res.json();
})
getPublicConfig()
.then((res) => res.data)
.then((data) => {
if (data.code === 200) {
setConfigs(data.data || []);