重做文章详情页:拾光阅读版式与目录/代码/灯箱交互

- 新增内容页外壳 base_content.html 与 reading.css / reading.js
- 重写 post_detail.html:分类胶囊、阅读进度、首字下沉、代码块复制、
  侧栏目录、上下篇、图片灯箱、明暗主题
- post_detail 视图补充上下篇、字数与阅读时长
- base.html 补 extra_css / extra_js block,修复脑图详情页样式不加载
- 加入 mindmaps、api、首页静态资源与模板
- 忽略 __pycache__ / *.pyc / *.back,并将已跟踪的 .pyc 移出版本库
This commit is contained in:
2026-11-20 15:37:55 +08:00
parent 7e45fa620e
commit 6ab9cca4f3
70 changed files with 26103 additions and 38 deletions
+4
View File
@@ -1 +1,5 @@
/media
__pycache__/
*.pyc
*.back
.DS_Store
View File
+3
View File
@@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.
+6
View File
@@ -0,0 +1,6 @@
from django.apps import AppConfig
class ApiConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "api"
View File
+3
View File
@@ -0,0 +1,3 @@
from django.db import models
# Create your models here.
+20
View File
@@ -0,0 +1,20 @@
# api/renderers.py
from rest_framework.renderers import BaseRenderer
class MarkdownRenderer(BaseRenderer):
"""
自定义 Markdown 渲染器
告诉 DRF 如何处理 text/markdown 类型的响应
"""
media_type = 'text/markdown'
format = 'markdown'
charset = 'utf-8'
def render(self, data, accepted_media_type=None, renderer_context=None):
"""
data 就是我们在视图里传给 Response 的字符串
"""
if isinstance(data, str):
return data.encode(self.charset)
return str(data).encode(self.charset)
+3
View File
@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.
+9
View File
@@ -0,0 +1,9 @@
from django.urls import path
from .views import sitemap_markdown
app_name = "api"
urlpatterns = [
# 对应前端请求的 /api/sitemap/
path('sitemap/', sitemap_markdown, name='sitemap-markdown'),
]
+60
View File
@@ -0,0 +1,60 @@
# api/views.py
from django.db import models
from rest_framework.decorators import api_view, renderer_classes
from rest_framework.response import Response
from blog.models import Category, Post, SiteInfo
from .renderers import MarkdownRenderer
@api_view(['GET'])
@renderer_classes([MarkdownRenderer])
def sitemap_markdown(request):
"""
生成站点地图的 Markdown 文本
分类按最早文章时间升序,文章按发布时间从小到大
"""
site_name = "我的博客"
try:
site_info = SiteInfo.get_site_info()
if site_info.about_title:
site_name = site_info.about_title
except Exception:
pass
lines = [f"# {site_name}", ""]
# 分类按该分类下最早发布的文章时间升序排列
# 没有文章的分类(first_post_date=None)会排在最前面
categories = Category.objects.all().order_by('name')
for cat in categories:
# 文章按 published_at 从小到大(升序)
posts = cat.posts.filter(status='published').order_by('published_at')
lines.append(f"## {cat.name}")
lines.append("")
if posts.exists():
for post in posts:
post_url = f"/post/{post.slug}/"
lines.append(f"### [{post.title}]({post_url})")
else:
lines.append("- *暂无文章*")
lines.append("")
# 未分类文章,同样按发布时间升序
uncategorized = Post.objects.filter(
categories__isnull=True,
status='published'
).order_by('published_at')
if uncategorized.exists():
lines.append("## 未分类")
lines.append("")
for post in uncategorized:
post_url = f"/post/{post.slug}/"
lines.append(f"### [{post.title}]({post_url})")
lines.append("")
markdown_text = "\n".join(lines)
return Response(markdown_text)
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+635
View File
@@ -0,0 +1,635 @@
/* =========================================================
🎨 主题变量 —— 想换配色就只动这里
========================================================= */
:root[data-theme="light"] {
--bg: #faf7f2; /* 羊皮纸暖底 */
--bg-grain: rgba(180,150,110,.04); /* 纸张噪点 */
--ink: #1f2937; /* 主文字 */
--ink-soft: #6b7280;
--ink-faint: #9ca3af;
--line: #e5e1d8; /* 分隔线 */
--card: #ffffff;
--card-shadow: 0 1px 2px rgba(31,41,55,.04), 0 4px 16px rgba(31,41,55,.06);
--card-shadow-hover: 0 4px 8px rgba(31,41,55,.06), 0 12px 28px rgba(31,41,55,.10);
--accent: #c2542d; /* 赤陶橘:主强调色 */
--accent-soft: rgba(194,84,45,.10);
/* 调色板:鼠尾草/琥珀/赤陶/板岩/梅子 */
--c1: #6b8f71; --c2: #d19a3f; --c3: #c2542d;
--c4: #5b7a9d; --c5: #8d5a83; --c6: #4a9c94;
}
:root[data-theme="dark"] {
--bg: #0f1319;
--bg-grain: rgba(255,255,255,.02);
--ink: #e8e6e1;
--ink-soft: #9ca3af;
--ink-faint: #6b7280;
--line: #232a33;
--card: #1a1f27;
--card-shadow: 0 1px 2px rgba(0,0,0,.3), 0 4px 16px rgba(0,0,0,.25);
--card-shadow-hover: 0 4px 8px rgba(0,0,0,.35), 0 12px 28px rgba(0,0,0,.45);
--accent: #e8956b;
--accent-soft: rgba(232,149,107,.12);
--c1: #7fae86; --c2: #e0b05c; --c3: #e8956b;
--c4: #7a9fc4; --c5: #b07ba8; --c6: #6bb8af;
}
* { margin:0; padding:0; box-sizing:border-box; }
html, body { height:100%; overflow:hidden; }
body {
font-family: 'Inter', -apple-system, 'PingFang SC', 'Microsoft YaHei', sans-serif;
background: var(--bg);
color: var(--ink);
transition: background .4s ease, color .4s ease;
}
/* 纸张噪点 + 柔和氛围光 */
body::before {
content:''; position:fixed; inset:0; pointer-events:none; z-index:0;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='3'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='0.35'/%3E%3C/svg%3E");
opacity:.35; mix-blend-mode:multiply;
}
body::after {
content:''; position:fixed; inset:0; pointer-events:none; z-index:0;
background:
radial-gradient(circle at 15% 20%, var(--accent-soft), transparent 45%),
radial-gradient(circle at 85% 80%, color-mix(in srgb, var(--c4) 10%, transparent), transparent 45%);
}
/* =========================================================
顶部 / 底部
========================================================= */
header {
position:fixed; top:0; left:0; right:0; z-index:10;
display:flex; align-items:center; justify-content:space-between;
padding: 18px 28px;
background: linear-gradient(to bottom, var(--bg) 30%, transparent);
pointer-events:none;
}
header > * { pointer-events:auto; }
.brand { display:flex; align-items:center; gap:12px; }
.brand-mark {
width:34px; height:34px; border-radius:10px;
background: linear-gradient(135deg, var(--c3), var(--c2));
display:grid; place-items:center; color:#fff;
font-family:'Noto Serif SC', serif; font-weight:900; font-size:16px;
box-shadow: var(--card-shadow);
transition: transform .3s cubic-bezier(.2,1.2,.4,1);
}
.brand-mark:hover { transform: rotate(-6deg) scale(1.06); }
.brand-text h1 {
font-family:'Noto Serif SC', serif;
font-size:17px; font-weight:700; letter-spacing:.5px;
}
.brand-text p { font-size:10.5px; color:var(--ink-faint); letter-spacing:3px; margin-top:1px; }
.top-actions { display:flex; gap:8px; align-items:center; }
.icon-btn {
width:34px; height:34px; border-radius:9px; border:1px solid var(--line);
background: var(--card); color: var(--ink-soft); cursor:pointer;
display:grid; place-items:center; font-size:14px;
transition: all .18s ease;
}
.icon-btn:hover { color:var(--accent); border-color:var(--accent); transform:translateY(-1px); }
.icon-btn.active { background:var(--accent); color:#fff; border-color:var(--accent); }
footer {
position:fixed; bottom:18px; left:28px; z-index:10;
font-size:11px; color:var(--ink-faint); letter-spacing:.5px;
display:flex; align-items:center; gap:14px;
}
footer .dot { width:3px; height:3px; border-radius:50%; background:var(--ink-faint); }
/* =========================================================
脑图容器
========================================================= */
#mindmap-wrap {
position:absolute; inset:0; z-index:1;
cursor:grab;
}
#mindmap-wrap.dragging { cursor:grabbing; }
svg#mindmap { width:100%; height:100%; display:block; }
/* =========================================================
Markmap 节点分层样式(核心)
foreignObject 里的内容是 Markdown 渲染后的 HTML
========================================================= */
/* —— 通用 —— */
.markmap-foreign, .markmap-foreign * {
font-family: inherit;
color: var(--ink);
transition: color .2s;
}
.markmap-foreign a { text-decoration:none; }
/* —— 根节点(depth-0):大标题胶囊 + 缓缓流动的鎏金 —— */
.markmap-node-depth-0 .markmap-foreign {
padding: 10px 22px !important;
background: linear-gradient(135deg, var(--accent), color-mix(in srgb, var(--accent) 60%, var(--c2)), var(--accent));
background-size: 220% 220%;
animation: nodeIn .5s cubic-bezier(.2,.8,.2,1) .05s backwards,
rootShimmer 7s ease-in-out .05s infinite;
border-radius: 999px;
box-shadow: var(--card-shadow-hover),
0 0 22px color-mix(in srgb, var(--accent) 22%, transparent);
}
@keyframes rootShimmer {
0%,100% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
}
.markmap-node-depth-0 .markmap-foreign *,
.markmap-node-depth-0 text {
color:#fff !important; fill:#fff !important;
font-family:'Noto Serif SC', serif !important;
font-size: 20px !important; font-weight: 900 !important;
letter-spacing: 1.5px;
}
/* —— 一级分类(depth-1):卡片 + 左侧色条 —— */
.markmap-node-depth-1 .markmap-foreign {
padding: 8px 16px 8px 14px !important;
background: var(--card);
border-radius: 12px;
border-left: 3px solid var(--node-color, var(--accent));
box-shadow: var(--card-shadow);
font-size: 15px;
transition: transform .2s ease, box-shadow .2s ease;
}
.markmap-node-depth-1 .markmap-foreign:hover {
transform: translateY(-2px);
box-shadow: var(--card-shadow-hover),
0 0 14px color-mix(in srgb, var(--node-color, var(--accent)) 25%, transparent);
}
.markmap-node-depth-1 .markmap-foreign h2,
.markmap-node-depth-1 .markmap-foreign strong {
font-family:'Noto Serif SC', serif;
font-size: 15.5px; font-weight: 700;
color: var(--ink);
}
/* —— 二级(depth-2):文章胶囊,可点击 —— */
.markmap-node-depth-2 .markmap-foreign {
padding: 4px 12px !important;
background: color-mix(in srgb, var(--node-color, var(--accent)) 8%, var(--card));
border: 1px solid color-mix(in srgb, var(--node-color, var(--accent)) 20%, transparent);
border-radius: 999px;
font-size: 13px; font-weight: 500;
transition: transform .18s, background .18s, border-color .18s;
}
.markmap-node-depth-2 .markmap-foreign a { color: var(--ink); }
.markmap-node-depth-2 .markmap-foreign:hover {
transform: translateY(-1.5px) scale(1.02);
background: color-mix(in srgb, var(--node-color, var(--accent)) 16%, var(--card));
border-color: var(--node-color, var(--accent));
}
.markmap-node-depth-2 .markmap-foreign a:hover { color: var(--node-color, var(--accent)); }
/* —— 三级及以下(depth-3+):极简小标签 —— */
.markmap-node-depth-3 .markmap-foreign,
.markmap-node-depth-4 .markmap-foreign {
padding: 2px 8px !important;
font-size: 11.5px;
color: var(--ink-soft) !important;
font-weight: 400;
letter-spacing: .3px;
}
.markmap-node-depth-3 .markmap-foreign a,
.markmap-node-depth-4 .markmap-foreign a { color: var(--ink-soft); }
.markmap-node-depth-3 .markmap-foreign a:hover { color: var(--accent); }
/* —— 节点圆点:按层级递减,hover 放大 —— */
.markmap-node > circle {
stroke-width: 2;
stroke: var(--bg);
filter: drop-shadow(0 1px 2px rgba(0,0,0,.12));
transition: r .18s ease;
}
.markmap-node-depth-0 > circle { r: 0; } /* 根节点隐藏圆点 */
.markmap-node-depth-1 > circle { r: 5; }
.markmap-node-depth-2 > circle { r: 4; }
.markmap-node-depth-3 > circle,
.markmap-node-depth-4 > circle { r: 3; opacity:.7; }
.markmap-node > circle:hover { r: 7; }
/* —— 分支连线:透明度随深度递减 —— */
.markmap-link { fill:none; stroke-linecap: round; }
.markmap-link-depth-0 { stroke-width: 2.4; opacity: .85; }
.markmap-link-depth-1 { stroke-width: 1.8; opacity: .65; }
.markmap-link-depth-2 { stroke-width: 1.3; opacity: .45; }
.markmap-link-depth-3,
.markmap-link-depth-4 { stroke-width: 1; opacity: .28; }
/* —— 入场级联动画 —— */
@keyframes nodeIn {
from { opacity: 0; transform: translateY(6px); }
to { opacity: 1; transform: none; }
}
.markmap-node .markmap-foreign {
animation: nodeIn .5s cubic-bezier(.2,.8,.2,1) backwards;
}
.markmap-node-depth-1 .markmap-foreign { animation-delay: .15s; }
.markmap-node-depth-2 .markmap-foreign { animation-delay: .28s; }
.markmap-node-depth-3 .markmap-foreign { animation-delay: .40s; }
@keyframes lineIn { from { stroke-opacity: 0; } }
.markmap-link { animation: lineIn .6s ease backwards; }
/* —— 搜索高亮 —— */
.markmap-node.matched .markmap-foreign {
outline: 2px solid var(--accent);
outline-offset: 2px;
border-radius: 999px;
}
.markmap-node.matched-dim { opacity: .25; transition: opacity .25s; }
/* =========================================================
搜索框
========================================================= */
.search-box {
position:fixed; top: 18px; left: 50%; transform: translateX(-50%) translateY(-8px);
z-index: 20;
display:flex; align-items:center; gap:8px;
padding: 8px 14px;
background: var(--card); border: 1px solid var(--line); border-radius: 999px;
box-shadow: var(--card-shadow-hover);
opacity:0; pointer-events:none;
transition: all .22s cubic-bezier(.2,.8,.2,1);
}
.search-box.show { opacity:1; pointer-events:auto; transform: translateX(-50%) translateY(0); }
.search-box input {
border:none; outline:none; background:none;
font: inherit; font-size: 13.5px; width: 220px; color: var(--ink);
}
.search-box kbd {
font: 11px 'JetBrains Mono', monospace;
padding: 2px 6px; border-radius:5px;
background: var(--bg); color: var(--ink-faint); border:1px solid var(--line);
}
/* =========================================================
右下角工具栏
========================================================= */
.toolbar {
position:fixed; right:20px; bottom:20px; z-index:20;
display:flex; flex-direction:column; gap:6px;
}
.toolbar .icon-btn { width:36px; height:36px; font-size:14px; background:var(--card); }
/* =========================================================
移动端
========================================================= */
@media (max-width: 720px) {
header { padding: 12px 16px; }
.brand-text p, .top-actions .hint { display:none; }
footer { display:none; }
.search-box input { width: 160px; }
.markmap-node-depth-0 .markmap-foreign { font-size:17px !important; padding:8px 18px !important; }
.markmap-node-depth-1 .markmap-foreign { font-size:13.5px; padding:6px 12px !important; }
.markmap-node-depth-2 .markmap-foreign { font-size:12px; padding:3px 10px !important; }
}
/* 极光层 */
.aurora {
position: fixed; inset: -20%;
z-index: 0; pointer-events: none;
filter: blur(80px) saturate(140%);
opacity: .55;
animation: auroraShift 24s ease-in-out infinite alternate;
}
.aurora::before,
.aurora::after {
content: ''; position: absolute; border-radius: 50%;
}
.aurora::before {
width: 55vw; height: 55vw;
top: -10%; left: 5%;
background: radial-gradient(circle at 30% 30%, var(--c3), transparent 65%);
animation: blobA 18s ease-in-out infinite alternate;
}
.aurora::after {
width: 45vw; height: 45vw;
bottom: -15%; right: 5%;
background: radial-gradient(circle at 60% 40%, var(--c4), transparent 65%);
animation: blobB 22s ease-in-out infinite alternate;
}
.aurora > .blob-c {
position: absolute;
width: 40vw; height: 40vw;
top: 30%; left: 35%;
background: radial-gradient(circle at 50% 50%, var(--c6), transparent 65%);
animation: blobC 26s ease-in-out infinite alternate;
}
@keyframes auroraShift {
from { transform: rotate(0deg) scale(1); }
to { transform: rotate(8deg) scale(1.08); }
}
@keyframes blobA { from { transform: translate(0,0); } to { transform: translate(12vw, 8vh); } }
@keyframes blobB { from { transform: translate(0,0); } to { transform: translate(-10vw, -6vh); } }
@keyframes blobC { from { transform: translate(0,0) scale(1); } to { transform: translate(-8vw, 10vh) scale(1.15); } }
/* 暗色模式下极光更浓郁 */
:root[data-theme="dark"] .aurora { opacity: .45; filter: blur(100px) saturate(160%); }
/* =========================================================
🎬 开场引导层 · 「道生万物」
========================================================= */
:root { --intro-dur: 4600ms; }
.intro {
position: fixed; inset: 0; z-index: 9999;
display: grid; place-items: center;
background: color-mix(in srgb, var(--bg) 86%, transparent);
backdrop-filter: blur(24px) saturate(140%);
-webkit-backdrop-filter: blur(24px) saturate(140%);
transition: opacity .7s cubic-bezier(.4,0,.2,1),
transform .7s cubic-bezier(.4,0,.2,1),
filter .7s cubic-bezier(.4,0,.2,1);
cursor: pointer;
}
.intro.leaving {
opacity: 0; transform: scale(1.04); filter: blur(12px);
pointer-events: none;
}
.intro-inner { display:flex; flex-direction:column; align-items:center; text-align:center; }
/* 内部元素级联入场 */
.intro-inner > * { animation: introUp .8s cubic-bezier(.2,.8,.2,1) backwards; }
.intro-inner > .intro-seed { animation-delay: .1s; }
.intro-inner > .tao-phase { animation-delay: .15s; }
.intro-inner > .intro-title { animation-delay: .35s; }
.intro-inner > .intro-sub { animation-delay: .55s; }
.intro-inner > .intro-divider { animation-delay: .7s; }
.intro-inner > .intro-stats { animation-delay: .8s; }
.intro-inner > .intro-progress { animation-delay: 1s; }
.intro-inner > .intro-hint { animation-delay: 1.2s; }
@keyframes introUp { from { opacity:0; transform: translateY(18px); } to { opacity:1; transform:none; } }
.intro-title {
font-family:'Noto Serif SC', serif; font-weight:900;
font-size: clamp(34px, 6vw, 56px);
letter-spacing: .18em; margin: 16px 0 8px;
background: linear-gradient(120deg, var(--ink) 20%, var(--accent) 75%, var(--c2));
-webkit-background-clip: text; background-clip: text; color: transparent;
filter: drop-shadow(0 0 18px color-mix(in srgb, var(--accent) 30%, transparent));
}
.intro-sub { color: var(--ink-soft); font-size: 14px; letter-spacing: .35em; text-indent: .35em; }
/* =========================================================
✦ 道生万物 · 生成之树
道(根) → 一 → 二(阴阳) → 三 → 万物(九叶)
每一层等上一层生成完毕再依次展开,节奏即"生生不息"
========================================================= */
.intro-seed { width: 195px; height: 195px; animation: seedFloat 5s ease-in-out infinite alternate; }
@keyframes seedFloat { from { transform: translateY(-4px) } to { transform: translateY(6px) } }
.seed-svg { width:100%; height:100%; overflow: visible; }
/* —— SVG 渐变停靠点:颜色跟随主题变量 —— */
.sgVine-a { stop-color: var(--accent); }
.sgVine-b { stop-color: var(--c2); }
.sgNode-a { stop-color: color-mix(in srgb, var(--c2) 55%, #fff); }
.sgNode-b { stop-color: var(--accent); }
.sgRoot-a { stop-color: color-mix(in srgb, var(--accent) 18%, #fff); }
.sgRoot-b { stop-color: var(--c2); }
.sgRoot-c { stop-color: var(--accent); }
.sgHalo-a { stop-color: var(--accent); stop-opacity:.45; }
.sgHalo-b { stop-color: var(--accent); stop-opacity:0; }
/* —— 缓旋虚线轨道 —— */
.orbit {
transform-box: fill-box; transform-origin: center;
animation: orbitSpin 46s linear infinite, orbitFade 1.4s ease .2s backwards;
}
@keyframes orbitSpin { to { transform: rotate(360deg); } }
@keyframes orbitFade { from { opacity: 0; } to { opacity: 1; } }
.orbit circle {
fill:none; stroke: var(--ink); opacity:.12; stroke-width:1;
stroke-dasharray: .018 .03; stroke-linecap: round;
}
/* —— 根部呼吸光晕 —— */
.halo {
fill: url(#sgHalo); stroke: none;
transform-box: fill-box; transform-origin: center;
animation: haloBreath 3s ease-in-out infinite;
}
@keyframes haloBreath {
0%,100% { transform: scale(.9); opacity:.55; }
50% { transform: scale(1.25); opacity:.95; }
}
/* —— 双层声呐波纹(错峰扩散) —— */
.sonar {
fill: none; stroke: var(--accent); stroke-width: 1.5;
transform-box: fill-box; transform-origin: center;
animation: sonar 2.4s ease-out infinite;
}
.sonar.s-b { animation-delay: 1.2s; }
@keyframes sonar { from { transform: scale(.6); opacity:.55 } to { transform: scale(2.4); opacity:0 } }
/* —— 藤蔓:渐变描边 + 辉光,按"世代"依次生长 —— */
.sl {
stroke: url(#sgVine); stroke-width: 2.3; stroke-linecap: round; fill: none;
stroke-dasharray: 1; stroke-dashoffset: 1;
filter: drop-shadow(0 0 4px color-mix(in srgb, var(--accent) 55%, transparent));
animation: draw .8s cubic-bezier(.4,0,.2,1) forwards;
}
.sl.g1 { animation-delay:.45s; } /* 道生一 */
.sl.g2 { animation-delay:1.25s; } /* 一生二 */
.sl.g3 { animation-delay:2.05s; } /* 二生三 */
@keyframes draw { to { stroke-dashoffset: 0 } }
/* —— 细枝:三生万物,九枝散叶 —— */
.twig {
stroke: var(--c2); stroke-width: 1.1; stroke-linecap: round; fill:none;
opacity:.6; stroke-dasharray: 1; stroke-dashoffset: 1;
animation: draw .5s ease forwards;
}
.twig.tw1 { animation-delay:2.95s } .twig.tw2 { animation-delay:3.02s }
.twig.tw3 { animation-delay:3.09s } .twig.tw4 { animation-delay:3.16s }
.twig.tw5 { animation-delay:3.23s } .twig.tw6 { animation-delay:3.30s }
.twig.tw7 { animation-delay:3.37s } .twig.tw8 { animation-delay:3.44s }
.twig.tw9 { animation-delay:3.51s }
/* —— 知识节点:渐变描边圆点,弹性绽放 —— */
.sn {
fill: var(--bg); stroke: url(#sgNode); stroke-width: 2.2;
transform-box: fill-box; transform-origin: center;
transform: scale(0);
filter: drop-shadow(0 0 5px color-mix(in srgb, var(--accent) 55%, transparent));
animation: pop .5s cubic-bezier(.2,1.4,.4,1) forwards;
}
.sn.n1 { animation-delay:.95s; } /* 一 */
.sn.n2 { animation-delay:1.85s; } /* 二 */
.sn.n3 { animation-delay:2.65s; } /* 三 */
@keyframes pop { to { transform: scale(1) } }
/* —— 阴阳二仪:一空一盈 —— */
.sn.yin { fill: var(--bg); stroke: url(#sgNode); }
.sn.yang { fill: url(#sgNode); stroke: none; }
/* —— 根部:鎏光呼吸的「道」 —— */
.sn.root {
fill: url(#sgRoot); stroke: none;
transform: scale(1);
animation: rootPulse 2.2s ease-in-out infinite;
filter: drop-shadow(0 0 10px color-mix(in srgb, var(--accent) 70%, transparent));
}
@keyframes rootPulse { 0%,100% { transform: scale(1) } 50% { transform: scale(1.16) } }
/* —— 万物之叶 —— */
.lf {
fill: var(--c2); stroke:none;
transform-box: fill-box; transform-origin: center;
transform: scale(0);
filter: drop-shadow(0 0 4px color-mix(in srgb, var(--c2) 60%, transparent));
animation: pop .45s cubic-bezier(.2,1.4,.4,1) forwards;
}
.lf.lf1 { animation-delay:3.35s } .lf.lf2 { animation-delay:3.42s }
.lf.lf3 { animation-delay:3.49s } .lf.lf4 { animation-delay:3.56s }
.lf.lf5 { animation-delay:3.63s } .lf.lf6 { animation-delay:3.70s }
.lf.lf7 { animation-delay:3.77s } .lf.lf8 { animation-delay:3.84s }
.lf.lf9 { animation-delay:3.91s }
/* —— 光尘:散落的时光正被拾起 —— */
.dust {
fill: var(--c2); opacity: 0;
transform-box: fill-box; transform-origin: center;
animation: dustFloat 4.5s ease-in infinite;
}
@keyframes dustFloat {
0% { opacity:0; transform: translateY(10px) scale(.7); }
25% { opacity:.9; }
100% { opacity:0; transform: translateY(-30px) scale(1.2); }
}
/* —— 流光:沿生成之路巡游的光点 —— */
.spark {
fill: var(--accent); stroke:none; opacity:0;
filter: drop-shadow(0 0 5px var(--accent));
animation: sparkLife 2.4s linear infinite;
}
@keyframes sparkLife {
0% { opacity:0; } 12% { opacity:1; } 82% { opacity:1; } 100% { opacity:0; }
}
/* —— 节点铭文:道 / 一 / 二 / 三 / 万物 —— */
.lbl {
font-family:'Noto Serif SC', serif; font-size:10px;
fill: var(--ink-soft); opacity:0;
animation: lblIn .7s ease forwards;
}
.lbl.l-wan { font-size:11px; fill: var(--accent); letter-spacing:2px; }
.lbl.l-dao { animation-delay:.6s }
.lbl.l-yi { animation-delay:1.15s }
.lbl.l-er { animation-delay:2.05s }
.lbl.l-san { animation-delay:2.85s }
.lbl.l-wan { animation-delay:3.75s }
@keyframes lblIn { from { opacity:0; transform: translateY(4px); } to { opacity:.8; transform:none; } }
.lbl.l-wan { animation-name: lblInWan; }
@keyframes lblInWan { from { opacity:0; transform: translateY(4px) scale(.9); } to { opacity:1; transform:none; } }
/* =========================================================
✦ 生成之语:道生一 → 一生二 → 二生三 → 三生万物
与树的展开节奏逐段同步(总时长 ≈ --intro-dur)
========================================================= */
.tao-phase {
position:relative; width: 220px; height: 24px; margin: 2px 0 0;
}
.tao-phase span {
position:absolute; inset:0; display:grid; place-items:center;
font-family:'Noto Serif SC', serif;
font-size:14px; letter-spacing:.5em; text-indent:.5em;
color: var(--ink-soft);
opacity:0;
animation-duration: 4.6s;
animation-timing-function: ease;
animation-fill-mode: forwards;
}
.tao-phase span:nth-child(1) { animation-name: taoP1; }
.tao-phase span:nth-child(2) { animation-name: taoP2; }
.tao-phase span:nth-child(3) { animation-name: taoP3; }
.tao-phase span:nth-child(4) { animation-name: taoP4; color: var(--accent); }
@keyframes taoP1 { 0%{opacity:0} 5%{opacity:1} 18%{opacity:1} 25%{opacity:0} 100%{opacity:0} }
@keyframes taoP2 { 0%{opacity:0} 23%{opacity:0} 29%{opacity:1} 40%{opacity:1} 47%{opacity:0} 100%{opacity:0} }
@keyframes taoP3 { 0%{opacity:0} 43%{opacity:0} 49%{opacity:1} 60%{opacity:1} 67%{opacity:0} 100%{opacity:0} }
@keyframes taoP4 { 0%{opacity:0} 64%{opacity:0} 71%{opacity:1} 100%{opacity:1} }
/* —— 数据统计:竖线分隔 + 数字鎏金渐变 —— */
.intro-stats { display:flex; gap: 0; margin: 20px 0 28px; }
.stat { display:flex; flex-direction:column; align-items:center; gap:4px; padding: 0 26px; position:relative; }
.stat + .stat::before {
content:''; position:absolute; left:0; top:18%; height:64%; width:1px;
background: linear-gradient(180deg, transparent, var(--line) 30%, var(--line) 70%, transparent);
}
.stat b {
font-family:'Noto Serif SC', serif; font-size: 26px; font-weight:900;
background: linear-gradient(180deg, var(--ink) 30%, color-mix(in srgb, var(--accent) 60%, var(--ink)));
-webkit-background-clip: text; background-clip: text; color: transparent;
font-variant-numeric: tabular-nums;
}
.stat span { font-size: 11px; color: var(--ink-faint); letter-spacing: 2px; }
/* 进度条:时长由 JS 写入 --intro-dur,与自动跳转严格同步 */
.intro-progress {
width: 240px; height: 2px; border-radius: 2px; overflow: hidden;
background: color-mix(in srgb, var(--ink) 12%, transparent);
}
.intro-progress i {
display:block; height:100%; width:0; border-radius:2px;
background: linear-gradient(90deg, var(--c3), var(--c2));
box-shadow: 0 0 10px color-mix(in srgb, var(--accent) 60%, transparent);
animation: introProg var(--intro-dur) linear forwards;
}
@keyframes introProg { to { width: 100% } }
.intro-hint {
margin-top: 12px; font-size: 11.5px; color: var(--ink-faint);
letter-spacing: 3px; animation: hintBlink 2.4s ease-in-out infinite;
}
@keyframes hintBlink { 0%,100%{opacity:.45} 50%{opacity:1} }
.intro-skip {
position: absolute; right: 28px; bottom: 26px;
padding: 8px 18px; border-radius: 999px; cursor: pointer;
background: transparent; color: var(--ink-soft);
border: 1px solid var(--line);
font-size: 12.5px; font-family: inherit; letter-spacing: 2px;
transition: all .2s;
}
.intro-skip:hover { color: var(--accent); border-color: var(--accent); transform: translateX(-2px); }
/* —— 主页面在开场前"未聚焦",揭幕后聚焦呈现 —— */
#mindmap-wrap, header, footer, .toolbar {
opacity: 0; transform: scale(.975); filter: blur(8px);
transition: opacity .9s ease .15s,
transform .9s cubic-bezier(.2,.8,.2,1) .15s,
filter .9s ease .15s;
}
body.intro-done #mindmap-wrap, body.intro-done header,
body.intro-done footer, body.intro-done .toolbar {
opacity: 1; transform: none; filter: none;
}
@media (max-width: 720px) {
.stat { padding: 0 16px; }
.stat b { font-size: 20px; }
.intro-progress { width: 190px; }
.intro-divider i { width: 44px; }
.tao-phase { width: 180px; }
.tao-phase span { font-size: 12.5px; }
}
/* —— 无障碍:偏好减弱动效时,直接呈现生成完成的静帧 —— */
@media (prefers-reduced-motion: reduce) {
.intro-seed, .intro-hint, .sonar, .sn.root, .halo, .orbit,
.dust, .spark, .intro-divider b,
.markmap-node-depth-0 .markmap-foreign { animation: none !important; }
.sl, .twig { animation: none !important; stroke-dashoffset: 0 !important; }
.sn, .lf { animation: none !important; transform: none !important; opacity: 1 !important; }
.lbl { animation: none !important; opacity: .8 !important; }
.lbl.l-wan { opacity: 1 !important; }
.tao-phase span { animation: none !important; opacity: 0 !important; }
.tao-phase span:last-child { opacity: 1 !important; }
.dust, .spark { opacity: 0 !important; }
.intro, #mindmap-wrap, header, footer, .toolbar { transition-duration: .01s !important; }
}
+39
View File
@@ -0,0 +1,39 @@
import os
import re
import urllib.request
# ==== 按你的实际路径改这三行 ====
CSS_IN = 'fonts.css'
CSS_OUT = 'fonts_out.css'
FONT_DIR = './files'
# ================================
UA = ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36')
os.makedirs(FONT_DIR, exist_ok=True)
css = open(CSS_IN, encoding='utf-8').read()
pat = re.compile(r'url\((["\']?)(https://gstatic\.loli\.net/[^)"\']+)\1\)')
urls = list(dict.fromkeys(m.group(2) for m in pat.finditer(css)))
print(f'找到 {len(urls)} 个字体文件')
if not urls:
raise SystemExit('没匹配到 gstatic 链接,检查 fonts.css 内容是否正常')
total = 0
for i, u in enumerate(urls):
name = f'{i:03d}.woff2'
path = os.path.join(FONT_DIR, name)
if not os.path.exists(path):
req = urllib.request.Request(u, headers={'User-Agent': UA})
with urllib.request.urlopen(req, timeout=60) as r, open(path, 'wb') as f:
f.write(r.read())
size = os.path.getsize(path)
total += size
css = css.replace(u, f'files/{name}') # 改成相对路径
if (i + 1) % 20 == 0 or i == len(urls) - 1:
print(f' {i+1}/{len(urls)} 累计 {total/1024/1024:.1f} MB')
open(CSS_OUT, 'w', encoding='utf-8').write(css)
print('完成 →', CSS_OUT)
+2
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
+221
View File
@@ -0,0 +1,221 @@
/* =========================================================
0. 主题初始化(提前到数据加载之前,避免暗色用户先看到白屏闪烁)
========================================================= */
document.documentElement.dataset.theme =
localStorage.getItem('theme') || 'light';
/* =========================================================
1. 博客数据源:从 Django 后端接口拉取 Markdown
后端视图见 sitemap_views.py,返回 text/markdown
接口失败时用兜底数据渲染,保证页面不白屏
========================================================= */
const SITEMAP_API = '/api/sitemap/';
const FALLBACK_MARKDOWN = `
# 我的博客
## 数据加载失败
### 请稍后重试
- [检查后端接口](/api/sitemap/)
`;
async function loadMarkdown() {
try {
const res = await fetch(SITEMAP_API, { headers: { 'Accept': 'text/markdown' } });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const md = await res.text();
if (!md.trim()) throw new Error('接口返回为空');
return md;
} catch (err) {
console.error('[sitemap] 加载失败:', err);
return FALLBACK_MARKDOWN;
}
}
const markdown = await loadMarkdown();
/* ============ 2. 解析 & 渲染 ============ */
const { Transformer } = window.markmap;
const { Markmap, deriveOptions } = window.markmap;
const transformer = new Transformer();
const { root } = transformer.transform(markdown);
const svgEl = document.getElementById('mindmap');
// 调色板(与 CSS 变量同步;一级分类按索引取色,向下继承)
const PALETTE = ['#6b8f71', '#d19a3f', '#c2542d', '#5b7a9d', '#8d5a83', '#4a9c94'];
// 给每个 depth-1 节点分配一个主题色,并通过 CSS 变量注入 foreignObject
function paintBranches(node, color, depth = 0) {
node.state = node.state || {};
node.state.depth = depth;
if (depth === 0) color = null;
else if (depth === 1) color = PALETTE[(node.state.key ?? 0) % PALETTE.length];
node.state.color = color || '#c2542d';
(node.children || []).forEach((c, i) => {
c.state = c.state || {};
c.state.key = i;
paintBranches(c, color, depth + 1);
});
}
root.children?.forEach((c, i) => { c.state = { key: i }; paintBranches(c, null, 1); });
const mm = Markmap.create(svgEl, {
duration: 380,
maxWidth: 260,
initialExpandLevel: 2,
spacingHorizontal: 110,
spacingVertical: 14,
paddingX: 12,
...deriveOptions({
colorFreezeLevel: 2,
linkShape: 'diagonal',
}),
color: (node) => node.state?.color ?? '#c2542d',
}, root);
// 把当前节点的分支色注入到 foreignObject,驱动 CSS 的 --node-color
function applyNodeColorVars() {
svgEl.querySelectorAll('.markmap-node').forEach(g => {
const depth = [...g.classList].find(c => c.startsWith('markmap-node-depth-'));
if (!depth) return;
const d = parseInt(depth.split('-').pop(), 10);
const circle = g.querySelector(':scope > circle');
const branchColor = circle ? circle.getAttribute('fill') : null;
if (branchColor) g.style.setProperty('--node-color', branchColor);
});
}
applyNodeColorVars();
mm.fit();
/* ============ 2.5 开场引导层(已移除数量统计逻辑) ============ */
const INTRO_DURATION = 10000;
const INTRO_EVERY_VISIT = true;
const INTRO_KEY = 'intro-seen';
const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)').matches;
/* 揭幕时重播脑图级联入场动画 */
function replayEntrance() {
svgEl.querySelectorAll('.markmap-foreign, .markmap-link').forEach(el => {
el.style.animation = 'none';
void el.offsetWidth;
el.style.animation = '';
});
}
const introEl = document.getElementById('intro');
function finishIntro() {
if (!introEl || introEl.classList.contains('leaving')) return;
introEl.classList.add('leaving');
document.body.classList.add('intro-done');
replayEntrance();
setTimeout(() => { introEl.remove(); mm.fit(); }, 800);
try { sessionStorage.setItem(INTRO_KEY, '1'); } catch {}
}
(function startIntro() {
let seen = null;
try { seen = sessionStorage.getItem(INTRO_KEY); } catch {}
const dur = (seen && !INTRO_EVERY_VISIT) || reduceMotion
? Math.min(INTRO_DURATION, 900)
: INTRO_DURATION;
document.documentElement.style.setProperty('--intro-dur', dur + 'ms');
// 【已移除】countUp 数字滚动统计调用
// 【已移除】footer 文章数同步
const timer = setTimeout(finishIntro, dur);
const skip = () => { clearTimeout(timer); finishIntro(); };
introEl.addEventListener('click', skip);
document.getElementById('btnSkipIntro').addEventListener('click', (e) => {
e.stopPropagation(); skip();
});
document.addEventListener('keydown', skip, { once: true });
})();
/* ============ 3. 主题切换 ============ */
const btnTheme = document.getElementById('btnTheme');
btnTheme.onclick = () => {
const cur = document.documentElement.dataset.theme;
const next = cur === 'light' ? 'dark' : 'light';
document.documentElement.dataset.theme = next;
localStorage.setItem('theme', next);
};
/* ============ 4. 搜索:匹配节点高亮 + 折叠其它 ============ */
const searchBox = document.getElementById('searchBox');
const searchInput = document.getElementById('searchInput');
btnSearch.onclick = () => {
searchBox.classList.toggle('show');
if (searchBox.classList.contains('show')) searchInput.focus();
else clearSearch();
};
searchInput.addEventListener('input', e => runSearch(e.target.value));
searchInput.addEventListener('keydown', e => {
if (e.key === 'Escape') { searchBox.classList.remove('show'); clearSearch(); }
});
document.addEventListener('keydown', e => {
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
e.preventDefault();
btnSearch.click();
}
});
function runSearch(q) {
clearSearch();
if (!q.trim()) return;
const kw = q.toLowerCase();
const matched = [];
svgEl.querySelectorAll('.markmap-node').forEach(g => {
const fo = g.querySelector('.markmap-foreign');
if (!fo) return;
const text = fo.textContent.toLowerCase();
if (text.includes(kw)) {
g.classList.add('matched');
matched.push(g);
} else {
g.classList.add('matched-dim');
}
});
matched.forEach(g => {
let p = g.parentElement;
while (p && !p.classList.contains('markmap-node')) p = p.parentElement;
});
if (matched.length) {
const first = matched[0].querySelector('.markmap-foreign');
if (first) first.scrollIntoView({ behavior:'smooth', block:'center', inline:'center' });
}
}
function clearSearch() {
svgEl.querySelectorAll('.matched, .matched-dim').forEach(g =>
g.classList.remove('matched', 'matched-dim'));
}
/* ============ 5. 文章点击:接管路由 ============ */
svgEl.addEventListener('click', e => {
const a = e.target.closest('.markmap-foreign a');
if (!a) return;
e.preventDefault();
window.open(a.getAttribute('href'), '_blank');
});
/* ============ 6. 工具栏 ============ */
const $ = id => document.getElementById(id);
$('btnFit').onclick = () => mm.fit();
$('btnIn').onclick = () => mm.rescale(1.2);
$('btnOut').onclick = () => mm.rescale(1/1.2);
$('btnFs').onclick = () => {
if (!document.fullscreenElement) document.documentElement.requestFullscreen();
else document.exitFullscreen();
};
/* ============ 7. 响应式 + 拖拽反馈 ============ */
let raf;
window.addEventListener('resize', () => {
cancelAnimationFrame(raf);
raf = requestAnimationFrame(() => mm.fit());
});
const wrap = document.getElementById('mindmap-wrap');
wrap.addEventListener('mousedown', () => wrap.classList.add('dragging'));
window.addEventListener('mouseup', () => wrap.classList.remove('dragging'));
+313
View File
@@ -0,0 +1,313 @@
/* =========================================================
拾光 · 阅读页交互
1. 主题切换(与首页共享 localStorage 键名 theme)
2. 顶栏滚动态 + 阅读进度
3. 自动生成目录(侧栏 / 窄屏折叠)
4. 代码块:语言标签 + 一键复制
5. 表格横向滚动包裹
6. 图片灯箱
7. 键盘 ← → 翻上下篇
无第三方依赖。
========================================================= */
(function () {
'use strict';
var root = document.documentElement;
var bodyEl = document.body;
/* ---------- 1. 主题切换 ---------- */
var btnTheme = document.getElementById('btnTheme');
if (btnTheme) {
btnTheme.addEventListener('click', function () {
var next = root.dataset.theme === 'dark' ? 'light' : 'dark';
root.dataset.theme = next;
try { localStorage.setItem('theme', next); } catch (e) {}
});
}
/* ---------- 2. 顶栏 + 阅读进度 ---------- */
var head = document.getElementById('siteHead');
var bar = document.getElementById('readProgress');
var ticking = false;
function updateScrollUI() {
var y = window.pageYOffset || document.documentElement.scrollTop || 0;
if (head) head.classList.toggle('is-scrolled', y > 8);
if (bar) {
var doc = document.documentElement;
var max = doc.scrollHeight - window.innerHeight;
var p = max > 0 ? Math.min(1, Math.max(0, y / max)) : 0;
bar.style.setProperty('--p', (p * 100).toFixed(2) + '%');
}
spy();
ticking = false;
}
function onScroll() {
if (ticking) return;
ticking = true;
window.requestAnimationFrame(updateScrollUI);
}
/* ---------- 3. 目录 ---------- */
var postBody = document.getElementById('postBody');
var tocFixed = document.getElementById('toc');
var tocMobile = document.getElementById('tocMobile');
var headings = postBody
? [].slice.call(postBody.querySelectorAll('h1, h2, h3'))
: [];
// 给标题补锚点 id
headings.forEach(function (h, i) {
if (!h.id) h.id = 'sec-' + (i + 1);
});
function buildToc(list) {
if (!list) return;
var frag = document.createDocumentFragment();
headings.forEach(function (h) {
var li = document.createElement('li');
li.className = 'toc-item depth-' + h.tagName.charAt(1);
var a = document.createElement('a');
a.href = '#' + h.id;
a.textContent = (h.textContent || '').trim().slice(0, 60) || '(无标题)';
li.appendChild(a);
frag.appendChild(li);
});
list.appendChild(frag);
}
if (headings.length >= 2) {
buildToc(tocFixed && tocFixed.querySelector('.toc-list'));
buildToc(tocMobile && tocMobile.querySelector('.toc-list'));
}
var tocLinks = [].slice.call(document.querySelectorAll('.toc-list a'));
// 侧栏目录只在足够宽时出现;窄屏用折叠目录
function syncToc() {
if (!tocFixed) return;
var wide = window.innerWidth >= 1340;
tocFixed.hidden = !(wide && headings.length >= 2);
if (tocMobile) tocMobile.hidden = headings.length < 2;
}
// 目录点击后收起折叠面板
if (tocMobile) {
tocMobile.addEventListener('click', function (e) {
if (e.target.closest('a')) tocMobile.open = false;
});
}
// 滚动高亮当前章节
function spy() {
if (!tocLinks.length) return;
var probe = window.innerHeight * 0.18 + 64;
var current = null;
for (var i = 0; i < headings.length; i++) {
var h = headings[i];
if (h.getBoundingClientRect().top <= probe) current = h;
else break;
}
if (!current) current = headings[0];
var currentId = current ? '#' + current.id : null;
tocLinks.forEach(function (a) {
a.classList.toggle('is-active', a.getAttribute('href') === currentId);
});
}
/* ---------- 4. 代码块增强 ---------- */
var LANG_NAMES = {
python: 'Python', py: 'Python', cpp: 'C++', 'c++': 'C++', cxx: 'C++',
c: 'C', vim: 'Vim', html: 'HTML', css: 'CSS', js: 'JavaScript',
javascript: 'JavaScript', asm: 'ASM', bat: 'BAT', bash: 'Bash',
shell: 'Shell', sh: 'Shell', markdown: 'Markdown', md: 'Markdown',
note: 'Note', java: 'Java', sql: 'SQL', json: 'JSON', go: 'Go',
rust: 'Rust', php: 'PHP', xml: 'XML', yaml: 'YAML', ini: 'INI'
};
function copyText(text) {
if (navigator.clipboard && window.isSecureContext !== false) {
return navigator.clipboard.writeText(text);
}
return new Promise(function (resolve, reject) {
var ta = document.createElement('textarea');
ta.value = text;
ta.setAttribute('readonly', '');
ta.style.cssText = 'position:fixed;top:-999px;left:-999px;opacity:0';
document.body.appendChild(ta);
ta.select();
try {
document.execCommand('copy') ? resolve() : reject(new Error('copy failed'));
} catch (err) {
reject(err);
}
document.body.removeChild(ta);
});
}
function enhanceCode(pre) {
var code = pre.querySelector('code');
var cls = (code && code.getAttribute('class')) || pre.getAttribute('class') || '';
var m = /language-([\w+#-]+)/i.exec(cls);
var lang = m ? (LANG_NAMES[m[1].toLowerCase()] || m[1]) : '';
var wrap = document.createElement('div');
wrap.className = 'code-block';
var barEl = document.createElement('div');
barEl.className = 'code-bar';
var label = document.createElement('span');
label.className = 'code-lang';
label.textContent = lang || 'CODE';
barEl.appendChild(label);
var btn = document.createElement('button');
btn.type = 'button';
btn.className = 'code-copy';
btn.textContent = '复制';
btn.setAttribute('aria-label', '复制这段代码');
barEl.appendChild(btn);
pre.parentNode.insertBefore(wrap, pre);
wrap.appendChild(barEl);
wrap.appendChild(pre);
btn.addEventListener('click', function () {
var text = (pre.innerText || pre.textContent || '').replace(/\n+$/, '');
copyText(text).then(function () {
btn.textContent = '已复制 ✓';
btn.classList.add('is-done');
window.setTimeout(function () {
btn.textContent = '复制';
btn.classList.remove('is-done');
}, 1600);
}).catch(function () {
btn.textContent = '复制失败';
window.setTimeout(function () { btn.textContent = '复制'; }, 1600);
});
});
}
if (postBody) {
[].slice.call(postBody.querySelectorAll('pre')).forEach(enhanceCode);
}
/* ---------- 4.5 语法高亮(highlight.js 异步加载,加载失败则保持纯文本) ---------- */
function highlightCode() {
if (!window.hljs) return;
[].slice.call(document.querySelectorAll('.post-body pre code')).forEach(function (code) {
try { window.hljs.highlightElement(code); } catch (err) {}
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', highlightCode);
} else {
highlightCode();
}
/* ---------- 5. 表格横向滚动 ---------- */
if (postBody) {
[].slice.call(postBody.querySelectorAll('table')).forEach(function (table) {
if (table.parentNode && table.parentNode.classList.contains('table-wrap')) return;
var wrap = document.createElement('div');
wrap.className = 'table-wrap';
table.parentNode.insertBefore(wrap, table);
wrap.appendChild(table);
});
}
/* ---------- 6. 图片灯箱 ---------- */
var lightbox = document.createElement('div');
lightbox.className = 'lightbox';
lightbox.hidden = true;
lightbox.setAttribute('role', 'dialog');
lightbox.setAttribute('aria-modal', 'true');
lightbox.setAttribute('aria-label', '图片预览');
lightbox.innerHTML =
'<button class="lb-close" type="button" aria-label="关闭预览">✕</button>' +
'<figure><img alt=""><figcaption></figcaption></figure>';
var lbImg = lightbox.querySelector('img');
var lbCap = lightbox.querySelector('figcaption');
document.body.appendChild(lightbox);
function openLightbox(src, caption) {
lbImg.src = src;
lbCap.textContent = caption && caption.toLowerCase() !== 'file' ? caption : '';
lightbox.hidden = false;
bodyEl.classList.add('no-scroll');
root.classList.add('no-scroll');
lightbox.querySelector('.lb-close').focus();
}
function closeLightbox() {
lightbox.hidden = true;
lbImg.removeAttribute('src');
bodyEl.classList.remove('no-scroll');
root.classList.remove('no-scroll');
}
if (postBody) {
postBody.addEventListener('click', function (e) {
var img = e.target.closest('img');
if (!img) return;
e.preventDefault();
openLightbox(img.currentSrc || img.src, img.getAttribute('alt') || '');
});
}
lightbox.addEventListener('click', function (e) {
if (e.target === lbImg) return;
closeLightbox();
});
/* ---------- 7. 键盘:← → 翻篇,Esc 关灯箱 ---------- */
var prevLink = document.querySelector('.pager-item[data-nav="prev"]');
var nextLink = document.querySelector('.pager-item[data-nav="next"]');
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape' && !lightbox.hidden) {
closeLightbox();
return;
}
if (e.metaKey || e.ctrlKey || e.altKey || e.shiftKey) return;
var t = e.target;
if (t && t.closest && t.closest('input, textarea, select, [contenteditable="true"]')) return;
if (!lightbox.hidden) return;
if (e.key === 'ArrowLeft' && prevLink) {
window.location.href = prevLink.getAttribute('href');
} else if (e.key === 'ArrowRight' && nextLink) {
window.location.href = nextLink.getAttribute('href');
}
});
/* ---------- 8. 外链新窗口 ---------- */
if (postBody) {
[].slice.call(postBody.querySelectorAll('a[href]')).forEach(function (a) {
if (/^https?:/i.test(a.href) && a.host !== window.location.host) {
a.target = '_blank';
a.rel = 'noopener noreferrer';
}
});
}
/* ---------- 启动 ---------- */
window.addEventListener('scroll', onScroll, { passive: true });
window.addEventListener('resize', function () {
syncToc();
onScroll();
});
syncToc();
updateScrollUI();
})();
+13
View File
@@ -42,6 +42,13 @@
padding: 0 1.5rem;
}
.container-wide {
max-width: 1400px;
margin: 0 auto;
padding: 0 1.5rem;
}
/* ===== 头部 ===== */
header {
padding: 3rem 0 2rem;
@@ -256,6 +263,7 @@
article h1 { font-size: 1.35rem; }
}
</style>
{% block extra_css %}{% endblock %}
</head>
<body>
<div class="container">
@@ -264,6 +272,7 @@
<nav>
<a href="/">首页</a>
<a href="/archive/">归档</a>
<a href="/mindmaps/">脑图</a>
<a href="/about/">关于</a>
</nav>
</header>
@@ -276,6 +285,9 @@
<p>© 2024 郭安的小站 · 用 Django 构建</p>
</footer>
</div>
<div class="container-wide">
{% block wide_content %}{% endblock %}
</div>
<!-- highlight.js 核心脚本 -->
<script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/highlight.min.js"></script>
@@ -286,5 +298,6 @@
});
});
</script>
{% block extra_js %}{% endblock %}
</body>
</html>
+197
View File
@@ -0,0 +1,197 @@
{% load static %}
<!DOCTYPE html>
<html lang="zh-CN" data-theme="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
<title>思维导航 · 我的博客</title>
<!-- <link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> -->
<!-- <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@500;700;900&family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400&display=swap" rel="stylesheet"> -->
<link rel="preconnect" href="https://fonts.loli.net">
<link rel="preconnect" href="https://gstatic.loli.net" crossorigin>
<link href="https://fonts.loli.net/css2?family=Noto+Serif+SC:wght@500;700;900&family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400&display=swap" rel="stylesheet">
<!-- 全局基础样式(项目级) -->
<link rel="stylesheet" href="{% static 'blog/css/style.css' %}">
<!-- 让子模板可以追加自己的 CSS -->
{% block extra_css %}{% endblock %}
</head>
<body>
<!-- 🎬 开场引导层:道生一,一生二,二生三,三生万物
自动约 4.6s,点击任意处 / 任意键 / 跳过按钮可提前结束 -->
<div class="intro" id="intro" role="dialog" aria-label="欢迎">
<div class="intro-inner">
<div class="intro-seed">
<svg class="seed-svg" viewBox="0 0 240 240" fill="none" aria-hidden="true">
<defs>
<!-- 渐变色全部由 CSS 变量控制,深浅主题自动适配 -->
<linearGradient id="sgVine" x1="120" y1="200" x2="120" y2="40" gradientUnits="userSpaceOnUse">
<stop class="sgVine-a" offset="0"/>
<stop class="sgVine-b" offset="1"/>
</linearGradient>
<radialGradient id="sgNode" cx=".35" cy=".35" r=".85">
<stop class="sgNode-a" offset="0"/>
<stop class="sgNode-b" offset="1"/>
</radialGradient>
<radialGradient id="sgRoot" cx=".4" cy=".4" r=".8">
<stop class="sgRoot-a" offset="0"/>
<stop class="sgRoot-b" offset=".55"/>
<stop class="sgRoot-c" offset="1"/>
</radialGradient>
<radialGradient id="sgHalo">
<stop class="sgHalo-a" offset="0"/>
<stop class="sgHalo-b" offset="1"/>
</radialGradient>
</defs>
<!-- ✦ 缓旋虚线轨道:包裹整个生成的宇宙 -->
<g class="orbit">
<circle cx="120" cy="126" r="106" pathLength="1"/>
</g>
<!-- ✦ 根部(道)的呼吸光晕与声呐 -->
<circle class="halo" cx="120" cy="192" r="24"/>
<circle class="sonar s-a" cx="120" cy="192" r="12"/>
<circle class="sonar s-b" cx="120" cy="192" r="12"/>
<!-- ✦ 道生一:无形中生出第一缕有 -->
<path class="sl g1" id="sgP1" pathLength="1" d="M120 192 C 120 178 120 164 120 152"/>
<!-- ✦ 一生二:阴阳两仪 -->
<path class="sl g2" id="sgP2a" pathLength="1" d="M120 152 C 108 138 96 126 86 114"/>
<path class="sl g2" pathLength="1" d="M120 152 C 132 138 144 126 154 114"/>
<!-- ✦ 二生三:冲气以为和,三才既立 -->
<path class="sl g3" pathLength="1" d="M86 114 C 76 102 68 92 62 80"/>
<path class="sl g3" id="sgP3" pathLength="1" d="M120 138 C 134 126 132 104 120 86"/>
<path class="sl g3" pathLength="1" d="M154 114 C 164 102 172 92 178 80"/>
<!-- ✦ 三生万物:九枝散叶,生生不息 -->
<path class="twig tw1" pathLength="1" d="M62 80 C 56 72 50 66 44 58"/>
<path class="twig tw2" pathLength="1" d="M62 80 C 62 70 60 62 58 52"/>
<path class="twig tw3" pathLength="1" d="M62 80 C 68 72 72 64 76 58"/>
<path class="twig tw4" pathLength="1" d="M120 84 C 114 74 108 66 104 60"/>
<path class="twig tw5" pathLength="1" d="M120 84 C 120 74 120 64 120 54"/>
<path class="twig tw6" pathLength="1" d="M120 84 C 126 74 132 66 136 60"/>
<path class="twig tw7" pathLength="1" d="M178 80 C 184 72 190 66 196 58"/>
<path class="twig tw8" pathLength="1" d="M178 80 C 178 70 180 62 182 52"/>
<path class="twig tw9" pathLength="1" d="M178 80 C 172 72 168 64 164 58"/>
<!-- ✦ 光尘:散落的时光正被拾起 -->
<circle class="dust" cx="70" cy="170" r="1.2" style="animation-delay:.9s"/>
<circle class="dust" cx="176" cy="150" r="1" style="animation-delay:2.2s"/>
<circle class="dust" cx="48" cy="100" r="1.1" style="animation-delay:3.3s"/>
<circle class="dust" cx="196" cy="96" r=".9" style="animation-delay:3.9s"/>
<!-- ✦ 流光:沿生成之路巡游的光点 -->
<circle class="spark" r="2.4">
<animateMotion dur="2.4s" begin="1s" repeatCount="indefinite"><mpath href="#sgP1"/></animateMotion>
</circle>
<circle class="spark" r="2">
<animateMotion dur="2.6s" begin="2.1s" repeatCount="indefinite"><mpath href="#sgP2a"/></animateMotion>
</circle>
<circle class="spark" r="1.8">
<animateMotion dur="2.4s" begin="2.8s" repeatCount="indefinite"><mpath href="#sgP3"/></animateMotion>
</circle>
<!-- ✦ 节点:道 → 一 → 二(阴/阳)→ 三 -->
<circle class="sn root" cx="120" cy="192" r="8"/>
<circle class="sn n1" cx="120" cy="152" r="5.5"/>
<circle class="sn n2 yin" cx="86" cy="114" r="5"/>
<circle class="sn n2 yang" cx="154" cy="114" r="5"/>
<circle class="sn n3" cx="62" cy="80" r="4.5"/>
<circle class="sn n3" cx="120" cy="86" r="4.5"/>
<circle class="sn n3" cx="178" cy="80" r="4.5"/>
<!-- ✦ 万物之叶 -->
<circle class="lf lf1" cx="44" cy="58" r="2.4"/>
<circle class="lf lf2" cx="58" cy="52" r="2.4"/>
<circle class="lf lf3" cx="76" cy="58" r="2.4"/>
<circle class="lf lf4" cx="104" cy="60" r="2.4"/>
<circle class="lf lf5" cx="120" cy="54" r="2.4"/>
<circle class="lf lf6" cx="136" cy="60" r="2.4"/>
<circle class="lf lf7" cx="164" cy="58" r="2.4"/>
<circle class="lf lf8" cx="182" cy="52" r="2.4"/>
<circle class="lf lf9" cx="196" cy="58" r="2.4"/>
<!-- ✦ 节点铭文 -->
<text class="lbl l-dao" x="120" y="216" text-anchor="middle">道</text>
<text class="lbl l-yi" x="133" y="156">一</text>
<text class="lbl l-er" x="120" y="103" text-anchor="middle">二</text>
<text class="lbl l-san" x="136" y="78">三</text>
<text class="lbl l-wan" x="120" y="38" text-anchor="middle">万物</text>
</svg>
</div>
<div class="tao-phase" aria-hidden="true">
<span>道生一</span><span>一生二</span><span>二生三</span><span>三生万物</span>
</div>
<h1 class="intro-title">拾光</h1>
<p class="intro-sub">把每一次思考 · 织成会生长的网</p>
<div class="intro-divider" aria-hidden="true"><i></i><b>✦</b><i></i></div>
<div class="intro-stats">
<div class="stat"><b data-stat="posts">{{total_posts}}</b><span>篇文章</span></div>
<div class="stat"><b data-stat="cats">{{total_categories}}</b><span>大分类</span></div>
<div class="stat"><b data-stat="subs">{{mindmap_count}}</b><span>知识图谱</span></div>
</div>
<div class="intro-progress"><i></i></div>
<p class="intro-hint">正在展开思维图谱</p>
</div>
<button class="intro-skip" id="btnSkipIntro">跳过 SKIP →</button>
</div>
<div class="aurora"><div class="blob-c"></div></div>
<header>
<div class="brand">
<div class="brand-mark">思</div>
<div class="brand-text">
<h1>拾光</h1>
<p>MIND MAP · BLOG</p>
</div>
</div>
<div class="top-actions">
<button class="icon-btn" id="btnSearch" title="搜索 (Ctrl+K)">⌕</button>
<button class="icon-btn" id="btnTheme" title="切换主题">◐</button>
</div>
</header>
<div class="search-box" id="searchBox">
<span style="color:var(--ink-faint); font-size:13px;">⌕</span>
<input id="searchInput" type="text" placeholder="搜索分类或文章…">
<kbd>ESC</kbd>
</div>
<div id="mindmap-wrap"><svg id="mindmap"></svg></div>
<div class="toolbar">
<button class="icon-btn" id="btnFit" title="自适应">⛶</button>
<button class="icon-btn" id="btnIn" title="放大">+</button>
<button class="icon-btn" id="btnOut" title="缩小">-</button>
<button class="icon-btn" id="btnFs" title="全屏">❐</button>
</div>
<footer>
<span>© 2026 我的博客</span>
<span class="dot"></span>
<span>共 18 篇文章</span>
<span class="dot"></span>
<span>Powered by xiaoan</span>
</footer>
<script src="{% static 'blog/js/d3.min.js' %}"></script>
<script src="{% static 'blog/js/index.js' %}"></script>
<script src="{% static 'blog/js/index.iife.js' %}"></script>
<!-- <script src="https://cdn.jsdelivr.net/npm/d3@7/dist/d3.min.js"></script> -->
<!-- <script src="https://cdn.jsdelivr.net/npm/markmap-view@0.18.10/dist/browser/index.js"></script> -->
<!-- <script src="https://cdn.jsdelivr.net/npm/markmap-lib@0.18.12/dist/browser/index.iife.js"></script> -->
<!-- <script src="https://cdn.jsdmirror.com/npm/d3@7/dist/d3.min.js"></script>
<script src="https://cdn.jsdmirror.com/npm/markmap-view@0.18.10/dist/browser/index.js"></script>
<script src="https://cdn.jsdmirror.com/npm/markmap-lib@0.18.12/dist/browser/index.iife.js"></script> -->
<script type="module" src="{% static 'blog/js/main.js' %}"></script>
<!-- 让子模板可以追加自己的 JS -->
{% block extra_js %}{% endblock %}
</body>
</html>
+73
View File
@@ -0,0 +1,73 @@
{% load static %}
<!DOCTYPE html>
<html lang="zh-CN" data-theme="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
<meta name="color-scheme" content="light dark">
<title>{% block title %}拾光{% endblock %}</title>
<meta name="description" content="{% block description %}把每一次思考 · 织成会生长的网{% endblock %}">
<!-- 主题预置:在样式生效前定好明暗,避免闪烁(键名与首页一致) -->
<script>
(function () {
var t = 'light';
try { t = localStorage.getItem('theme') || 'light'; } catch (e) {}
document.documentElement.dataset.theme = (t === 'dark') ? 'dark' : 'light';
})();
</script>
<link rel="preconnect" href="https://fonts.loli.net">
<link rel="preconnect" href="https://gstatic.loli.net" crossorigin>
<link href="https://fonts.loli.net/css2?family=Noto+Serif+SC:wght@500;600;700;900&family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="{% static 'blog/css/reading.css' %}">
<!-- 代码高亮(深色代码块配套主题) -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/styles/github-dark.min.css">
{% block extra_css %}{% endblock %}
</head>
<body>
<a class="skip-link" href="#article">跳到正文</a>
<div class="page-glow" aria-hidden="true"><i></i><i></i><i></i></div>
<div class="read-progress" id="readProgress" aria-hidden="true"><i></i></div>
<header class="site-head" id="siteHead">
<a class="brand" href="/" aria-label="拾光 · 返回思维导航">
<span class="brand-mark" aria-hidden="true">思</span>
<span class="brand-text">
<b>拾光</b>
<small>MIND MAP · READING</small>
</span>
</a>
<div class="head-actions">
<a class="btn-map" href="/" title="返回思维导图">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"
stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M19 12H5M11 6l-6 6 6 6"/>
</svg>
<span>返回导图</span>
</a>
<button class="icon-btn" id="btnTheme" type="button" aria-label="切换明暗主题" title="切换主题(明 / 暗)">◐</button>
</div>
</header>
<main class="reading" id="article">
{% block content %}{% endblock %}
</main>
<!-- 侧栏目录:由 reading.js 根据正文标题生成 -->
<aside class="toc" id="toc" hidden aria-label="本篇目录">
<p class="toc-title"><span>✦</span>本篇目录</p>
<ol class="toc-list"></ol>
</aside>
<footer class="site-foot">
<p>© 2026 拾光<span class="dot"></span>字句织网 · 思绪成图</p>
</footer>
<script defer src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/highlight.min.js"></script>
<script src="{% static 'blog/js/reading.js' %}"></script>
{% block extra_js %}{% endblock %}
</body>
</html>
+148
View File
@@ -0,0 +1,148 @@
{% extends "base.html" %}
{% block title %}{{ mindmap.title }}{% endblock %}
{% block extra_css %}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/simple-mind-map@0.10.0/dist/style.css" />
<style>
#mindmap-wrapper {
position: relative;
margin-top: 1.5rem;
width: 100vw;
margin-left: calc(-50vw + 50%);
}
#mindmap-container {
width: 100% !important;
height: 90vh !important;
min-height: 700px !important;
border: 1px solid #e0e0e0;
border-radius: 6px;
display: block !important;
position: relative;
overflow: hidden;
background: #fff;
}
#mindmap-container svg {
width: 100% !important;
height: 100% !important;
}
#fullscreen-btn {
position: absolute;
top: 10px;
right: 10px;
z-index: 100;
padding: 6px 14px;
background: #333;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 13px;
font-family: -apple-system, "Noto Sans SC", sans-serif;
}
#fullscreen-btn:hover {
background: #555;
}
#mindmap-container:fullscreen {
width: 100vw !important;
height: 100vh !important;
border-radius: 0;
}
</style>
{% endblock %}
{% block wide_content %}
<h1>{{ mindmap.title }}</h1>
{% if mindmap.description %}
<p style="color: var(--text-light); margin-bottom: 1rem;">{{ mindmap.description }}</p>
{% endif %}
<div id="mindmap-wrapper">
<button id="fullscreen-btn">全屏</button>
<div id="mindmap-container"></div>
</div>
<script src="https://cdn.jsdelivr.net/npm/simple-mind-map@0.10.0/dist/simpleMindMap.umd.min.js"></script>
<script>
(function () {
function init() {
var el = document.getElementById('mindmap-container');
if (!el) return;
// ✅ 强制容器尺寸先生效
el.style.width = '100%';
el.style.height = '90vh';
el.style.display = 'block';
// ✅ 等一帧让浏览器 reflow
requestAnimationFrame(function () {
// 这时候 el.clientWidth 应该是 1400px 左右了
var raw = {{ mindmap.mindmap_data|safe }};
function adapt(node) {
if (!node) return null;
if (node.topic !== undefined) {
var result = { data: { text: node.topic } };
if (node.children && node.children.length) {
result.children = node.children.map(adapt).filter(Boolean);
}
return result;
}
if (node.data && node.data.text) {
var result2 = { data: { text: node.data.text } };
if (node.children && node.children.length) {
result2.children = node.children.map(adapt).filter(Boolean);
}
return result2;
}
return null;
}
var mindData;
if (raw.data && raw.data.topic !== undefined) {
mindData = adapt(raw.data);
} else if (raw.data && raw.data.text) {
mindData = adapt(raw);
} else {
return;
}
var MindMap = window.simpleMindMap && window.simpleMindMap.default;
if (!MindMap) return;
new MindMap({
el: el,
data: mindData,
readonly: true,
layout: 'logicalStructure',
theme: 'default',
scale: 1.5,
maxScale: 3,
minScale: 0.3,
fit: false,
center: true
});
// ✅ 初始化完再强制改一次 SVG 尺寸
var svg = el.querySelector('svg');
if (svg) {
svg.style.width = el.clientWidth + 'px';
svg.style.height = el.clientHeight + 'px';
}
});
}
// DOM ready 后执行
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
setTimeout(init, 100);
}
})();
</script>
{% endblock %}
+14
View File
@@ -0,0 +1,14 @@
{% extends "base.html" %}
{% block content %}
<h1>脑图笔记</h1>
<ul class="mindmap-list">
{% for m in mindmaps %}
<li>
<a href="{{ m.get_absolute_url }}">{{ m.title }}</a>
<p>{{ m.description }}</p>
</li>
{% empty %}
<li>还没有脑图,去后台导入吧。</li>
{% endfor %}
</ul>
{% endblock %}
+82 -27
View File
@@ -1,33 +1,88 @@
{% extends "base.html" %}
{% load static %}
{% extends "base_content.html" %}
{% block title %}{{ post.title }} - 人,是一根会思考的芦苇{% endblock %}
{% block title %}{{ post.title }} · 拾光{% endblock %}
{% block description %}{{ post.title }}{% endblock %}
{% block content %}
<article>
<h1>{{ post.title }}</h1>
<div class="article-meta">
<span>{{ post.published_at|date:"Y年m月d日 H:i" }}</span>
{% if post.category %}
<span><a href="/category/{{ post.category.slug }}/" style="color: var(--text-muted); text-decoration: none;">{{ post.category.name }}</a></span>
{% endif %}
</div>
<article class="article">
<div class="post-body">
{{ post.content|safe }}
</div>
<header class="article-head">
{% if post.categories.all %}
<div class="article-cats">
{% for cat in post.categories.all %}
<a class="cat-chip" href="{{ cat.get_absolute_url }}">{{ cat.name }}</a>
{% endfor %}
</div>
{% endif %}
{% if post.tags.all %}
<div class="tags">
🏷
{% for tag in post.tags.all %}
<a href="/tag/{{ tag.slug }}/">{{ tag.name }}</a>
{% endfor %}
</div>
{% endif %}
<h1 class="article-title">{{ post.title }}</h1>
<div style="margin-top: 3rem; padding-top: 1.5rem; border-top: 1px solid var(--border); font-size: 0.85rem; color: var(--text-muted); font-family: -apple-system, 'Noto Sans SC', sans-serif;">
<a href="/" style="color: var(--text-light); text-decoration: none;">← 返回首页</a>
</div>
</article>
{% endblock %}
{% if post.excerpt %}
<p class="article-lede">{{ post.excerpt|striptags }}</p>
{% endif %}
<div class="article-meta">
<span class="meta-item">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"
stroke-linecap="round" aria-hidden="true">
<rect x="3.5" y="5" width="17" height="15.5" rx="3"/>
<path d="M8 3.5v3M16 3.5v3M3.5 10h17"/>
</svg>
{{ post.published_at|date:"Y年n月j日" }}
</span>
<i class="dot" aria-hidden="true"></i>
<span class="meta-item">{{ char_count }} 字</span>
<i class="dot" aria-hidden="true"></i>
<span class="meta-item">约 {{ read_minutes }} 分钟读完</span>
</div>
<div class="article-orn" aria-hidden="true"><i></i><b>❋</b><i></i></div>
</header>
<!-- 窄屏折叠目录(内容由 reading.js 生成) -->
<details class="toc-mobile" id="tocMobile" hidden>
<summary>本篇目录</summary>
<ol class="toc-list"></ol>
</details>
<div class="article-card">
<div class="post-body" id="postBody">
{{ post.content|safe }}
</div>
{% if post.tags.all %}
<div class="article-tags">
<span class="tags-label">❋ 拾遗</span>
{% for tag in post.tags.all %}
<a class="tag-chip" href="{% url 'blog:tag_detail' slug=tag.slug %}"># {{ tag.name }}</a>
{% endfor %}
</div>
{% endif %}
</div>
<nav class="pager" aria-label="上一篇 / 下一篇">
{% if prev_post %}
<a class="pager-item prev" href="{{ prev_post.get_absolute_url }}" data-nav="prev">
<span class="pager-k">← 上一篇</span>
<span class="pager-t">{{ prev_post.title }}</span>
</a>
{% else %}
<span class="pager-item is-empty" aria-hidden="true"></span>
{% endif %}
{% if next_post %}
<a class="pager-item next" href="{{ next_post.get_absolute_url }}" data-nav="next">
<span class="pager-k">下一篇 →</span>
<span class="pager-t">{{ next_post.title }}</span>
</a>
{% else %}
<span class="pager-item is-empty" aria-hidden="true"></span>
{% endif %}
</nav>
<div class="article-foot">
<a class="btn-back" href="/">← 返回思维导航</a>
<span class="foot-note">字句织网 · 思绪成图</span>
</div>
</article>
{% endblock %}
+74 -11
View File
@@ -1,21 +1,53 @@
import math
import re
from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator
from django.utils.html import strip_tags
from .models import Category, Post, Tag , SiteInfo
from mindmaps.models import MindMap
def category_list(request):
"""首页:展示所有分类"""
category_list = Category.objects.all()
# """首页:展示所有分类"""
# category_list = Category.objects.all()
paginator = Paginator(category_list, 6) # 每页 10 个分类
page_number = request.GET.get('page')
categories = paginator.get_page(page_number)
# paginator = Paginator(category_list, 6) # 每页 10 个分类
# page_number = request.GET.get('page')
# categories = paginator.get_page(page_number)
### 第二版new
# ===== 新增:文章数量 & 分类数量 =====
total_posts = Post.objects.filter(status='published').count() # 已发布文章总数
total_categories = Category.objects.count() # 分类总数
mindmap_count = MindMap.objects.count() # 脑图数量
# ===== 新增:最新文章(取前5篇)=====
# latest_posts = Post.objects.filter(
# status='published'
# ).prefetch_related('categories', 'tags')[:5]
return render(request, 'category_list.html', {
'categories': categories,
# ===== 新增:站点信息 =====
#site_info = SiteInfo.get_site_info()
# ===== 新增:每个分类各有多少篇文章(用于侧边栏/首页展示)=====
# categories_with_count = Category.objects.annotate(
# post_count=Count(
# 'posts',
# filter=models.Q(posts__status='published')
# )
# ).filter(post_count__gt=0).order_by('-post_count')
return render(request, 'base2.html', {
# 'categories': categories,
'total_posts': total_posts, # 文章总数
'total_categories': total_categories, # 分类总数
'mindmap_count' : mindmap_count
})
def category_detail(request, slug):
"""分类详情:该分类下的文章列表"""
category = get_object_or_404(Category, slug=slug)
@@ -32,9 +64,39 @@ def category_detail(request, slug):
def post_detail(request, slug):
"""文章详情"""
post = get_object_or_404(Post, slug=slug, status='published')
return render(request, 'post_detail.html', {'post': post})
"""文章详情:正文 + 上下篇 + 字数/阅读时长"""
post = get_object_or_404(
Post.objects.prefetch_related('categories', 'tags'),
slug=slug,
status='published',
)
# 同一时间轴上的已发布文章,按(发布时间, id)排序后取相邻两篇
published_ids = list(
Post.objects.filter(status='published')
.order_by('published_at', 'id')
.values_list('id', flat=True)
)
prev_post = next_post = None
if post.id in published_ids:
index = published_ids.index(post.id)
if index > 0:
prev_post = Post.objects.filter(id=published_ids[index - 1]).first()
if index < len(published_ids) - 1:
next_post = Post.objects.filter(id=published_ids[index + 1]).first()
# 阅读统计:先去掉 HTML 标签,再按非空白字符计数
plain_text = strip_tags(post.content or '')
char_count = len(re.sub(r'\s+', '', plain_text))
read_minutes = max(1, math.ceil(char_count / 400))
return render(request, 'post_detail.html', {
'post': post,
'prev_post': prev_post,
'next_post': next_post,
'char_count': char_count,
'read_minutes': read_minutes,
})
def tag_detail(request, slug):
@@ -49,6 +111,7 @@ def tag_detail(request, slug):
return render(request, 'tag_detail.html', {
'tag': tag,
'posts': posts,
"container_wide": True,
})
def about_page(request):
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+34
View File
@@ -38,8 +38,38 @@ INSTALLED_APPS = [
"django.contrib.messages",
"django.contrib.staticfiles",
"blog",
"mindmaps",
"api",
"rest_framework",
]
# myproject/settings.py
REST_FRAMEWORK = {
# ① 权限:开发阶段先允许任何人访问,上线再改成登录
"DEFAULT_PERMISSION_CLASSES": [
"rest_framework.permissions.AllowAny",
# 上线建议换成下面这种:登录用户可读写,匿名只能读
# "rest_framework.permissions.IsAuthenticatedOrReadOnly",
],
# ② 分页:列表接口自动分页,避免一次返回几万条
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
"PAGE_SIZE": 10, # 每页 10 条
# ③ 渲染:开发期保留可浏览 API 页面,生产环境可去掉 BrowsableAPIRenderer
"DEFAULT_RENDERER_CLASSES": [
"rest_framework.renderers.JSONRenderer",
"rest_framework.renderers.BrowsableAPIRenderer", # 浏览器里能直接调试
],
# ④ 过滤后端(需要 pip install django-filter)
"DEFAULT_FILTER_BACKENDS": [
"rest_framework.filters.SearchFilter",
"rest_framework.filters.OrderingFilter",
],
}
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
@@ -153,6 +183,10 @@ USE_TZ = True
STATIC_URL = "static/"
STATICFILES_DIRS = [
BASE_DIR / "static", # 项目根 static 目录
]
# Default primary key field type
# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field
+2
View File
@@ -34,6 +34,8 @@ urlpatterns = [
# 空字符串表示挂载到根路径
# 比如 blog/urls.py 里定义了 '' → 实际访问 /
path('', include('blog.urls')),
path("mindmaps/", include("mindmaps.urls")),
path("api/",include("api.urls")),
]
# 开发环境下,让 Django 提供 media 文件的访问
View File
+29
View File
@@ -0,0 +1,29 @@
from django.contrib import admin
from django import forms
from .models import MindMap
@admin.register(MindMap)
class MindMapAdmin(admin.ModelAdmin):
list_display = ("title", "created_at", "has_mindmap")
search_fields = ("title",)
prepopulated_fields = {"slug": ("title",)}
readonly_fields = ("updated_at",)
def has_mindmap(self, obj):
return bool(obj.mindmap_data and obj.mindmap_data.get("data"))
has_mindmap.boolean = True
has_mindmap.short_description = "已解析"
def save_model(self, request, obj, form, change):
is_new = not obj.pk
super().save_model(request, obj, form, change)
if "xmind_file" in form.changed_data and obj.xmind_file:
try:
obj.parse_and_store(obj.xmind_file.path)
self.message_user(request, f"脑图「{obj.title}」解析成功")
except Exception as e:
self.message_user(
request, f"解析失败: {e}", level="error"
)
+6
View File
@@ -0,0 +1,6 @@
from django.apps import AppConfig
class MindmapsConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "mindmaps"
+70
View File
@@ -0,0 +1,70 @@
# Generated by Django 4.2 on 2026-10-20 09:54
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="MindMap",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("title", models.CharField(max_length=200, verbose_name="标题")),
(
"slug",
models.SlugField(
blank=True, max_length=200, unique=True, verbose_name="别名"
),
),
(
"description",
models.TextField(
blank=True, help_text="列表页显示", verbose_name="简介"
),
),
(
"xmind_file",
models.FileField(
blank=True,
upload_to="mindmaps/xmind/%Y/%m/",
verbose_name="XMind 文件",
),
),
(
"mindmap_data",
models.JSONField(
blank=True,
default=dict,
help_text="由 xmind 解析后生成的前端渲染数据",
verbose_name="脑图数据",
),
),
(
"created_at",
models.DateTimeField(auto_now_add=True, verbose_name="创建时间"),
),
(
"updated_at",
models.DateTimeField(auto_now=True, verbose_name="更新时间"),
),
],
options={
"verbose_name": "脑图",
"verbose_name_plural": "脑图",
"ordering": ["-created_at"],
},
),
]
View File
+68
View File
@@ -0,0 +1,68 @@
import json
from django.db import models
from django.utils.text import slugify
from django.urls import reverse # ← 加这个 import
from xmindparser import xmind_to_dict
def xmind_to_mindmap_format(parsed_data):
"""
把 xmindparser 输出转成 simple-mind-map 标准格式
"""
if not parsed_data:
raise ValueError("XMind 文件内容为空")
sheet = parsed_data[0]
if "topic" not in sheet:
raise ValueError("XMind 第一个画布没有根节点")
def conv(topic):
"""递归转换节点"""
node = {
"data": {
"text": topic.get("title", "(无标题)")
}
}
subs = topic.get("topics") or []
if subs:
node["children"] = [conv(t) for t in subs]
return node
return conv(sheet["topic"])
class MindMap(models.Model):
title = models.CharField("标题", max_length=200)
slug = models.SlugField("别名", max_length=200, unique=True, blank=True)
description = models.TextField("简介", blank=True, help_text="列表页显示")
xmind_file = models.FileField(
"XMind 文件", upload_to="mindmaps/xmind/%Y/%m/", blank=True
)
mindmap_data = models.JSONField(
"脑图数据", default=dict, blank=True,
help_text="由 xmind 解析后生成的前端渲染数据"
)
created_at = models.DateTimeField("创建时间", auto_now_add=True)
updated_at = models.DateTimeField("更新时间", auto_now=True)
class Meta:
ordering = ["-created_at"]
verbose_name = "脑图"
verbose_name_plural = "脑图"
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("mindmaps:detail", args=[self.slug])
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title) or f"mindmap-{self.pk or 'new'}"
super().save(*args, **kwargs)
def parse_and_store(self, file_path):
"""解析 xmind 文件并存储为前端可用格式"""
parsed = xmind_to_dict(file_path)
self.mindmap_data = xmind_to_mindmap_format(parsed)
self.save()
+3
View File
@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.
+8
View File
@@ -0,0 +1,8 @@
from django.urls import path
from . import views
app_name = "mindmaps"
urlpatterns = [
path("", views.mindmap_list, name="list"),
path("<slug:slug>/", views.mindmap_detail, name="detail"),
]
+14
View File
@@ -0,0 +1,14 @@
from django.shortcuts import render, get_object_or_404
from .models import MindMap
def mindmap_list(request):
mindmaps = MindMap.objects.filter(mindmap_data__isnull=False).exclude(
mindmap_data={}
)
return render(request, "mindlist.html", {"mindmaps": mindmaps})
def mindmap_detail(request, slug):
mm = get_object_or_404(MindMap, slug=slug)
return render(request, "minddetail.html", {"mindmap": mm})