From 128dc20cd584b5be8fbf291fcdf9ec39050d04f5 Mon Sep 17 00:00:00 2001 From: xiaoan <419177984@qq.com> Date: Sat, 21 Nov 2026 12:52:28 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=A0=E5=85=A5=E3=80=8C=E6=8B=BE=E7=BC=96?= =?UTF-8?q?=E3=80=8D=E5=86=99=E4=BD=9C=E5=8F=B0=EF=BC=9A=E6=96=87=E7=AB=A0?= =?UTF-8?q?=20/=20=E5=88=86=E7=B1=BB=E7=AE=A1=E7=90=86=20+=20Markdown=20?= =?UTF-8?q?=E4=B8=8A=E4=BC=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 studio 应用与 /manage/ 写作台 - 文章增删改查、状态/分类/标签、搜索筛选分页 - 分类增删改查,支持父分类 - 直接上传 .md(front matter)并创建文章,编辑页支持 Markdown 导入 - Post 增加 content_format,公开文章页支持 Markdown 渲染 - 复用拾匣密码解锁;首页页脚新增写作台入口 --- blog/migrations/0004_post_content_format.py | 23 + blog/models.py | 26 + blog/static/blog/css/style.css | 2 + blog/templates/base2.html | 2 + blog/templates/base_content.html | 1 + blog/templates/post_detail.html | 2 +- blog/views.py | 2 +- blogsite/settings.py | 1 + blogsite/urls.py | 1 + studio/__init__.py | 0 studio/apps.py | 7 + studio/forms.py | 171 +++++ studio/static/studio/studio.css | 721 ++++++++++++++++++++ studio/static/studio/studio.js | 243 +++++++ studio/templates/studio/_messages.html | 7 + studio/templates/studio/editor.html | 144 ++++ studio/templates/studio/lock.html | 35 + studio/templates/studio/manage.html | 200 ++++++ studio/urls.py | 15 + studio/utils.py | 177 +++++ studio/views.py | 388 +++++++++++ 21 files changed, 2166 insertions(+), 2 deletions(-) create mode 100644 blog/migrations/0004_post_content_format.py create mode 100644 studio/__init__.py create mode 100644 studio/apps.py create mode 100644 studio/forms.py create mode 100644 studio/static/studio/studio.css create mode 100644 studio/static/studio/studio.js create mode 100644 studio/templates/studio/_messages.html create mode 100644 studio/templates/studio/editor.html create mode 100644 studio/templates/studio/lock.html create mode 100644 studio/templates/studio/manage.html create mode 100644 studio/urls.py create mode 100644 studio/utils.py create mode 100644 studio/views.py diff --git a/blog/migrations/0004_post_content_format.py b/blog/migrations/0004_post_content_format.py new file mode 100644 index 0000000..57e32d0 --- /dev/null +++ b/blog/migrations/0004_post_content_format.py @@ -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="内容格式", + ), + ), + ] diff --git a/blog/models.py b/blog/models.py index a0413bf..393f06b 100644 --- a/blog/models.py +++ b/blog/models.py @@ -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): """ diff --git a/blog/static/blog/css/style.css b/blog/static/blog/css/style.css index f818bd4..dbd1a58 100644 --- a/blog/static/blog/css/style.css +++ b/blog/static/blog/css/style.css @@ -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); } /* ========================================================= 脑图容器 diff --git a/blog/templates/base2.html b/blog/templates/base2.html index 8baf85f..272ec56 100644 --- a/blog/templates/base2.html +++ b/blog/templates/base2.html @@ -181,6 +181,8 @@ Powered by xiaoan + + 写作台 diff --git a/blog/templates/base_content.html b/blog/templates/base_content.html index 33f9262..2d82ac1 100644 --- a/blog/templates/base_content.html +++ b/blog/templates/base_content.html @@ -26,6 +26,7 @@ {% block extra_css %}{% endblock %} + {% block extra_head %}{% endblock %} diff --git a/blog/templates/post_detail.html b/blog/templates/post_detail.html index fa008c5..dc6a192 100644 --- a/blog/templates/post_detail.html +++ b/blog/templates/post_detail.html @@ -47,7 +47,7 @@
- {{ post.content|safe }} + {{ post.rendered_content|safe }}
{% if post.tags.all %} diff --git a/blog/views.py b/blog/views.py index b48958b..50b46a7 100644 --- a/blog/views.py +++ b/blog/views.py @@ -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)) diff --git a/blogsite/settings.py b/blogsite/settings.py index 0469bfd..1bae638 100644 --- a/blogsite/settings.py +++ b/blogsite/settings.py @@ -45,6 +45,7 @@ INSTALLED_APPS = [ "cabinet", "reflections", "moments", + "studio", "rest_framework", ] diff --git a/blogsite/urls.py b/blogsite/urls.py index 2b051cf..37bd9cb 100644 --- a/blogsite/urls.py +++ b/blogsite/urls.py @@ -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")), diff --git a/studio/__init__.py b/studio/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/studio/apps.py b/studio/apps.py new file mode 100644 index 0000000..207bfaf --- /dev/null +++ b/studio/apps.py @@ -0,0 +1,7 @@ +from django.apps import AppConfig + + +class StudioConfig(AppConfig): + default_auto_field = "django.db.models.BigAutoField" + name = "studio" + verbose_name = "拾编" diff --git a/studio/forms.py b/studio/forms.py new file mode 100644 index 0000000..b3e6f29 --- /dev/null +++ b/studio/forms.py @@ -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") diff --git a/studio/static/studio/studio.css b/studio/static/studio/studio.css new file mode 100644 index 0000000..dbd25ff --- /dev/null +++ b/studio/static/studio/studio.css @@ -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); } diff --git a/studio/static/studio/studio.js b/studio/static/studio/studio.js new file mode 100644 index 0000000..d3b4003 --- /dev/null +++ b/studio/static/studio/studio.js @@ -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+/, ''); + } +})(); diff --git a/studio/templates/studio/_messages.html b/studio/templates/studio/_messages.html new file mode 100644 index 0000000..4cf2435 --- /dev/null +++ b/studio/templates/studio/_messages.html @@ -0,0 +1,7 @@ +{% if messages %} +
+ {% for message in messages %} +

{{ message }}

+ {% endfor %} +
+{% endif %} diff --git a/studio/templates/studio/editor.html b/studio/templates/studio/editor.html new file mode 100644 index 0000000..05feec3 --- /dev/null +++ b/studio/templates/studio/editor.html @@ -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 拾光写字的地方{% endblock %} +{% block extra_head %}{% endblock %} + +{% block content %} +
+ ← 写作台 + +
+
+

拾编 · STUDIO

+

{% if is_new %}新建文章{% else %}编辑文章{% endif %}

+

+ {% if post %} + /post/{{ post.slug }}/ · 最后更新 {{ post.updated_at|date:"Y-m-d H:i" }} + {% else %} + 写好后可以先存草稿,再从写作台发布。 + {% endif %} +

+
+
+ {% if post and post.status == 'published' %} + 查看文章 ↗ + {% endif %} + +
+
+ + {% include "studio/_messages.html" %} + +
+ {% csrf_token %} + {{ form.non_field_errors }} + +
+
+ + {{ form.title }} + {{ form.title.errors }} +
+ +
+
+ + {{ form.slug }} +

留空会自动生成;文章地址是 /post/<slug>/。

+
+
+ + {{ form.content_format }} +
+
+ +
+
+ + + 0 字 +
+ {{ form.content }} + {{ form.content.errors }} +
+
+ + +
+ + {% if post %} +
+ {% csrf_token %} +
+ {% endif %} +
+{% endblock %} + +{% block extra_css %} + +{% endblock %} + +{% block extra_js %} + +{% endblock %} diff --git a/studio/templates/studio/lock.html b/studio/templates/studio/lock.html new file mode 100644 index 0000000..beb5b7d --- /dev/null +++ b/studio/templates/studio/lock.html @@ -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 拾光写字的地方{% endblock %} +{% block extra_head %}{% endblock %} + +{% block content %} +
+
+

拾编 · STUDIO

+

写作台

+

文章、分类和草稿,只对站点主人开放。

+ +
+ + + +
+ + +

与拾匣共用密码

+
+
+{% endblock %} + +{% block extra_css %} + +{% endblock %} + +{% block extra_js %} + +{% endblock %} diff --git a/studio/templates/studio/manage.html b/studio/templates/studio/manage.html new file mode 100644 index 0000000..1bb65a2 --- /dev/null +++ b/studio/templates/studio/manage.html @@ -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 拾光写字的地方{% endblock %} +{% block extra_head %}{% endblock %} + +{% block content %} +
+
+
+

拾编 · STUDIO

+

写作台

+

文章、分类和草稿,都放在一张桌子上。

+
+
+ 回首页 + +
+
+ + {% include "studio/_messages.html" %} + +
+
{{ stats.total }}全部文章
+
{{ stats.published }}已发布
+
{{ stats.draft }}草稿
+
{{ stats.categories }}分类
+
{{ stats.tags }}标签
+
+ +
+ + 新建文章 + + 上传后先进入编辑页,确认后再发布。 +
+ + + +
+
+
+

文章 {{ filtered_count }}

+
+ +
+ + + + + 重置 +
+ +
+ + + + + + + + + + + + {% for post in page %} + + + + + + + + {% empty %} + + {% endfor %} + +
文章状态分类发布时间
+ {{ post.title }} + /post/{{ post.slug }}/ + {{ post.get_status_display }} + + {% for cat in post.categories.all %}{{ cat.name }}{% empty %}未分类{% endfor %} + + + 编辑 + {% if post.status == 'published' %} + 查看 + {% endif %} +
+ {% csrf_token %} + +
+
没有符合条件的文章。
+
+ + {% if page.paginator.num_pages > 1 %} + + {% endif %} +
+ + +
+ +

写作台只对站点主人开放;解锁状态与拾匣共用,锁定后此页会回到密码界面。

+
+{% endblock %} + +{% block extra_css %} + +{% endblock %} + +{% block extra_js %} + +{% endblock %} diff --git a/studio/urls.py b/studio/urls.py new file mode 100644 index 0000000..ad614ad --- /dev/null +++ b/studio/urls.py @@ -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//edit/", views.post_edit, name="post_edit"), + path("posts//delete/", views.post_delete, name="post_delete"), + path("categories/save/", views.category_save, name="category_save"), + path("categories//delete/", views.category_delete, name="category_delete"), +] diff --git a/studio/utils.py b/studio/utils.py new file mode 100644 index 0000000..90bc77a --- /dev/null +++ b/studio/utils.py @@ -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 diff --git a/studio/views.py b/studio/views.py new file mode 100644 index 0000000..ee9cd12 --- /dev/null +++ b/studio/views.py @@ -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())