diff --git a/.env.development b/.env.development new file mode 100644 index 0000000..29d85a3 --- /dev/null +++ b/.env.development @@ -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 diff --git a/.env.production b/.env.production new file mode 100644 index 0000000..e8faefb --- /dev/null +++ b/.env.production @@ -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 diff --git a/.gitignore b/.gitignore index 60a250e..97633ff 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,8 @@ out/ .DS_Store *.log .env* +!.env.development +!.env.production .pnp .pnp.* .yarn/* diff --git a/README.md b/README.md new file mode 100644 index 0000000..bb87543 --- /dev/null +++ b/README.md @@ -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) + +## 项目预览 + + + +
+
+ 📷 截图占位 · 首页桌面端 +
+ 建议尺寸:1600 × 900 +


+
+ + + +
+
+ 📱 截图占位 · 首页移动端 +
+ 建议尺寸:390 × 844 +


+
+ +## 三端组成 + +| 项目 | 职责 | 仓库 | +| --- | --- | --- | +| 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` 前,代码默认保留全部权利。 diff --git a/next-env.d.ts b/next-env.d.ts index c4b7818..9edff1c 100644 --- a/next-env.d.ts +++ b/next-env.d.ts @@ -1,6 +1,6 @@ /// /// -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. diff --git a/next.config.ts b/next.config.ts index bceaa64..d441857 100644 --- a/next.config.ts +++ b/next.config.ts @@ -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: [ diff --git a/src/api/config.ts b/src/api/config.ts index 9b93872..942223a 100644 --- a/src/api/config.ts +++ b/src/api/config.ts @@ -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[1]) { + const response = await fetch(getServerApiURL('/config/public'), init) + return response.json() +} diff --git a/src/api/request.ts b/src/api/request.ts index cee5092..5a570af 100644 --- a/src/api/request.ts +++ b/src/api/request.ts @@ -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, }) diff --git a/src/app/achievements/page.tsx b/src/app/achievements/page.tsx index 99885bb..e010bea 100644 --- a/src/app/achievements/page.tsx +++ b/src/app/achievements/page.tsx @@ -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 { return []; } -async function getPublicConfigs(): Promise> { - try { - const res = await getPublicConfig(); - const data = res.data; - if (data && data.code === 200 && Array.isArray(data.data)) { - const configMap: Record = {}; - 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 ( ); } diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 64e7dba..914d3d4 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -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 { 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) { diff --git a/src/app/love/page.tsx b/src/app/love/page.tsx index 4b8c240..702a7be 100644 --- a/src/app/love/page.tsx +++ b/src/app/love/page.tsx @@ -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> { try { const response = await getPublicConfig(); diff --git a/src/app/pond/page.tsx b/src/app/pond/page.tsx index bbd889d..c739df0 100644 --- a/src/app/pond/page.tsx +++ b/src/app/pond/page.tsx @@ -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 缓动逻辑 diff --git a/src/app/writing/[slug]/page.tsx b/src/app/writing/[slug]/page.tsx index 0d6dc8c..3db6f41 100644 --- a/src/app/writing/[slug]/page.tsx +++ b/src/app/writing/[slug]/page.tsx @@ -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) { diff --git a/src/app/writing/page.tsx b/src/app/writing/page.tsx index b9b7923..104dca1 100644 --- a/src/app/writing/page.tsx +++ b/src/app/writing/page.tsx @@ -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() { ); } - diff --git a/src/components/Navbar.tsx b/src/components/Navbar.tsx index 44cc08a..56eab4f 100644 --- a/src/components/Navbar.tsx +++ b/src/components/Navbar.tsx @@ -197,7 +197,14 @@ export default function Navbar() { {/* Logo 标志性小图标 */} {logoUrl ? ( - Logo + Logo ) : ( diff --git a/src/components/achievements/AchievementsPageClient.tsx b/src/components/achievements/AchievementsPageClient.tsx index 449655f..0661cf8 100644 --- a/src/components/achievements/AchievementsPageClient.tsx +++ b/src/components/achievements/AchievementsPageClient.tsx @@ -28,10 +28,9 @@ const defaultMetas: AchievementMeta[] = [ interface AchievementsPageClientProps { initialItems: Achievement[]; initialMetas: AchievementMeta[]; - configs: Record; } -export default function AchievementsPageClient({ initialItems, initialMetas, configs }: AchievementsPageClientProps) { +export default function AchievementsPageClient({ initialItems, initialMetas }: AchievementsPageClientProps) { const [activeFilter, setActiveFilter] = useState("all"); const [activeAchievement, setActiveAchievement] = useState(null); const [items, setItems] = useState(initialItems); diff --git a/src/components/achievements/CertificateCard.tsx b/src/components/achievements/CertificateCard.tsx index 59ed640..168af79 100644 --- a/src/components/achievements/CertificateCard.tsx +++ b/src/components/achievements/CertificateCard.tsx @@ -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"; diff --git a/src/components/footprints/FootprintsPageClient.tsx b/src/components/footprints/FootprintsPageClient.tsx index 29776db..a023d71 100644 --- a/src/components/footprints/FootprintsPageClient.tsx +++ b/src/components/footprints/FootprintsPageClient.tsx @@ -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; } } diff --git a/src/components/gallery/GalleryCard.tsx b/src/components/gallery/GalleryCard.tsx index 9e23888..642700c 100644 --- a/src/components/gallery/GalleryCard.tsx +++ b/src/components/gallery/GalleryCard.tsx @@ -122,6 +122,8 @@ export default function GalleryCard({ photo, index, onClick }: GalleryCardProps) {/* 极轻微的暗角与网格纹理叠加层 */}
+ {/* Admin-managed images have unknown intrinsic dimensions and may use arbitrary storage origins. */} + {/* eslint-disable-next-line @next/next/no-img-element */} {photo.title} ) : ( + // Preserve the original intrinsic ratio for arbitrary admin-managed lightbox media. + // eslint-disable-next-line @next/next/no-img-element {photo.title} {coverUrl ? ( - {title} ) : (
diff --git a/src/components/ui/Markdown.tsx b/src/components/ui/Markdown.tsx index 58aad04..bb01b52 100644 --- a/src/components/ui/Markdown.tsx +++ b/src/components/ui/Markdown.tsx @@ -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 = { + 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 ( + + ); +} + +// 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 (Key) + const kbdRegex = /([^<]+)<\/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( - - {parseInline(matchData, offset + minIndex + 2)} + + + + ); + } else if (matchType === "task_unchecked") { + result.push( + + + + ); + } else if (matchType === "bold" && typeof matchData === "string") { + result.push( + + {parseInline(matchData, onImageClick, offset + minIndex + 2)} ); } else if (matchType === "italic" && typeof matchData === "string") { result.push( - - {parseInline(matchData, offset + minIndex + 1)} + + {parseInline(matchData, onImageClick, offset + minIndex + 1)} ); + } else if (matchType === "strike" && typeof matchData === "string") { + result.push( + + {parseInline(matchData, onImageClick, offset + minIndex + 2)} + + ); + } else if (matchType === "highlight" && typeof matchData === "string") { + result.push( + + {parseInline(matchData, onImageClick, offset + minIndex + 2)} + + ); + } else if (matchType === "kbd" && typeof matchData === "string") { + result.push( + + {matchData} + + ); } else if (matchType === "code" && typeof matchData === "string") { result.push( {matchData} @@ -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)} ); - } 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( - - {matchData.text} - {matchData.text && ( - - {matchData.text} - +
+
onImageClick?.(url, alt)} + > + {/* eslint-disable-next-line @next/next/no-img-element */} + {alt +
+ + 点击放大预览 + +
+
+ {alt && ( +
+ {alt} +
)} - +
); } 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( +
+ +
e.stopPropagation()} + > + {/* eslint-disable-next-line @next/next/no-img-element */} + {alt} + {alt && ( +
+ {alt} +
+ )} +
+
, + 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 ( -
+
{blocks.map((block, idx) => { const key = `${block.type}-${idx}`; switch (block.type) { + case "hr": + return ( +
+
+
+
+
+ +
+
+ ); + case "table": { const data = block.tableData; if (!data) return null; return ( -
- +
+
- + {data.headers.map((header, i) => { const align = data.aligns[i] || "left"; return ( ); })} - + {data.rows.map((row, rIdx) => ( {row.map((cell, cIdx) => { const align = data.aligns[cIdx] || "left"; @@ -374,9 +704,9 @@ export default function Markdown({ content }: { content: string }) { ); })} @@ -387,95 +717,171 @@ export default function Markdown({ content }: { content: string }) { ); } + case "h1": - return ( -

- {parseInline(block.content || "")} -

- ); case "h2": - return ( -

- {parseInline(block.content || "")} -

- ); case "h3": - return ( -

- {parseInline(block.content || "")} -

- ); 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 ( +

+ + {parseInline(textContent, handleImageClick)} + + + +

+ ); + } + if (block.type === "h2") { + return ( +

+ + {parseInline(textContent, handleImageClick)} + + + +

+ ); + } + if (block.type === "h3") { + return ( +

+ + {parseInline(textContent, handleImageClick)} + + + +

+ ); + } return (

- {parseInline(block.content || "")} + {parseInline(textContent, handleImageClick)}

); + } + + case "callout": { + const calloutType = block.calloutType || "NOTE"; + const config = CALLOUT_MAP[calloutType]; + const Icon = config.icon; + const calloutText = block.lines ? block.lines.join(" ") : ""; + + return ( +
+
+ + {config.title} +
+
+ {parseInline(calloutText, handleImageClick)} +
+
+ ); + } + + case "blockquote": { + const quoteText = block.lines ? block.lines.join(" ") : ""; + return ( +
+ {parseInline(quoteText, handleImageClick)} +
+ ); + } + case "paragraph": { const text = block.lines ? block.lines.join(" ") : ""; return (

- {parseInline(text)} + {parseInline(text, handleImageClick)}

); } - case "blockquote": { - const text = block.lines ? block.lines.join(" ") : ""; - return ( -
- {parseInline(text)} -
- ); - } + case "ul": return (
    - {block.lines?.map((line, i) => ( -
  • - - {parseInline(line)} -
  • - ))} + {block.lines?.map((line, i) => { + const isTask = /^\[([ xX])\]/.test(line.trim()); + return ( +
  • + {!isTask && ( + + )} + {parseInline(line, handleImageClick)} +
  • + ); + })}
); + case "ol": return (
    {block.lines?.map((line, i) => (
  1. - {parseInline(line)} + {parseInline(line, handleImageClick)}
  2. ))}
); + 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 (
- {/* Mac 风格三色窗口控制栏 */} -
+ {/* Mac Terminal Topbar */} +
- - {block.lang || "code"} - +
+ + {block.lang || "code"} + + +
-
+                
                   
                 
); } + default: return null; } })} + + {/* Lightbox Modal */} + {activeImage && ( + setActiveImage(null)} + /> + )}
); } diff --git a/src/components/ui/TapeStation.tsx b/src/components/ui/TapeStation.tsx index d21e01d..1f7b0b9 100644 --- a/src/components/ui/TapeStation.tsx +++ b/src/components/ui/TapeStation.tsx @@ -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"; diff --git a/src/data/writing.ts b/src/data/writing.ts index 5693cdc..108cf2f 100644 --- a/src/data/writing.ts +++ b/src/data/writing.ts @@ -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 渲染引擎排版、调色与交互体验的测试文章。文章包含了行内样式 **粗体字**、*斜体字*、~~删除线~~、==文本高亮==、按键提示 Cmd + K 以及 [个人档案馆](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 \`
\${post.content}
\`; +} \`\`\` -## 小结 +--- -如果所有区块如标题、列表、引用和代码块都排版美观、字体易读、且代码块显示为精致的深色终端样式,则说明渲染引擎表现符合预期。` +## 五、胶片影像与 Lightbox 放大 + +![生活档案馆·摄影记录](/assets/writing-camera.png) + +## 六、小结 + +如果标题左侧带有暖色饰条、警示框色彩柔和且带有对应图标、代码块能够一键复制、图片点击可以弹出半透明全屏大图预览,则说明渲染引擎升级圆满完成!` } ]; diff --git a/src/hooks/useArticles.ts b/src/hooks/useArticles.ts index 6cad320..8770d2c 100644 --- a/src/hooks/useArticles.ts +++ b/src/hooks/useArticles.ts @@ -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"; diff --git a/src/hooks/useGallery.ts b/src/hooks/useGallery.ts index 1d5ca7d..c1b642a 100644 --- a/src/hooks/useGallery.ts +++ b/src/hooks/useGallery.ts @@ -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"; diff --git a/src/hooks/useSysConfig.ts b/src/hooks/useSysConfig.ts index f2dd9d6..8d6a54d 100644 --- a/src/hooks/useSysConfig.ts +++ b/src/hooks/useSysConfig.ts @@ -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 || []);
- {parseInline(header)} + {parseInline(header, handleImageClick)}
- {parseInline(cell)} + {parseInline(cell, handleImageClick)}