加入「拾编」写作台:文章 / 分类管理 + Markdown 上传
- 新增 studio 应用与 /manage/ 写作台 - 文章增删改查、状态/分类/标签、搜索筛选分页 - 分类增删改查,支持父分类 - 直接上传 .md(front matter)并创建文章,编辑页支持 Markdown 导入 - Post 增加 content_format,公开文章页支持 Markdown 渲染 - 复用拾匣密码解锁;首页页脚新增写作台入口
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
# Generated by Django 5.2.18 on 2026-11-21 04:31
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("blog", "0003_siteinfo"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name="post",
|
||||
name="content_format",
|
||||
field=models.CharField(
|
||||
choices=[("html", "HTML"), ("markdown", "Markdown")],
|
||||
default="html",
|
||||
max_length=20,
|
||||
verbose_name="内容格式",
|
||||
),
|
||||
),
|
||||
]
|
||||
@@ -110,6 +110,17 @@ class Post(models.Model):
|
||||
|
||||
# 文章内容(经典编辑器是 HTML,Markdown 插件的话可能是 md 源码)
|
||||
content = models.TextField(verbose_name='内容')
|
||||
|
||||
CONTENT_FORMAT_CHOICES = [
|
||||
('html', 'HTML'),
|
||||
('markdown', 'Markdown'),
|
||||
]
|
||||
content_format = models.CharField(
|
||||
max_length=20,
|
||||
choices=CONTENT_FORMAT_CHOICES,
|
||||
default='html',
|
||||
verbose_name='内容格式',
|
||||
)
|
||||
|
||||
excerpt = models.TextField(
|
||||
blank=True,
|
||||
@@ -163,6 +174,21 @@ class Post(models.Model):
|
||||
def get_absolute_url(self):
|
||||
return reverse('blog:post_detail', kwargs={'slug': self.slug})
|
||||
|
||||
@property
|
||||
def rendered_content(self):
|
||||
"""按 content_format 渲染正文;原有 HTML 文章保持原样。"""
|
||||
if self.content_format == 'markdown':
|
||||
try:
|
||||
import markdown
|
||||
except ImportError:
|
||||
return self.content or ''
|
||||
return markdown.markdown(
|
||||
self.content or '',
|
||||
extensions=['extra', 'sane_lists', 'toc'],
|
||||
output_format='html5',
|
||||
)
|
||||
return self.content or ''
|
||||
|
||||
|
||||
class SiteInfo(models.Model):
|
||||
"""
|
||||
|
||||
@@ -115,6 +115,8 @@ footer {
|
||||
display:flex; align-items:center; gap:14px;
|
||||
}
|
||||
footer .dot { width:3px; height:3px; border-radius:50%; background:var(--ink-faint); }
|
||||
.footer-link { color:var(--ink-faint); text-decoration:none; letter-spacing:.5px; transition:color .18s ease; }
|
||||
.footer-link:hover { color:var(--accent); }
|
||||
|
||||
/* =========================================================
|
||||
脑图容器
|
||||
|
||||
@@ -181,6 +181,8 @@
|
||||
<!-- <span>共 18 篇文章</span> -->
|
||||
<span class="dot"></span>
|
||||
<span>Powered by xiaoan</span>
|
||||
<span class="dot"></span>
|
||||
<a class="footer-link" href="/manage/">写作台</a>
|
||||
</footer>
|
||||
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
<!-- 代码高亮(深色代码块配套主题) -->
|
||||
<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 %}
|
||||
{% block extra_head %}{% endblock %}
|
||||
</head>
|
||||
<body>
|
||||
<a class="skip-link" href="#article">跳到正文</a>
|
||||
|
||||
@@ -47,7 +47,7 @@
|
||||
|
||||
<div class="article-card">
|
||||
<div class="post-body" id="postBody">
|
||||
{{ post.content|safe }}
|
||||
{{ post.rendered_content|safe }}
|
||||
</div>
|
||||
|
||||
{% if post.tags.all %}
|
||||
|
||||
+1
-1
@@ -88,7 +88,7 @@ def post_detail(request, slug):
|
||||
next_post = Post.objects.filter(id=published_ids[index + 1]).first()
|
||||
|
||||
# 阅读统计:先去掉 HTML 标签,再按非空白字符计数
|
||||
plain_text = strip_tags(post.content or '')
|
||||
plain_text = strip_tags(post.rendered_content or '')
|
||||
char_count = len(re.sub(r'\s+', '', plain_text))
|
||||
read_minutes = max(1, math.ceil(char_count / 400))
|
||||
|
||||
|
||||
@@ -45,6 +45,7 @@ INSTALLED_APPS = [
|
||||
"cabinet",
|
||||
"reflections",
|
||||
"moments",
|
||||
"studio",
|
||||
"rest_framework",
|
||||
]
|
||||
|
||||
|
||||
@@ -36,6 +36,7 @@ urlpatterns = [
|
||||
path('files/', include('cabinet.urls')),
|
||||
path('reflections/', include('reflections.urls')),
|
||||
path('moments/', include('moments.urls')),
|
||||
path('manage/', include('studio.urls')),
|
||||
path('', include('blog.urls')),
|
||||
path("mindmaps/", include("mindmaps.urls")),
|
||||
path("api/",include("api.urls")),
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class StudioConfig(AppConfig):
|
||||
default_auto_field = "django.db.models.BigAutoField"
|
||||
name = "studio"
|
||||
verbose_name = "拾编"
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
from django import forms
|
||||
|
||||
from blog.models import Category, Post, Tag
|
||||
|
||||
from .utils import descendant_ids
|
||||
|
||||
|
||||
class PostForm(forms.Form):
|
||||
title = forms.CharField(
|
||||
max_length=200,
|
||||
label="标题",
|
||||
widget=forms.TextInput(attrs={
|
||||
"class": "st-input st-title-input",
|
||||
"placeholder": "文章标题",
|
||||
}),
|
||||
)
|
||||
slug = forms.CharField(
|
||||
required=False,
|
||||
max_length=200,
|
||||
label="URL 别名",
|
||||
widget=forms.TextInput(attrs={
|
||||
"class": "st-input",
|
||||
"placeholder": "留空自动生成,建议英文",
|
||||
}),
|
||||
)
|
||||
content = forms.CharField(
|
||||
label="正文",
|
||||
widget=forms.Textarea(attrs={
|
||||
"class": "st-input st-content",
|
||||
"rows": 24,
|
||||
"spellcheck": "false",
|
||||
"placeholder": "写点什么,或直接粘贴 / 导入 Markdown",
|
||||
}),
|
||||
)
|
||||
content_format = forms.ChoiceField(
|
||||
choices=Post.CONTENT_FORMAT_CHOICES,
|
||||
label="内容格式",
|
||||
widget=forms.Select(attrs={"class": "st-input"}),
|
||||
)
|
||||
excerpt = forms.CharField(
|
||||
required=False,
|
||||
label="摘要",
|
||||
widget=forms.Textarea(attrs={
|
||||
"class": "st-input",
|
||||
"rows": 3,
|
||||
"placeholder": "留空会从正文自动提取",
|
||||
}),
|
||||
)
|
||||
published_at = forms.DateTimeField(
|
||||
label="发布时间",
|
||||
input_formats=["%Y-%m-%dT%H:%M", "%Y-%m-%dT%H:%M:%S"],
|
||||
widget=forms.DateTimeInput(
|
||||
format="%Y-%m-%dT%H:%M",
|
||||
attrs={"class": "st-input", "type": "datetime-local"},
|
||||
),
|
||||
)
|
||||
status = forms.ChoiceField(
|
||||
choices=Post.STATUS_CHOICES,
|
||||
label="状态",
|
||||
widget=forms.Select(attrs={"class": "st-input"}),
|
||||
)
|
||||
categories = forms.ModelMultipleChoiceField(
|
||||
queryset=Category.objects.none(),
|
||||
required=False,
|
||||
label="分类",
|
||||
widget=forms.CheckboxSelectMultiple,
|
||||
)
|
||||
tags = forms.ModelMultipleChoiceField(
|
||||
queryset=Tag.objects.none(),
|
||||
required=False,
|
||||
label="标签",
|
||||
widget=forms.CheckboxSelectMultiple,
|
||||
)
|
||||
new_tags = forms.CharField(
|
||||
required=False,
|
||||
max_length=300,
|
||||
label="新标签",
|
||||
widget=forms.TextInput(attrs={
|
||||
"class": "st-input",
|
||||
"placeholder": "多个用逗号分隔",
|
||||
}),
|
||||
)
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields["categories"].queryset = Category.objects.order_by("name")
|
||||
self.fields["tags"].queryset = Tag.objects.order_by("name")
|
||||
|
||||
|
||||
class CategoryForm(forms.Form):
|
||||
id = forms.IntegerField(required=False, widget=forms.HiddenInput)
|
||||
name = forms.CharField(
|
||||
max_length=100,
|
||||
label="名称",
|
||||
widget=forms.TextInput(attrs={"class": "st-input", "placeholder": "分类名称"}),
|
||||
)
|
||||
slug = forms.CharField(
|
||||
required=False,
|
||||
max_length=100,
|
||||
label="URL 别名",
|
||||
widget=forms.TextInput(attrs={
|
||||
"class": "st-input",
|
||||
"placeholder": "留空自动生成,可中文",
|
||||
}),
|
||||
)
|
||||
description = forms.CharField(
|
||||
required=False,
|
||||
label="描述",
|
||||
widget=forms.Textarea(attrs={
|
||||
"class": "st-input",
|
||||
"rows": 2,
|
||||
"placeholder": "可选",
|
||||
}),
|
||||
)
|
||||
parent = forms.ModelChoiceField(
|
||||
queryset=Category.objects.none(),
|
||||
required=False,
|
||||
label="上级分类",
|
||||
empty_label="无上级分类",
|
||||
widget=forms.Select(attrs={"class": "st-input"}),
|
||||
)
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
edit_id = None
|
||||
if self.is_bound:
|
||||
try:
|
||||
edit_id = int(self.data.get("id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
edit_id = None
|
||||
elif self.initial.get("id"):
|
||||
try:
|
||||
edit_id = int(self.initial["id"])
|
||||
except (TypeError, ValueError):
|
||||
edit_id = None
|
||||
|
||||
queryset = Category.objects.order_by("name")
|
||||
if edit_id:
|
||||
category = Category.objects.filter(pk=edit_id).first()
|
||||
if category:
|
||||
queryset = queryset.exclude(
|
||||
pk__in={category.pk} | descendant_ids(category)
|
||||
)
|
||||
self.fields["parent"].queryset = queryset
|
||||
|
||||
|
||||
class MarkdownUploadForm(forms.Form):
|
||||
file = forms.FileField(
|
||||
label="Markdown 文件",
|
||||
widget=forms.ClearableFileInput(attrs={
|
||||
"accept": ".md,.markdown,text/markdown",
|
||||
}),
|
||||
)
|
||||
category = forms.ModelChoiceField(
|
||||
queryset=Category.objects.none(),
|
||||
required=False,
|
||||
label="归入分类",
|
||||
empty_label="不归入分类",
|
||||
widget=forms.Select(attrs={"class": "st-input"}),
|
||||
)
|
||||
status = forms.ChoiceField(
|
||||
choices=Post.STATUS_CHOICES,
|
||||
initial="draft",
|
||||
label="默认状态",
|
||||
widget=forms.Select(attrs={"class": "st-input"}),
|
||||
)
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields["category"].queryset = Category.objects.order_by("name")
|
||||
@@ -0,0 +1,721 @@
|
||||
/* =========================================================
|
||||
拾编 · 写作台
|
||||
========================================================= */
|
||||
|
||||
body {
|
||||
font-family: Inter, 'Noto Sans SC', -apple-system, 'PingFang SC', sans-serif;
|
||||
}
|
||||
main#article {
|
||||
max-width: 1180px;
|
||||
padding-top: clamp(84px, 11vh, 112px);
|
||||
padding-bottom: 80px;
|
||||
}
|
||||
.read-progress,
|
||||
.toc { display: none; }
|
||||
|
||||
.st {
|
||||
max-width: 1120px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
/* ---------- 顶部 ---------- */
|
||||
.st-head {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
justify-content: space-between;
|
||||
gap: 20px;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 22px;
|
||||
}
|
||||
.st-eyebrow {
|
||||
margin: 0 0 10px;
|
||||
color: var(--ink-faint);
|
||||
font-size: 10.5px;
|
||||
font-weight: 500;
|
||||
letter-spacing: .24em;
|
||||
}
|
||||
.st-eyebrow span { margin-right: 7px; color: var(--gold); font-size: 10px; }
|
||||
.st-head h1 {
|
||||
margin: 0 0 8px;
|
||||
color: var(--ink);
|
||||
font-family: 'Noto Serif SC', serif;
|
||||
font-size: clamp(1.8rem, 3.6vw, 2.5rem);
|
||||
font-weight: 900;
|
||||
line-height: 1.3;
|
||||
letter-spacing: .01em;
|
||||
}
|
||||
.st-sub { margin: 0; color: var(--ink-faint); font-size: 12.5px; line-height: 1.8; }
|
||||
.st-head-actions { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
|
||||
.st-back {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-bottom: 14px;
|
||||
color: var(--ink-faint);
|
||||
font-size: 12px;
|
||||
text-decoration: none;
|
||||
transition: color .2s ease;
|
||||
}
|
||||
.st-back:hover { color: var(--accent); }
|
||||
|
||||
/* ---------- 按钮 ---------- */
|
||||
.st-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
min-height: 32px;
|
||||
padding: 6px 14px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 9px;
|
||||
background: var(--paper);
|
||||
color: var(--ink-soft);
|
||||
font-family: inherit;
|
||||
font-size: 12px;
|
||||
line-height: 1;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
transition: all .18s ease;
|
||||
}
|
||||
.st-btn:hover {
|
||||
color: var(--accent);
|
||||
border-color: color-mix(in srgb, var(--accent) 45%, transparent);
|
||||
background: var(--accent-soft);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
.st-btn-primary {
|
||||
border-color: transparent;
|
||||
background: linear-gradient(135deg, var(--accent), var(--gold));
|
||||
color: #fff;
|
||||
font-weight: 600;
|
||||
box-shadow: 0 10px 22px -14px var(--accent);
|
||||
}
|
||||
.st-btn-primary:hover {
|
||||
color: #fff;
|
||||
border-color: transparent;
|
||||
background: linear-gradient(135deg, var(--accent), var(--accent));
|
||||
}
|
||||
.st-btn-ghost { border-color: transparent; background: transparent; color: var(--ink-faint); }
|
||||
.st-btn-ghost:hover { background: var(--paper-soft); }
|
||||
.st-btn-danger,
|
||||
.st-btn.st-danger {
|
||||
border-color: color-mix(in srgb, var(--accent) 35%, var(--line));
|
||||
background: var(--accent-soft);
|
||||
color: var(--accent);
|
||||
}
|
||||
.st-btn.st-danger:hover { background: var(--accent); color: #fff; border-color: var(--accent); }
|
||||
|
||||
.st-link-danger {
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--ink-faint);
|
||||
font-family: inherit;
|
||||
font-size: 11.5px;
|
||||
cursor: pointer;
|
||||
transition: color .18s ease;
|
||||
}
|
||||
.st-link-danger:hover { color: var(--accent); }
|
||||
|
||||
/* ---------- 数据卡 ---------- */
|
||||
.st-stats {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(104px, 1fr));
|
||||
gap: 10px;
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
.st-stat {
|
||||
padding: 13px 16px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 12px;
|
||||
background: var(--paper);
|
||||
box-shadow: var(--shadow-sm);
|
||||
}
|
||||
.st-stat b {
|
||||
display: block;
|
||||
color: var(--ink);
|
||||
font-family: 'Noto Serif SC', serif;
|
||||
font-size: 22px;
|
||||
font-weight: 900;
|
||||
line-height: 1.2;
|
||||
}
|
||||
.st-stat span { color: var(--ink-faint); font-size: 10.5px; letter-spacing: .04em; }
|
||||
|
||||
/* ---------- 工具条 / 上传 ---------- */
|
||||
.st-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 9px;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.st-toolbar-hint { color: var(--ink-faint); font-size: 10.5px; }
|
||||
|
||||
.st-upload-panel {
|
||||
margin-bottom: 18px;
|
||||
padding: 16px 18px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 14px;
|
||||
background: var(--paper);
|
||||
box-shadow: var(--shadow-sm);
|
||||
animation: st-rise .3s ease both;
|
||||
}
|
||||
.st-upload-panel[hidden] { display: none; }
|
||||
.st-upload-grid {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1.3fr) minmax(0, 1fr) minmax(0, .9fr) auto;
|
||||
gap: 10px;
|
||||
align-items: end;
|
||||
}
|
||||
.st-upload-grid label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
color: var(--ink-faint);
|
||||
font-size: 10.5px;
|
||||
letter-spacing: .04em;
|
||||
}
|
||||
.st-file {
|
||||
width: 100%;
|
||||
padding: 6px 9px;
|
||||
border: 1px dashed var(--line);
|
||||
border-radius: 9px;
|
||||
background: var(--paper-soft);
|
||||
color: var(--ink-soft);
|
||||
font-family: inherit;
|
||||
font-size: 11.5px;
|
||||
}
|
||||
.st-help {
|
||||
margin: 10px 0 0;
|
||||
color: var(--ink-faint);
|
||||
font-size: 10.5px;
|
||||
line-height: 1.8;
|
||||
}
|
||||
.st-help code {
|
||||
padding: 1px 4px;
|
||||
border-radius: 4px;
|
||||
background: var(--paper-soft);
|
||||
border: 1px solid var(--line-soft);
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
font-size: 9.5px;
|
||||
}
|
||||
|
||||
/* ---------- 布局 ---------- */
|
||||
.st-layout {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) 320px;
|
||||
gap: 18px;
|
||||
align-items: start;
|
||||
}
|
||||
.st-panel {
|
||||
padding: 18px 20px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 16px;
|
||||
background: var(--paper);
|
||||
box-shadow: var(--shadow-sm);
|
||||
}
|
||||
.st-panel-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.st-panel-head h2 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin: 0;
|
||||
color: var(--ink);
|
||||
font-family: 'Noto Serif SC', serif;
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
letter-spacing: .05em;
|
||||
}
|
||||
.st-panel-head h2 b {
|
||||
padding: 1px 7px;
|
||||
border-radius: 999px;
|
||||
background: var(--paper-soft);
|
||||
color: var(--ink-faint);
|
||||
font-family: Inter, sans-serif;
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.st-panel-head a { color: var(--accent); font-size: 11.5px; text-decoration: none; }
|
||||
.st-panel-head a:hover { text-decoration: underline; }
|
||||
|
||||
/* ---------- 筛选 ---------- */
|
||||
.st-filters {
|
||||
display: flex;
|
||||
gap: 7px;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.st-filters .st-input { width: auto; min-width: 110px; }
|
||||
.st-filters input[type="search"] { flex: 1; min-width: 160px; }
|
||||
|
||||
/* ---------- 表格 ---------- */
|
||||
.st-table-wrap { overflow-x: auto; margin: 0 -4px; padding: 0 4px; }
|
||||
.st-table {
|
||||
width: 100%;
|
||||
min-width: 680px;
|
||||
border-collapse: collapse;
|
||||
font-size: 12px;
|
||||
}
|
||||
.st-table th {
|
||||
padding: 8px 10px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
color: var(--ink-faint);
|
||||
font-size: 9.5px;
|
||||
font-weight: 500;
|
||||
letter-spacing: .12em;
|
||||
text-align: left;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.st-table td {
|
||||
padding: 11px 10px;
|
||||
border-bottom: 1px solid var(--line-soft);
|
||||
color: var(--ink-soft);
|
||||
vertical-align: top;
|
||||
}
|
||||
.st-table tr:last-child td { border-bottom: 0; }
|
||||
.st-table tr:hover td { background: color-mix(in srgb, var(--paper-soft) 55%, transparent); }
|
||||
.st-post-title {
|
||||
display: block;
|
||||
color: var(--ink);
|
||||
font-family: 'Noto Serif SC', serif;
|
||||
font-size: 13.5px;
|
||||
font-weight: 700;
|
||||
line-height: 1.5;
|
||||
text-decoration: none;
|
||||
transition: color .18s ease;
|
||||
}
|
||||
.st-post-title:hover { color: var(--accent); }
|
||||
.st-slug {
|
||||
display: block;
|
||||
margin-top: 2px;
|
||||
color: var(--ink-faint);
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
font-size: 9.5px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.st-badge {
|
||||
display: inline-block;
|
||||
padding: 3px 8px;
|
||||
border-radius: 999px;
|
||||
font-size: 9.5px;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.st-badge.published { background: rgba(107, 143, 113, .14); color: #5d7f63; }
|
||||
.st-badge.draft { background: rgba(209, 154, 63, .16); color: #9a7220; }
|
||||
:root[data-theme="dark"] .st-badge.published { background: rgba(127, 174, 134, .16); color: #8fc096; }
|
||||
:root[data-theme="dark"] .st-badge.draft { background: rgba(224, 176, 92, .16); color: #e0b05c; }
|
||||
.st-cats { display: flex; gap: 4px; flex-wrap: wrap; }
|
||||
.st-cats span {
|
||||
padding: 2px 7px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 999px;
|
||||
color: var(--ink-faint);
|
||||
font-size: 9.5px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.st-cats i { color: var(--ink-faint); font-size: 9.5px; font-style: normal; }
|
||||
.st-table time { color: var(--ink-faint); font-size: 10.5px; white-space: nowrap; }
|
||||
.st-row-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.st-row-actions a {
|
||||
color: var(--ink-faint);
|
||||
font-size: 11.5px;
|
||||
text-decoration: none;
|
||||
transition: color .18s ease;
|
||||
}
|
||||
.st-row-actions a:hover { color: var(--accent); }
|
||||
.st-row-actions form { display: inline; margin: 0; }
|
||||
.st-table-empty {
|
||||
padding: 40px 10px !important;
|
||||
color: var(--ink-faint);
|
||||
text-align: center;
|
||||
}
|
||||
.st-pager {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 14px;
|
||||
margin-top: 14px;
|
||||
color: var(--ink-faint);
|
||||
font-size: 11px;
|
||||
}
|
||||
.st-pager a { color: var(--accent); text-decoration: none; }
|
||||
.st-pager a:hover { text-decoration: underline; }
|
||||
|
||||
/* ---------- 分类面板 ---------- */
|
||||
.st-cat-list { list-style: none; margin: 0 0 18px; padding: 0; }
|
||||
.st-cat-list li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 9px;
|
||||
border-bottom: 1px solid var(--line-soft);
|
||||
border-radius: 8px;
|
||||
}
|
||||
.st-cat-list li:last-child { border-bottom: 0; }
|
||||
.st-cat-list li.is-editing { background: var(--accent-soft); }
|
||||
.st-cat-info { min-width: 0; flex: 1; }
|
||||
.st-cat-info a {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
color: var(--ink);
|
||||
font-family: 'Noto Serif SC', serif;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.st-cat-info a:hover { color: var(--accent); }
|
||||
.st-cat-info small {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
margin-top: 1px;
|
||||
color: var(--ink-faint);
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
font-size: 9px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.st-cat-count {
|
||||
min-width: 22px;
|
||||
padding: 1px 6px;
|
||||
border-radius: 999px;
|
||||
background: var(--paper-soft);
|
||||
color: var(--ink-faint);
|
||||
font-size: 9.5px;
|
||||
text-align: center;
|
||||
}
|
||||
.st-cat-actions { display: flex; align-items: center; gap: 7px; }
|
||||
.st-cat-actions a {
|
||||
color: var(--ink-faint);
|
||||
font-size: 10.5px;
|
||||
text-decoration: none;
|
||||
}
|
||||
.st-cat-actions a:hover { color: var(--accent); }
|
||||
.st-cat-actions form { display: inline; margin: 0; }
|
||||
.st-cat-empty { color: var(--ink-faint); font-size: 11.5px; }
|
||||
.st-cat-form-title {
|
||||
margin: 0 0 10px;
|
||||
padding-top: 14px;
|
||||
border-top: 1px dashed var(--line);
|
||||
color: var(--ink);
|
||||
font-family: 'Noto Serif SC', serif;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.st-cat-form { display: flex; flex-direction: column; gap: 8px; }
|
||||
.st-cat-form label,
|
||||
.st-field label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
color: var(--ink-faint);
|
||||
font-size: 10.5px;
|
||||
letter-spacing: .05em;
|
||||
}
|
||||
.st-cat-form .st-input,
|
||||
.st-field .st-input { width: 100%; }
|
||||
|
||||
/* ---------- 输入 ---------- */
|
||||
.st-input {
|
||||
width: 100%;
|
||||
padding: 7px 10px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
background: var(--paper-soft);
|
||||
color: var(--ink);
|
||||
font-family: inherit;
|
||||
font-size: 12px;
|
||||
line-height: 1.65;
|
||||
outline: none;
|
||||
transition: border-color .18s ease, box-shadow .18s ease;
|
||||
}
|
||||
.st-input:focus {
|
||||
border-color: color-mix(in srgb, var(--accent) 45%, transparent);
|
||||
box-shadow: 0 0 0 3px var(--accent-soft);
|
||||
}
|
||||
.st-input[type="search"]:focus { box-shadow: 0 0 0 3px var(--accent-soft); }
|
||||
textarea.st-input { resize: vertical; }
|
||||
.st-form-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
/* ---------- 消息 / 错误 ---------- */
|
||||
.st-messages { display: flex; flex-direction: column; gap: 7px; margin-bottom: 14px; }
|
||||
.st-msg {
|
||||
margin: 0;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid var(--line);
|
||||
border-left: 3px solid var(--ink-faint);
|
||||
border-radius: 8px;
|
||||
background: var(--paper);
|
||||
color: var(--ink-soft);
|
||||
font-size: 11.5px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
.st-msg.success { border-left-color: #6b8f71; }
|
||||
.st-msg.info { border-left-color: var(--c4); }
|
||||
.st-msg.warning { border-left-color: var(--gold); }
|
||||
.st-msg.error { border-left-color: var(--accent); color: var(--accent); }
|
||||
|
||||
.st .errorlist {
|
||||
margin: 4px 0 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
color: var(--accent);
|
||||
font-size: 10.5px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
.st .errorlist li { margin: 0; }
|
||||
|
||||
/* ---------- 编辑器 ---------- */
|
||||
.st-editor {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) 330px;
|
||||
gap: 18px;
|
||||
align-items: start;
|
||||
}
|
||||
.st-editor-main,
|
||||
.st-side-card {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 16px;
|
||||
background: var(--paper);
|
||||
box-shadow: var(--shadow-sm);
|
||||
}
|
||||
.st-editor-main { padding: 20px 22px; }
|
||||
.st-side-card { padding: 16px 18px; }
|
||||
.st-editor-side { display: flex; flex-direction: column; gap: 14px; }
|
||||
|
||||
.st-field { margin-bottom: 14px; }
|
||||
.st-field:last-child { margin-bottom: 0; }
|
||||
.st-title-input {
|
||||
padding: 10px 12px;
|
||||
font-family: 'Noto Serif SC', serif;
|
||||
font-size: 1.35rem;
|
||||
font-weight: 700;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.st-editor-meta-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) 150px;
|
||||
gap: 14px;
|
||||
}
|
||||
.st-content-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.st-content-head > label {
|
||||
color: var(--ink-faint);
|
||||
font-size: 10.5px;
|
||||
letter-spacing: .05em;
|
||||
}
|
||||
.st-md-import {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 3px 9px;
|
||||
border: 1px dashed var(--line);
|
||||
border-radius: 999px;
|
||||
color: var(--ink-faint);
|
||||
font-size: 10px;
|
||||
cursor: pointer;
|
||||
transition: all .18s ease;
|
||||
}
|
||||
.st-md-import:hover { color: var(--accent); border-color: var(--accent); background: var(--accent-soft); }
|
||||
.st-md-import input {
|
||||
position: absolute;
|
||||
width: 1px; height: 1px;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
.st-char-count { margin-left: auto; color: var(--ink-faint); font-size: 10px; font-variant-numeric: tabular-nums; }
|
||||
.st-char-count b { color: var(--ink-soft); font-weight: 600; }
|
||||
.st-content {
|
||||
min-height: 58vh;
|
||||
padding: 14px 16px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
background: var(--paper-soft);
|
||||
color: var(--ink);
|
||||
font-family: 'JetBrains Mono', 'Noto Serif SC', monospace;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.85;
|
||||
resize: vertical;
|
||||
tab-size: 2;
|
||||
}
|
||||
|
||||
.st-side-card h2 {
|
||||
margin: 0 0 12px;
|
||||
padding-bottom: 8px;
|
||||
border-bottom: 1px dashed var(--line);
|
||||
color: var(--ink);
|
||||
font-family: 'Noto Serif SC', serif;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
letter-spacing: .06em;
|
||||
}
|
||||
.st-side-card .st-field { margin-bottom: 10px; }
|
||||
.st-side-card .st-form-actions { margin-top: 10px; }
|
||||
.st-side-card .st-help { margin-top: 8px; }
|
||||
|
||||
.st-check-grid {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 5px 10px;
|
||||
max-height: 190px;
|
||||
overflow-y: auto;
|
||||
padding-right: 4px;
|
||||
}
|
||||
.st-check {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
color: var(--ink-soft);
|
||||
font-size: 11px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.st-check input { accent-color: var(--accent); }
|
||||
.st-check span { line-height: 1.6; }
|
||||
|
||||
.st-danger-zone { border-color: color-mix(in srgb, var(--accent) 22%, var(--line)); }
|
||||
|
||||
/* ---------- 锁定页 ---------- */
|
||||
.st-lock-page {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
min-height: calc(100vh - 240px);
|
||||
padding: 20px 0 60px;
|
||||
}
|
||||
.st-lock-card {
|
||||
width: min(92vw, 410px);
|
||||
padding: 34px 34px 28px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 22px;
|
||||
background: var(--paper);
|
||||
box-shadow: var(--shadow);
|
||||
text-align: center;
|
||||
}
|
||||
.st-lock-card h1 {
|
||||
margin: 0 0 8px;
|
||||
color: var(--ink);
|
||||
font-family: 'Noto Serif SC', serif;
|
||||
font-size: 1.9rem;
|
||||
font-weight: 900;
|
||||
}
|
||||
.st-lock-sub { margin: 0 0 20px; color: var(--ink-faint); font-size: 12px; line-height: 1.8; }
|
||||
.st-unlock-form { display: flex; gap: 7px; }
|
||||
.st-unlock-form input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: 8px 11px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 9px;
|
||||
background: var(--paper-soft);
|
||||
color: var(--ink);
|
||||
font-family: inherit;
|
||||
font-size: 12px;
|
||||
outline: none;
|
||||
}
|
||||
.st-unlock-form input:focus {
|
||||
border-color: color-mix(in srgb, var(--accent) 45%, transparent);
|
||||
box-shadow: 0 0 0 3px var(--accent-soft);
|
||||
}
|
||||
.st-unlock-form .st-btn { flex: none; }
|
||||
.st-error {
|
||||
margin: 12px 0 0;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid color-mix(in srgb, var(--accent) 30%, var(--line));
|
||||
border-radius: 8px;
|
||||
background: var(--accent-soft);
|
||||
color: var(--accent);
|
||||
font-size: 11.5px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
.st-lock-hint { margin: 16px 0 0; color: var(--ink-faint); font-size: 10px; }
|
||||
|
||||
.st-note {
|
||||
margin: 26px 0 0;
|
||||
padding-top: 14px;
|
||||
border-top: 1px dashed var(--line);
|
||||
color: var(--ink-faint);
|
||||
font-size: 10.5px;
|
||||
line-height: 1.9;
|
||||
}
|
||||
|
||||
@keyframes st-rise {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
to { opacity: 1; transform: none; }
|
||||
}
|
||||
|
||||
/* ---------- 响应式 ---------- */
|
||||
@media (max-width: 980px) {
|
||||
.st-layout,
|
||||
.st-editor { grid-template-columns: 1fr; }
|
||||
.st-editor-side { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); }
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.st-head { align-items: flex-start; }
|
||||
.st-head-actions { width: 100%; }
|
||||
.st-stats { grid-template-columns: repeat(3, 1fr); }
|
||||
.st-stat { padding: 10px 12px; }
|
||||
.st-stat b { font-size: 18px; }
|
||||
.st-upload-grid { grid-template-columns: 1fr; }
|
||||
.st-filters .st-input { flex: 1; min-width: 0; }
|
||||
.st-editor-main { padding: 16px; }
|
||||
.st-editor-meta-row { grid-template-columns: 1fr; }
|
||||
.st-panel { padding: 14px; }
|
||||
.st-content { min-height: 48vh; }
|
||||
}
|
||||
|
||||
@media (max-width: 420px) {
|
||||
.st-stats { grid-template-columns: repeat(2, 1fr); }
|
||||
.st-unlock-form { flex-direction: column; }
|
||||
.st-unlock-form .st-btn { width: 100%; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.st-upload-panel { animation: none; }
|
||||
.st-btn { transition: none; }
|
||||
}
|
||||
|
||||
/* JS 临时提示 */
|
||||
.st-js-toast {
|
||||
position: fixed;
|
||||
left: 50%;
|
||||
bottom: 32px;
|
||||
z-index: 1100;
|
||||
max-width: min(90vw, 460px);
|
||||
padding: 9px 16px;
|
||||
border-radius: 10px;
|
||||
background: var(--ink);
|
||||
color: var(--bg);
|
||||
font-size: 12px;
|
||||
line-height: 1.7;
|
||||
box-shadow: var(--shadow);
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transform: translate(-50%, 8px);
|
||||
transition: opacity .2s ease, transform .2s ease;
|
||||
}
|
||||
.st-js-toast.is-visible { opacity: 1; transform: translate(-50%, 0); }
|
||||
@@ -0,0 +1,243 @@
|
||||
/* =========================================================
|
||||
拾编 · 写作台交互
|
||||
========================================================= */
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var csrfMeta = document.querySelector('meta[name="csrf-token"]');
|
||||
var CSRF = csrfMeta ? csrfMeta.getAttribute('content') || '' : '';
|
||||
var $ = function (selector) { return document.querySelector(selector); };
|
||||
|
||||
function toast(message) {
|
||||
var box = document.querySelector('.st-js-toast');
|
||||
if (!box) {
|
||||
box = document.createElement('div');
|
||||
box.className = 'st-js-toast';
|
||||
document.body.appendChild(box);
|
||||
}
|
||||
box.textContent = message;
|
||||
box.classList.add('is-visible');
|
||||
clearTimeout(box._timer);
|
||||
box._timer = setTimeout(function () {
|
||||
box.classList.remove('is-visible');
|
||||
}, 3200);
|
||||
}
|
||||
|
||||
function showError(message) {
|
||||
var box = $('#stError');
|
||||
if (box) {
|
||||
box.textContent = message;
|
||||
box.hidden = false;
|
||||
return;
|
||||
}
|
||||
toast(message);
|
||||
}
|
||||
|
||||
function hideError() {
|
||||
var box = $('#stError');
|
||||
if (box) box.hidden = true;
|
||||
}
|
||||
|
||||
async function postJson(url, payload) {
|
||||
var response = await fetch(url, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'application/json',
|
||||
'X-CSRFToken': CSRF
|
||||
},
|
||||
body: JSON.stringify(payload || {})
|
||||
});
|
||||
var data = null;
|
||||
try { data = await response.json(); } catch (err) {}
|
||||
|
||||
if (!response.ok) {
|
||||
var error = new Error((data && data.error) || ('请求失败(HTTP ' + response.status + ')'));
|
||||
error.code = data && data.code;
|
||||
throw error;
|
||||
}
|
||||
return data || {};
|
||||
}
|
||||
|
||||
/* ---------- 解锁 / 锁定 ---------- */
|
||||
var unlockForm = $('#stUnlockForm');
|
||||
if (unlockForm) {
|
||||
unlockForm.addEventListener('submit', async function (event) {
|
||||
event.preventDefault();
|
||||
var input = $('#stPassword');
|
||||
var button = unlockForm.querySelector('button[type="submit"]');
|
||||
var password = input ? input.value : '';
|
||||
|
||||
if (!password) {
|
||||
showError('请输入密码');
|
||||
if (input) input.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
button.disabled = true;
|
||||
hideError();
|
||||
try {
|
||||
await postJson('/files/unlock/', { password: password });
|
||||
window.location.reload();
|
||||
} catch (error) {
|
||||
showError((error && error.message) || '解锁失败');
|
||||
button.disabled = false;
|
||||
if (input) input.select();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
var lockBtn = $('#stLockBtn');
|
||||
if (lockBtn) {
|
||||
lockBtn.addEventListener('click', async function () {
|
||||
lockBtn.disabled = true;
|
||||
try {
|
||||
await postJson('/files/lock/', {});
|
||||
window.location.reload();
|
||||
} catch (error) {
|
||||
toast((error && error.message) || '锁定失败');
|
||||
lockBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------- 上传 Markdown 面板 ---------- */
|
||||
var uploadToggle = $('#stUploadToggle');
|
||||
var uploadForm = $('#stUploadForm');
|
||||
if (uploadToggle && uploadForm) {
|
||||
uploadToggle.addEventListener('click', function () {
|
||||
uploadForm.hidden = !uploadForm.hidden;
|
||||
if (!uploadForm.hidden && uploadForm.scrollIntoView) {
|
||||
uploadForm.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------- 删除确认 ---------- */
|
||||
Array.prototype.forEach.call(document.querySelectorAll('form[data-confirm]'), function (form) {
|
||||
form.addEventListener('submit', function (event) {
|
||||
if (!window.confirm(form.getAttribute('data-confirm') || '确定执行这个操作?')) {
|
||||
event.preventDefault();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
/* ---------- 编辑器 ---------- */
|
||||
var content = $('#id_content');
|
||||
var counter = $('#stCharCount');
|
||||
if (content && counter) {
|
||||
var updateCount = function () {
|
||||
counter.textContent = String(content.value.length);
|
||||
};
|
||||
content.addEventListener('input', updateCount);
|
||||
updateCount();
|
||||
}
|
||||
|
||||
var importer = $('#stMdImport');
|
||||
if (importer && content) {
|
||||
importer.addEventListener('change', function () {
|
||||
var file = importer.files && importer.files[0];
|
||||
if (!file) return;
|
||||
|
||||
if (file.size > 2 * 1024 * 1024) {
|
||||
showError('Markdown 文件不能超过 2 MB');
|
||||
importer.value = '';
|
||||
return;
|
||||
}
|
||||
|
||||
var reader = new FileReader();
|
||||
reader.onload = function () {
|
||||
var text = String(reader.result || '');
|
||||
var parsed = splitFrontMatter(text);
|
||||
var meta = parsed[0];
|
||||
var body = parsed[1];
|
||||
var metaTitle = (meta.title || '').trim();
|
||||
var heading = firstHeading(body);
|
||||
var title = metaTitle || heading || file.name.replace(/\.(md|markdown)$/i, '');
|
||||
|
||||
if (metaTitle) {
|
||||
if (heading && heading === metaTitle) body = removeFirstHeading(body);
|
||||
} else if (heading) {
|
||||
body = removeFirstHeading(body);
|
||||
}
|
||||
|
||||
if (content.value.trim() && !window.confirm('导入会覆盖当前正文,继续?')) {
|
||||
importer.value = '';
|
||||
return;
|
||||
}
|
||||
|
||||
setValue('#id_content', body.trim());
|
||||
setValue('#id_title', title);
|
||||
setValue('#id_slug', meta.slug || '');
|
||||
setValue('#id_excerpt', meta.excerpt || '');
|
||||
setValue('#id_content_format', 'markdown');
|
||||
|
||||
if (meta.status === 'draft' || meta.status === 'published') {
|
||||
setValue('#id_status', meta.status);
|
||||
}
|
||||
if (meta.date) {
|
||||
var match = String(meta.date).match(/^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2}))?/);
|
||||
if (match) {
|
||||
setValue(
|
||||
'#id_published_at',
|
||||
match[1] + '-' + match[2] + '-' + match[3] + 'T' + (match[4] || '00') + ':' + (match[5] || '00')
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (counter) counter.textContent = String(content.value.length);
|
||||
hideError();
|
||||
toast('已导入 Markdown,检查后保存');
|
||||
importer.value = '';
|
||||
};
|
||||
|
||||
reader.onerror = function () {
|
||||
showError('读取文件失败');
|
||||
importer.value = '';
|
||||
};
|
||||
|
||||
reader.readAsText(file, 'utf-8');
|
||||
});
|
||||
}
|
||||
|
||||
function setValue(selector, value) {
|
||||
var element = $(selector);
|
||||
if (element) element.value = value;
|
||||
}
|
||||
|
||||
function splitFrontMatter(text) {
|
||||
text = text.replace(/^\uFEFF/, '');
|
||||
var lines = text.split(/\r?\n/);
|
||||
if (!lines.length || lines[0].trim() !== '---') return [{}, text];
|
||||
|
||||
var end = -1;
|
||||
for (var i = 1; i < lines.length; i++) {
|
||||
if (lines[i].trim() === '---' || lines[i].trim() === '...') {
|
||||
end = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (end < 0) return [{}, text];
|
||||
|
||||
var meta = {};
|
||||
for (var j = 1; j < end; j++) {
|
||||
var position = lines[j].indexOf(':');
|
||||
if (position <= 0) continue;
|
||||
var key = lines[j].slice(0, position).trim().toLowerCase();
|
||||
var value = lines[j].slice(position + 1).trim().replace(/^['"]|['"]$/g, '');
|
||||
if (key) meta[key] = value;
|
||||
}
|
||||
|
||||
return [meta, lines.slice(end + 1).join('\n').replace(/^\n+/, '')];
|
||||
}
|
||||
|
||||
function firstHeading(body) {
|
||||
var match = String(body).match(/^#\s+(.+?)\s*$/m);
|
||||
return match ? match[1].replace(/[*_`]+/g, '').trim() : '';
|
||||
}
|
||||
|
||||
function removeFirstHeading(body) {
|
||||
return String(body).replace(/^#\s+.+?\s*$/m, '').replace(/^\n+/, '');
|
||||
}
|
||||
})();
|
||||
@@ -0,0 +1,7 @@
|
||||
{% if messages %}
|
||||
<div class="st-messages" role="status">
|
||||
{% for message in messages %}
|
||||
<p class="st-msg {{ message.tags }}">{{ message }}</p>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
@@ -0,0 +1,144 @@
|
||||
{% extends "base_content.html" %}
|
||||
{% load static %}
|
||||
|
||||
{% block title %}{% if is_new %}新建文章{% else %}编辑文章{% endif %} · 拾编{% endblock %}
|
||||
{% block description %}博客文章编辑{% endblock %}
|
||||
{% block brand_sub %}MIND MAP · STUDIO{% endblock %}
|
||||
{% block footer %}© 2026 拾光<span class="dot"></span>写字的地方{% endblock %}
|
||||
{% block extra_head %}<meta name="robots" content="noindex,nofollow">{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="st st-editor-page">
|
||||
<a class="st-back" href="{% url 'studio:index' %}">← 写作台</a>
|
||||
|
||||
<header class="st-head">
|
||||
<div>
|
||||
<p class="st-eyebrow"><span aria-hidden="true">✦</span>拾编 · STUDIO</p>
|
||||
<h1>{% if is_new %}新建文章{% else %}编辑文章{% endif %}</h1>
|
||||
<p class="st-sub">
|
||||
{% if post %}
|
||||
/post/{{ post.slug }}/ · 最后更新 {{ post.updated_at|date:"Y-m-d H:i" }}
|
||||
{% else %}
|
||||
写好后可以先存草稿,再从写作台发布。
|
||||
{% endif %}
|
||||
</p>
|
||||
</div>
|
||||
<div class="st-head-actions">
|
||||
{% if post and post.status == 'published' %}
|
||||
<a class="st-btn" href="{{ post.get_absolute_url }}" target="_blank" rel="noopener">查看文章 ↗</a>
|
||||
{% endif %}
|
||||
<button class="st-btn st-btn-primary" type="submit" form="stPostForm">保存</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{% include "studio/_messages.html" %}
|
||||
|
||||
<form class="st-editor" id="stPostForm" method="post">
|
||||
{% csrf_token %}
|
||||
{{ form.non_field_errors }}
|
||||
|
||||
<div class="st-editor-main">
|
||||
<div class="st-field">
|
||||
<label for="{{ form.title.id_for_label }}">标题</label>
|
||||
{{ form.title }}
|
||||
{{ form.title.errors }}
|
||||
</div>
|
||||
|
||||
<div class="st-editor-meta-row">
|
||||
<div class="st-field">
|
||||
<label for="{{ form.slug.id_for_label }}">URL 别名</label>
|
||||
{{ form.slug }}
|
||||
<p class="st-help">留空会自动生成;文章地址是 <code>/post/<slug>/</code>。</p>
|
||||
</div>
|
||||
<div class="st-field st-field-narrow">
|
||||
<label for="{{ form.content_format.id_for_label }}">内容格式</label>
|
||||
{{ form.content_format }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="st-field">
|
||||
<div class="st-content-head">
|
||||
<label for="{{ form.content.id_for_label }}">正文</label>
|
||||
<label class="st-md-import" for="stMdImport">从 Markdown 导入
|
||||
<input type="file" id="stMdImport" accept=".md,.markdown">
|
||||
</label>
|
||||
<span class="st-char-count"><b id="stCharCount">0</b> 字</span>
|
||||
</div>
|
||||
{{ form.content }}
|
||||
{{ form.content.errors }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<aside class="st-editor-side">
|
||||
<section class="st-side-card">
|
||||
<h2>发布</h2>
|
||||
<div class="st-field">
|
||||
<label for="{{ form.status.id_for_label }}">状态</label>
|
||||
{{ form.status }}
|
||||
</div>
|
||||
<div class="st-field">
|
||||
<label for="{{ form.published_at.id_for_label }}">发布时间</label>
|
||||
{{ form.published_at }}
|
||||
</div>
|
||||
<div class="st-field">
|
||||
<label for="{{ form.excerpt.id_for_label }}">摘要</label>
|
||||
{{ form.excerpt }}
|
||||
</div>
|
||||
<div class="st-form-actions">
|
||||
<button class="st-btn st-btn-primary" type="submit">保存文章</button>
|
||||
</div>
|
||||
<p class="st-help">保存后可继续编辑;状态设为「已发布」才会出现在博客上。</p>
|
||||
</section>
|
||||
|
||||
<section class="st-side-card">
|
||||
<h2>分类</h2>
|
||||
<div class="st-check-grid">
|
||||
{% for checkbox in form.categories %}
|
||||
<label class="st-check">{{ checkbox.tag }}<span>{{ checkbox.choice_label }}</span></label>
|
||||
{% empty %}
|
||||
<p class="st-help">还没有分类,先回写作台建一个。</p>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="st-side-card">
|
||||
<h2>标签</h2>
|
||||
<div class="st-check-grid">
|
||||
{% for checkbox in form.tags %}
|
||||
<label class="st-check">{{ checkbox.tag }}<span>{{ checkbox.choice_label }}</span></label>
|
||||
{% empty %}
|
||||
<p class="st-help">还没有标签。</p>
|
||||
{% endfor %}
|
||||
</div>
|
||||
<div class="st-field">
|
||||
<label for="{{ form.new_tags.id_for_label }}">新标签</label>
|
||||
{{ form.new_tags }}
|
||||
<p class="st-help">多个用逗号分隔,保存时自动创建。</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{% if post %}
|
||||
<section class="st-side-card st-danger-zone">
|
||||
<h2>删除</h2>
|
||||
<p class="st-help">删除后不可恢复。</p>
|
||||
<button class="st-btn st-danger" type="submit" form="stDeleteForm">删除文章</button>
|
||||
</section>
|
||||
{% endif %}
|
||||
</aside>
|
||||
</form>
|
||||
|
||||
{% if post %}
|
||||
<form id="stDeleteForm" method="post" action="{% url 'studio:post_delete' post.id %}" data-confirm="确定删除这篇文章?此操作不可恢复。">
|
||||
{% csrf_token %}
|
||||
</form>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<link rel="stylesheet" href="{% static 'studio/studio.css' %}">
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script src="{% static 'studio/studio.js' %}"></script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,35 @@
|
||||
{% extends "base_content.html" %}
|
||||
{% load static %}
|
||||
|
||||
{% block title %}拾编 · 写作台{% endblock %}
|
||||
{% block description %}博客文章与分类管理{% endblock %}
|
||||
{% block brand_sub %}MIND MAP · STUDIO{% endblock %}
|
||||
{% block footer %}© 2026 拾光<span class="dot"></span>写字的地方{% endblock %}
|
||||
{% block extra_head %}<meta name="robots" content="noindex,nofollow">{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="st st-lock-page">
|
||||
<section class="st-lock-card">
|
||||
<p class="st-eyebrow"><span aria-hidden="true">✦</span>拾编 · STUDIO</p>
|
||||
<h1>写作台</h1>
|
||||
<p class="st-lock-sub">文章、分类和草稿,只对站点主人开放。</p>
|
||||
|
||||
<form class="st-unlock-form" id="stUnlockForm">
|
||||
<label class="sr-only" for="stPassword">密码</label>
|
||||
<input type="password" id="stPassword" placeholder="输入密码" autocomplete="current-password">
|
||||
<button class="st-btn st-btn-primary" type="submit">解锁进入</button>
|
||||
</form>
|
||||
|
||||
<p class="st-error" id="stError" hidden></p>
|
||||
<p class="st-lock-hint">与拾匣共用密码</p>
|
||||
</section>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<link rel="stylesheet" href="{% static 'studio/studio.css' %}">
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script src="{% static 'studio/studio.js' %}"></script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,200 @@
|
||||
{% extends "base_content.html" %}
|
||||
{% load static %}
|
||||
|
||||
{% block title %}拾编 · 写作台{% endblock %}
|
||||
{% block description %}博客文章与分类管理{% endblock %}
|
||||
{% block brand_sub %}MIND MAP · STUDIO{% endblock %}
|
||||
{% block footer %}© 2026 拾光<span class="dot"></span>写字的地方{% endblock %}
|
||||
{% block extra_head %}<meta name="robots" content="noindex,nofollow">{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="st">
|
||||
<header class="st-head">
|
||||
<div>
|
||||
<p class="st-eyebrow"><span aria-hidden="true">✦</span>拾编 · STUDIO</p>
|
||||
<h1>写作台</h1>
|
||||
<p class="st-sub">文章、分类和草稿,都放在一张桌子上。</p>
|
||||
</div>
|
||||
<div class="st-head-actions">
|
||||
<a class="st-btn" href="/">回首页</a>
|
||||
<button class="st-btn" id="stLockBtn" type="button">锁定</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{% include "studio/_messages.html" %}
|
||||
|
||||
<div class="st-stats">
|
||||
<div class="st-stat"><b>{{ stats.total }}</b><span>全部文章</span></div>
|
||||
<div class="st-stat"><b>{{ stats.published }}</b><span>已发布</span></div>
|
||||
<div class="st-stat"><b>{{ stats.draft }}</b><span>草稿</span></div>
|
||||
<div class="st-stat"><b>{{ stats.categories }}</b><span>分类</span></div>
|
||||
<div class="st-stat"><b>{{ stats.tags }}</b><span>标签</span></div>
|
||||
</div>
|
||||
|
||||
<div class="st-toolbar">
|
||||
<a class="st-btn st-btn-primary" href="{% url 'studio:post_new' %}">+ 新建文章</a>
|
||||
<button class="st-btn" id="stUploadToggle" type="button">↑ 上传 Markdown</button>
|
||||
<span class="st-toolbar-hint">上传后先进入编辑页,确认后再发布。</span>
|
||||
</div>
|
||||
|
||||
<form class="st-upload-panel" id="stUploadForm" method="post"
|
||||
action="{% url 'studio:upload_markdown' %}" enctype="multipart/form-data" hidden>
|
||||
{% csrf_token %}
|
||||
<div class="st-upload-grid">
|
||||
<label>Markdown 文件
|
||||
<input class="st-file" type="file" name="file" accept=".md,.markdown" required>
|
||||
</label>
|
||||
<label>归入分类
|
||||
<select class="st-input" name="category">
|
||||
<option value="">不归入分类</option>
|
||||
{% for cat in categories %}
|
||||
<option value="{{ cat.id }}">{{ cat.name }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
<label>默认状态
|
||||
<select class="st-input" name="status">
|
||||
<option value="draft">草稿</option>
|
||||
<option value="published">已发布</option>
|
||||
</select>
|
||||
</label>
|
||||
<button class="st-btn st-btn-primary" type="submit">上传并创建</button>
|
||||
</div>
|
||||
<p class="st-help">支持 front matter:<code>title / slug / date / status / categories / tags / excerpt</code>。上传后先进入编辑页,确认后再发布。</p>
|
||||
</form>
|
||||
|
||||
<div class="st-layout">
|
||||
<section class="st-panel st-posts">
|
||||
<div class="st-panel-head">
|
||||
<h2>文章 <b>{{ filtered_count }}</b></h2>
|
||||
</div>
|
||||
|
||||
<form class="st-filters" method="get" action="{% url 'studio:index' %}">
|
||||
<select class="st-input" name="status" aria-label="状态">
|
||||
<option value="all" {% if status == 'all' %}selected{% endif %}>全部状态</option>
|
||||
<option value="published" {% if status == 'published' %}selected{% endif %}>已发布</option>
|
||||
<option value="draft" {% if status == 'draft' %}selected{% endif %}>草稿</option>
|
||||
</select>
|
||||
<select class="st-input" name="category" aria-label="分类">
|
||||
<option value="">全部分类</option>
|
||||
{% for cat in categories %}
|
||||
<option value="{{ cat.id }}" {% if category_id == cat.id %}selected{% endif %}>{{ cat.name }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
<input class="st-input" type="search" name="q" value="{{ query }}" placeholder="搜索标题 / 摘要 / 正文">
|
||||
<button class="st-btn" type="submit">筛选</button>
|
||||
<a class="st-btn st-btn-ghost" href="{% url 'studio:index' %}">重置</a>
|
||||
</form>
|
||||
|
||||
<div class="st-table-wrap">
|
||||
<table class="st-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>文章</th>
|
||||
<th>状态</th>
|
||||
<th>分类</th>
|
||||
<th>发布时间</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for post in page %}
|
||||
<tr>
|
||||
<td>
|
||||
<a class="st-post-title" href="{% url 'studio:post_edit' post.id %}">{{ post.title }}</a>
|
||||
<small class="st-slug">/post/{{ post.slug }}/</small>
|
||||
</td>
|
||||
<td><span class="st-badge {{ post.status }}">{{ post.get_status_display }}</span></td>
|
||||
<td>
|
||||
<span class="st-cats">
|
||||
{% for cat in post.categories.all %}<span>{{ cat.name }}</span>{% empty %}<i>未分类</i>{% endfor %}
|
||||
</span>
|
||||
</td>
|
||||
<td><time>{{ post.published_at|date:"Y-m-d H:i" }}</time></td>
|
||||
<td class="st-row-actions">
|
||||
<a href="{% url 'studio:post_edit' post.id %}">编辑</a>
|
||||
{% if post.status == 'published' %}
|
||||
<a href="{{ post.get_absolute_url }}" target="_blank" rel="noopener">查看</a>
|
||||
{% endif %}
|
||||
<form method="post" action="{% url 'studio:post_delete' post.id %}" data-confirm="确定删除这篇文章?此操作不可恢复。">
|
||||
{% csrf_token %}
|
||||
<button class="st-link-danger" type="submit">删除</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
{% empty %}
|
||||
<tr><td colspan="5" class="st-table-empty">没有符合条件的文章。</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{% if page.paginator.num_pages > 1 %}
|
||||
<nav class="st-pager" aria-label="文章分页">
|
||||
{% if page.has_previous %}
|
||||
<a href="?page={{ page.previous_page_number }}{% if status != 'all' %}&status={{ status }}{% endif %}{% if category_id %}&category={{ category_id }}{% endif %}{% if query %}&q={{ query|urlencode }}{% endif %}">‹ 上一页</a>
|
||||
{% endif %}
|
||||
<span>{{ page.number }} / {{ page.paginator.num_pages }}</span>
|
||||
{% if page.has_next %}
|
||||
<a href="?page={{ page.next_page_number }}{% if status != 'all' %}&status={{ status }}{% endif %}{% if category_id %}&category={{ category_id }}{% endif %}{% if query %}&q={{ query|urlencode }}{% endif %}">下一页 ›</a>
|
||||
{% endif %}
|
||||
</nav>
|
||||
{% endif %}
|
||||
</section>
|
||||
|
||||
<aside class="st-panel st-cats" id="categories">
|
||||
<div class="st-panel-head">
|
||||
<h2>分类 <b>{{ stats.categories }}</b></h2>
|
||||
<a href="{% url 'studio:index' %}#categories">新建</a>
|
||||
</div>
|
||||
|
||||
<ul class="st-cat-list">
|
||||
{% for cat in categories %}
|
||||
<li{% if edit_category and edit_category.id == cat.id %} class="is-editing"{% endif %}>
|
||||
<div class="st-cat-info">
|
||||
<a href="?edit_cat={{ cat.id }}#categories">{{ cat.name }}</a>
|
||||
<small>{{ cat.slug }}{% if cat.parent %} · 上级 {{ cat.parent.name }}{% endif %}</small>
|
||||
</div>
|
||||
<span class="st-cat-count">{{ cat.post_count }}</span>
|
||||
<div class="st-cat-actions">
|
||||
<a href="?edit_cat={{ cat.id }}#categories">编辑</a>
|
||||
<form method="post" action="{% url 'studio:category_delete' cat.id %}" data-confirm="删除分类「{{ cat.name }}」?文章会保留,但子分类会一起删除。">
|
||||
{% csrf_token %}
|
||||
<button class="st-link-danger" type="submit">删除</button>
|
||||
</form>
|
||||
</div>
|
||||
</li>
|
||||
{% empty %}
|
||||
<li class="st-cat-empty">还没有分类。</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
|
||||
<h3 class="st-cat-form-title">{% if edit_category %}编辑「{{ edit_category.name }}」{% else %}新建分类{% endif %}</h3>
|
||||
<form class="st-cat-form" method="post" action="{% url 'studio:category_save' %}">
|
||||
{% csrf_token %}
|
||||
{{ category_form.id }}
|
||||
<label>名称 {{ category_form.name }}</label>
|
||||
<label>URL 别名 {{ category_form.slug }}</label>
|
||||
<label>上级分类 {{ category_form.parent }}</label>
|
||||
<label>描述 {{ category_form.description }}</label>
|
||||
<div class="st-form-actions">
|
||||
<button class="st-btn st-btn-primary" type="submit">{% if edit_category %}保存修改{% else %}创建分类{% endif %}</button>
|
||||
{% if edit_category %}
|
||||
<a class="st-btn st-btn-ghost" href="{% url 'studio:index' %}#categories">取消</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</form>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<p class="st-note">写作台只对站点主人开放;解锁状态与拾匣共用,锁定后此页会回到密码界面。</p>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<link rel="stylesheet" href="{% static 'studio/studio.css' %}">
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_js %}
|
||||
<script src="{% static 'studio/studio.js' %}"></script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,15 @@
|
||||
from django.urls import path
|
||||
|
||||
from . import views
|
||||
|
||||
app_name = "studio"
|
||||
|
||||
urlpatterns = [
|
||||
path("", views.index, name="index"),
|
||||
path("posts/new/", views.post_edit, name="post_new"),
|
||||
path("posts/upload/", views.upload_markdown, name="upload_markdown"),
|
||||
path("posts/<int:post_id>/edit/", views.post_edit, name="post_edit"),
|
||||
path("posts/<int:post_id>/delete/", views.post_delete, name="post_delete"),
|
||||
path("categories/save/", views.category_save, name="category_save"),
|
||||
path("categories/<int:category_id>/delete/", views.category_delete, name="category_delete"),
|
||||
]
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
"""拾编写作台的通用工具:slug、front matter、摘要。"""
|
||||
|
||||
import re
|
||||
from datetime import datetime, time
|
||||
from pathlib import Path
|
||||
|
||||
from django.utils import timezone
|
||||
from django.utils.dateparse import parse_date, parse_datetime
|
||||
from django.utils.html import strip_tags
|
||||
from django.utils.text import slugify
|
||||
|
||||
from blog.models import Category, Post, Tag
|
||||
|
||||
|
||||
def unique_slug(model, base, exclude_id=None, max_length=200):
|
||||
base = (base or "item").strip()[:max_length] or "item"
|
||||
slug = base
|
||||
index = 2
|
||||
queryset = model.objects.all()
|
||||
if exclude_id:
|
||||
queryset = queryset.exclude(pk=exclude_id)
|
||||
while queryset.filter(slug=slug).exists():
|
||||
suffix = "-{}".format(index)
|
||||
slug = base[: max_length - len(suffix)] + suffix
|
||||
index += 1
|
||||
return slug
|
||||
|
||||
|
||||
def make_post_slug(raw="", title="", filename="", exclude_id=None):
|
||||
candidates = [raw, title, Path(filename).stem if filename else ""]
|
||||
for candidate in candidates:
|
||||
value = slugify(candidate or "")
|
||||
if value:
|
||||
return unique_slug(Post, value[:200], exclude_id, 200)
|
||||
fallback = "post-" + timezone.localtime().strftime("%Y%m%d-%H%M")
|
||||
return unique_slug(Post, fallback, exclude_id, 200)
|
||||
|
||||
|
||||
def make_category_slug(raw="", name="", exclude_id=None):
|
||||
candidate = (raw or "").strip()
|
||||
if candidate:
|
||||
candidate = candidate.replace("/", "-")
|
||||
candidate = re.sub(r"\s+", "-", candidate)
|
||||
if not candidate:
|
||||
candidate = slugify(name or "", allow_unicode=True)
|
||||
if not candidate:
|
||||
candidate = "cat"
|
||||
return unique_slug(Category, candidate[:100], exclude_id, 100)
|
||||
|
||||
|
||||
def make_tag_slug(name, exclude_id=None):
|
||||
candidate = slugify(name or "", allow_unicode=True) or "tag"
|
||||
return unique_slug(Tag, candidate[:100], exclude_id, 100)
|
||||
|
||||
|
||||
def get_or_create_category(name):
|
||||
name = (name or "").strip()[:100]
|
||||
if not name:
|
||||
return None
|
||||
category = Category.objects.filter(name=name).first()
|
||||
if category:
|
||||
return category
|
||||
return Category.objects.create(name=name, slug=make_category_slug(name=name))
|
||||
|
||||
|
||||
def get_or_create_tag(name):
|
||||
name = (name or "").strip()[:100]
|
||||
if not name:
|
||||
return None
|
||||
tag = Tag.objects.filter(name=name).first()
|
||||
if tag:
|
||||
return tag
|
||||
return Tag.objects.create(name=name, slug=make_tag_slug(name))
|
||||
|
||||
|
||||
def descendant_ids(category):
|
||||
"""分类的所有后代 id(不含自身)。"""
|
||||
found = set()
|
||||
stack = [category.pk]
|
||||
while stack:
|
||||
parent_id = stack.pop()
|
||||
children = list(
|
||||
Category.objects.filter(parent_id=parent_id).values_list("pk", flat=True)
|
||||
)
|
||||
for child_id in children:
|
||||
if child_id not in found:
|
||||
found.add(child_id)
|
||||
stack.append(child_id)
|
||||
return found
|
||||
|
||||
|
||||
def parse_front_matter(text):
|
||||
"""解析一个极简 YAML front matter;不引入 PyYAML。"""
|
||||
text = (text or "").lstrip("\ufeff")
|
||||
lines = text.splitlines()
|
||||
if not lines or lines[0].strip() != "---":
|
||||
return {}, text
|
||||
|
||||
end = None
|
||||
for index in range(1, len(lines)):
|
||||
if lines[index].strip() in ("---", "..."):
|
||||
end = index
|
||||
break
|
||||
if end is None:
|
||||
return {}, text
|
||||
|
||||
meta = {}
|
||||
for line in lines[1:end]:
|
||||
if ":" not in line:
|
||||
continue
|
||||
key, value = line.split(":", 1)
|
||||
key = key.strip().lower()
|
||||
if not key:
|
||||
continue
|
||||
meta[key] = value.strip().strip("\"'")
|
||||
|
||||
body = "\n".join(lines[end + 1:]).lstrip("\n")
|
||||
return meta, body
|
||||
|
||||
|
||||
def split_names(value):
|
||||
value = (value or "").strip().strip("[]")
|
||||
if not value:
|
||||
return []
|
||||
return [
|
||||
item.strip().strip("\"'")
|
||||
for item in re.split(r"[,,、]", value)
|
||||
if item.strip()
|
||||
]
|
||||
|
||||
|
||||
def first_heading(body):
|
||||
match = re.search(r"^#\s+(.+?)\s*$", body or "", re.MULTILINE)
|
||||
if not match:
|
||||
return ""
|
||||
return re.sub(r"[*_`]+", "", match.group(1)).strip()
|
||||
|
||||
|
||||
def remove_first_heading(body):
|
||||
match = re.search(r"^#\s+(.+?)\s*$", body or "", re.MULTILINE)
|
||||
if not match:
|
||||
return body
|
||||
return (body[: match.start()] + body[match.end():]).lstrip("\n")
|
||||
|
||||
|
||||
def plain_excerpt(content, content_format="markdown", length=180):
|
||||
if content_format == "markdown":
|
||||
try:
|
||||
import markdown
|
||||
html = markdown.markdown(
|
||||
content or "", extensions=["extra", "sane_lists"]
|
||||
)
|
||||
except Exception:
|
||||
html = content or ""
|
||||
else:
|
||||
html = content or ""
|
||||
|
||||
text = strip_tags(html)
|
||||
text = re.sub(r"\s+", " ", text).strip()
|
||||
return text[:length]
|
||||
|
||||
|
||||
def parse_date_value(value):
|
||||
value = (value or "").strip()
|
||||
if not value:
|
||||
return None
|
||||
|
||||
moment = parse_datetime(value)
|
||||
if moment is None:
|
||||
day = parse_date(value)
|
||||
if day is None:
|
||||
return None
|
||||
moment = datetime.combine(day, time.min)
|
||||
|
||||
if timezone.is_naive(moment):
|
||||
moment = timezone.make_aware(moment)
|
||||
return moment
|
||||
+388
@@ -0,0 +1,388 @@
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from django.contrib import messages
|
||||
from django.core.paginator import Paginator
|
||||
from django.db.models import Count, Q
|
||||
from django.shortcuts import get_object_or_404, redirect, render
|
||||
from django.urls import reverse
|
||||
from django.utils import timezone
|
||||
from django.utils.text import slugify
|
||||
from django.views.decorators.http import require_POST
|
||||
|
||||
from blog.models import Category, Post, Tag
|
||||
from cabinet.access import is_unlocked, minutes_left, unlock_minutes
|
||||
|
||||
from .forms import CategoryForm, MarkdownUploadForm, PostForm
|
||||
from .utils import (
|
||||
descendant_ids,
|
||||
first_heading,
|
||||
get_or_create_category,
|
||||
get_or_create_tag,
|
||||
make_category_slug,
|
||||
make_post_slug,
|
||||
parse_date_value,
|
||||
parse_front_matter,
|
||||
plain_excerpt,
|
||||
remove_first_heading,
|
||||
split_names,
|
||||
)
|
||||
|
||||
MAX_MD_BYTES = 2 * 1024 * 1024
|
||||
|
||||
|
||||
def _lock_context(request):
|
||||
return {
|
||||
"minutes_left": minutes_left(request),
|
||||
"unlock_minutes": unlock_minutes(),
|
||||
}
|
||||
|
||||
|
||||
def _form_error_text(form):
|
||||
parts = []
|
||||
for field_name, errors in form.errors.items():
|
||||
label = form.fields[field_name].label if field_name in form.fields else "表单"
|
||||
parts.append("{}:{}".format(label, errors[0]))
|
||||
return ";".join(parts) or "请检查输入"
|
||||
|
||||
|
||||
def _category_redirect(category_id=None):
|
||||
base = reverse("studio:index")
|
||||
if category_id:
|
||||
return "{}?edit_cat={}#categories".format(base, category_id)
|
||||
return base + "#categories"
|
||||
|
||||
|
||||
def index(request):
|
||||
if not is_unlocked(request):
|
||||
return render(request, "studio/lock.html", _lock_context(request))
|
||||
|
||||
status = request.GET.get("status", "all")
|
||||
if status not in {"all", "published", "draft"}:
|
||||
status = "all"
|
||||
|
||||
category_raw = request.GET.get("category", "")
|
||||
category_id = int(category_raw) if category_raw.isdigit() else None
|
||||
query = request.GET.get("q", "").strip()
|
||||
|
||||
posts = (
|
||||
Post.objects.prefetch_related("categories", "tags")
|
||||
.order_by("-published_at", "-id")
|
||||
)
|
||||
if status != "all":
|
||||
posts = posts.filter(status=status)
|
||||
if category_id:
|
||||
posts = posts.filter(categories__id=category_id).distinct()
|
||||
if query:
|
||||
posts = posts.filter(
|
||||
Q(title__icontains=query)
|
||||
| Q(excerpt__icontains=query)
|
||||
| Q(content__icontains=query)
|
||||
)
|
||||
|
||||
page = Paginator(posts, 15).get_page(request.GET.get("page"))
|
||||
|
||||
categories = Category.objects.annotate(
|
||||
post_count=Count("posts", distinct=True)
|
||||
).order_by("name")
|
||||
|
||||
edit_category = None
|
||||
edit_raw = request.GET.get("edit_cat", "")
|
||||
if edit_raw.isdigit():
|
||||
edit_category = Category.objects.filter(pk=int(edit_raw)).first()
|
||||
|
||||
if edit_category:
|
||||
category_form = CategoryForm(initial={
|
||||
"id": edit_category.id,
|
||||
"name": edit_category.name,
|
||||
"slug": edit_category.slug,
|
||||
"description": edit_category.description,
|
||||
"parent": edit_category.parent_id,
|
||||
})
|
||||
else:
|
||||
category_form = CategoryForm()
|
||||
|
||||
stats = {
|
||||
"total": Post.objects.count(),
|
||||
"published": Post.objects.filter(status="published").count(),
|
||||
"draft": Post.objects.filter(status="draft").count(),
|
||||
"categories": categories.count(),
|
||||
"tags": Tag.objects.count(),
|
||||
}
|
||||
|
||||
context = {
|
||||
"page": page,
|
||||
"status": status,
|
||||
"category_id": category_id,
|
||||
"query": query,
|
||||
"filtered_count": page.paginator.count,
|
||||
"categories": categories,
|
||||
"edit_category": edit_category,
|
||||
"category_form": category_form,
|
||||
"upload_form": MarkdownUploadForm(),
|
||||
"stats": stats,
|
||||
**_lock_context(request),
|
||||
}
|
||||
return render(request, "studio/manage.html", context)
|
||||
|
||||
|
||||
def post_edit(request, post_id=None):
|
||||
if not is_unlocked(request):
|
||||
return redirect("studio:index")
|
||||
|
||||
post = get_object_or_404(Post, pk=post_id) if post_id else None
|
||||
|
||||
if request.method == "POST":
|
||||
form = PostForm(request.POST)
|
||||
if form.is_valid():
|
||||
data = form.cleaned_data
|
||||
title = data["title"].strip()
|
||||
content = data["content"]
|
||||
content_format = data["content_format"]
|
||||
requested_slug = data["slug"].strip()
|
||||
slug = make_post_slug(
|
||||
requested_slug,
|
||||
title,
|
||||
exclude_id=post.pk if post else None,
|
||||
)
|
||||
|
||||
if post is None:
|
||||
post = Post.objects.create(
|
||||
title=title,
|
||||
slug=slug,
|
||||
content=content,
|
||||
content_format=content_format,
|
||||
excerpt=data["excerpt"].strip()
|
||||
or plain_excerpt(content, content_format),
|
||||
published_at=data["published_at"],
|
||||
status=data["status"],
|
||||
)
|
||||
else:
|
||||
post.title = title
|
||||
post.slug = slug
|
||||
post.content = content
|
||||
post.content_format = content_format
|
||||
post.excerpt = data["excerpt"].strip() or plain_excerpt(content, content_format)
|
||||
post.published_at = data["published_at"]
|
||||
post.status = data["status"]
|
||||
post.save()
|
||||
|
||||
selected_tags = list(data["tags"])
|
||||
for name in re.split(r"[,,、]", data["new_tags"] or ""):
|
||||
tag = get_or_create_tag(name)
|
||||
if tag:
|
||||
selected_tags.append(tag)
|
||||
selected_tags = list({tag.pk: tag for tag in selected_tags}.values())
|
||||
|
||||
post.categories.set(list(data["categories"]))
|
||||
post.tags.set(selected_tags)
|
||||
|
||||
messages.success(request, "文章已保存。")
|
||||
if requested_slug and slug != slugify(requested_slug):
|
||||
messages.info(
|
||||
request,
|
||||
"URL 别名已调整为 /post/{}/。".format(slug),
|
||||
)
|
||||
return redirect("studio:post_edit", post_id=post.id)
|
||||
|
||||
messages.error(request, "保存失败:{}".format(_form_error_text(form)))
|
||||
else:
|
||||
if post:
|
||||
initial = {
|
||||
"title": post.title,
|
||||
"slug": post.slug,
|
||||
"content": post.content,
|
||||
"content_format": post.content_format,
|
||||
"excerpt": post.excerpt,
|
||||
"published_at": timezone.localtime(post.published_at).strftime("%Y-%m-%dT%H:%M"),
|
||||
"status": post.status,
|
||||
"categories": list(post.categories.values_list("pk", flat=True)),
|
||||
"tags": list(post.tags.values_list("pk", flat=True)),
|
||||
}
|
||||
else:
|
||||
initial = {
|
||||
"content_format": "markdown",
|
||||
"status": "draft",
|
||||
"published_at": timezone.localtime(timezone.now()).strftime("%Y-%m-%dT%H:%M"),
|
||||
}
|
||||
form = PostForm(initial=initial)
|
||||
|
||||
context = {
|
||||
"post": post,
|
||||
"form": form,
|
||||
"is_new": post is None,
|
||||
"categories": Category.objects.annotate(
|
||||
post_count=Count("posts", distinct=True)
|
||||
).order_by("name"),
|
||||
"tags": Tag.objects.order_by("name"),
|
||||
**_lock_context(request),
|
||||
}
|
||||
return render(request, "studio/editor.html", context)
|
||||
|
||||
|
||||
@require_POST
|
||||
def post_delete(request, post_id):
|
||||
if not is_unlocked(request):
|
||||
return redirect("studio:index")
|
||||
|
||||
post = get_object_or_404(Post, pk=post_id)
|
||||
title = post.title
|
||||
post.delete()
|
||||
messages.success(request, "已删除文章「{}」。".format(title))
|
||||
return redirect("studio:index")
|
||||
|
||||
|
||||
@require_POST
|
||||
def upload_markdown(request):
|
||||
if not is_unlocked(request):
|
||||
return redirect("studio:index")
|
||||
|
||||
form = MarkdownUploadForm(request.POST, request.FILES)
|
||||
if not form.is_valid():
|
||||
messages.error(request, "上传失败:{}".format(_form_error_text(form)))
|
||||
return redirect("studio:index")
|
||||
|
||||
uploaded = form.cleaned_data["file"]
|
||||
filename = uploaded.name or ""
|
||||
if not filename.lower().endswith((".md", ".markdown")):
|
||||
messages.error(request, "只支持 .md / .markdown 文件。")
|
||||
return redirect("studio:index")
|
||||
if uploaded.size and uploaded.size > MAX_MD_BYTES:
|
||||
messages.error(request, "Markdown 文件不能超过 2 MB。")
|
||||
return redirect("studio:index")
|
||||
|
||||
try:
|
||||
raw = uploaded.read().decode("utf-8-sig")
|
||||
except UnicodeDecodeError:
|
||||
messages.error(request, "文件不是 UTF-8 编码,转码后再试。")
|
||||
return redirect("studio:index")
|
||||
|
||||
meta, body = parse_front_matter(raw)
|
||||
meta_title = (meta.get("title") or "").strip()
|
||||
heading = first_heading(body)
|
||||
|
||||
if meta_title:
|
||||
title = meta_title
|
||||
if heading and heading == meta_title:
|
||||
body = remove_first_heading(body)
|
||||
elif heading:
|
||||
title = heading
|
||||
body = remove_first_heading(body)
|
||||
else:
|
||||
title = Path(filename).stem
|
||||
|
||||
title = title.strip()[:200] or "未命名文章"
|
||||
content = body.strip()
|
||||
if not content:
|
||||
messages.error(request, "Markdown 没有正文内容。")
|
||||
return redirect("studio:index")
|
||||
|
||||
slug = make_post_slug(meta.get("slug", ""), title, filename)
|
||||
|
||||
status = (meta.get("status") or "").strip().lower()
|
||||
if status not in {"draft", "published"}:
|
||||
status = form.cleaned_data["status"]
|
||||
|
||||
published_at = parse_date_value(meta.get("date", "")) or timezone.now()
|
||||
excerpt = (meta.get("excerpt") or "").strip() or plain_excerpt(content, "markdown")
|
||||
|
||||
post = Post.objects.create(
|
||||
title=title,
|
||||
slug=slug,
|
||||
content=content,
|
||||
content_format="markdown",
|
||||
excerpt=excerpt,
|
||||
published_at=published_at,
|
||||
status=status,
|
||||
)
|
||||
|
||||
selected_categories = []
|
||||
form_category = form.cleaned_data["category"]
|
||||
if form_category:
|
||||
selected_categories.append(form_category)
|
||||
for name in split_names(meta.get("categories", "")):
|
||||
category = get_or_create_category(name)
|
||||
if category:
|
||||
selected_categories.append(category)
|
||||
selected_categories = list({c.pk: c for c in selected_categories}.values())
|
||||
post.categories.set(selected_categories)
|
||||
|
||||
selected_tags = []
|
||||
for name in split_names(meta.get("tags", "")):
|
||||
tag = get_or_create_tag(name)
|
||||
if tag:
|
||||
selected_tags.append(tag)
|
||||
selected_tags = list({t.pk: t for t in selected_tags}.values())
|
||||
post.tags.set(selected_tags)
|
||||
|
||||
messages.success(
|
||||
request,
|
||||
"已从 Markdown 创建「{}」,确认后可以发布。".format(post.title),
|
||||
)
|
||||
return redirect("studio:post_edit", post_id=post.id)
|
||||
|
||||
|
||||
@require_POST
|
||||
def category_save(request):
|
||||
if not is_unlocked(request):
|
||||
return redirect("studio:index")
|
||||
|
||||
form = CategoryForm(request.POST)
|
||||
if not form.is_valid():
|
||||
messages.error(request, "分类保存失败:{}".format(_form_error_text(form)))
|
||||
return redirect(_category_redirect(form.data.get("id")))
|
||||
|
||||
category_id = form.cleaned_data.get("id")
|
||||
category = Category.objects.filter(pk=category_id).first() if category_id else None
|
||||
name = form.cleaned_data["name"].strip()
|
||||
|
||||
duplicates = Category.objects.filter(name=name)
|
||||
if category:
|
||||
duplicates = duplicates.exclude(pk=category.pk)
|
||||
if duplicates.exists():
|
||||
messages.error(request, "分类名称「{}」已存在。".format(name))
|
||||
return redirect(_category_redirect(category_id))
|
||||
|
||||
parent = form.cleaned_data["parent"]
|
||||
if category and parent and (
|
||||
parent.pk == category.pk or parent.pk in descendant_ids(category)
|
||||
):
|
||||
messages.error(request, "上级分类不能是自身或自己的子分类。")
|
||||
return redirect(_category_redirect(category_id))
|
||||
|
||||
slug = make_category_slug(
|
||||
form.cleaned_data["slug"],
|
||||
name,
|
||||
exclude_id=category.pk if category else None,
|
||||
)
|
||||
description = form.cleaned_data["description"].strip()
|
||||
|
||||
if category:
|
||||
category.name = name
|
||||
category.slug = slug
|
||||
category.description = description
|
||||
category.parent = parent
|
||||
category.save()
|
||||
messages.success(request, "分类「{}」已更新。".format(name))
|
||||
else:
|
||||
Category.objects.create(
|
||||
name=name,
|
||||
slug=slug,
|
||||
description=description,
|
||||
parent=parent,
|
||||
)
|
||||
messages.success(request, "分类「{}」已创建。".format(name))
|
||||
|
||||
return redirect(_category_redirect(category_id))
|
||||
|
||||
|
||||
@require_POST
|
||||
def category_delete(request, category_id):
|
||||
if not is_unlocked(request):
|
||||
return redirect("studio:index")
|
||||
|
||||
category = get_object_or_404(Category, pk=category_id)
|
||||
name = category.name
|
||||
category.delete()
|
||||
messages.success(request, "已删除分类「{}」,文章保留。".format(name))
|
||||
return redirect(_category_redirect())
|
||||
Reference in New Issue
Block a user