diff --git a/blog/templates/base2.html b/blog/templates/base2.html index 272ec56..cccc0d3 100644 --- a/blog/templates/base2.html +++ b/blog/templates/base2.html @@ -182,6 +182,8 @@ Powered by xiaoan + 拾脉 + 写作台 diff --git a/mindmaps/admin.py b/mindmaps/admin.py index 0dd1fc0..367f080 100644 --- a/mindmaps/admin.py +++ b/mindmaps/admin.py @@ -1,29 +1,48 @@ from django.contrib import admin -from django import forms -from .models import MindMap + +from .models import MindFolder, MindMap + + +@admin.register(MindFolder) +class MindFolderAdmin(admin.ModelAdmin): + list_display = ("id", "name", "parent", "map_count", "created_at") + search_fields = ("name", "description") + prepopulated_fields = {"slug": ("name",)} + readonly_fields = ("created_at", "updated_at") + + @admin.display(description="脑图数") + def map_count(self, obj): + return obj.maps.count() @admin.register(MindMap) class MindMapAdmin(admin.ModelAdmin): - list_display = ("title", "created_at", "has_mindmap") - search_fields = ("title",) + list_display = ( + "id", "title", "folder", "sheet_count", "node_count", "has_mindmap", "updated_at", + ) + list_filter = ("folder", "created_at") + search_fields = ("title", "description", "original_name") prepopulated_fields = {"slug": ("title",)} - readonly_fields = ("updated_at",) + readonly_fields = ("created_at", "updated_at", "original_name", "sheet_count") + list_select_related = ("folder",) + @admin.display(description="节点") + def node_count(self, obj): + return obj.node_total + + @admin.display(boolean=True, description="已解析") def has_mindmap(self, obj): return bool(obj.mindmap_data and obj.mindmap_data.get("data")) - has_mindmap.boolean = True - has_mindmap.short_description = "已解析" def save_model(self, request, obj, form, change): - is_new = not obj.pk super().save_model(request, obj, form, change) - - if "xmind_file" in form.changed_data and obj.xmind_file: + if obj.xmind_file and ("xmind_file" in form.changed_data or not obj.mindmap_data): try: obj.parse_and_store(obj.xmind_file.path) - self.message_user(request, f"脑图「{obj.title}」解析成功") - except Exception as e: + self.message_user(request, "脑图「{}」解析成功".format(obj.title)) + except Exception as exc: self.message_user( - request, f"解析失败: {e}", level="error" - ) \ No newline at end of file + request, + "解析失败:{}".format(exc), + level="error", + ) diff --git a/mindmaps/forms.py b/mindmaps/forms.py new file mode 100644 index 0000000..27d02e6 --- /dev/null +++ b/mindmaps/forms.py @@ -0,0 +1,145 @@ +import zipfile + +from django import forms +from django.core.exceptions import ValidationError + +from .models import MindFolder, MindMap + +MAX_XMIND_MB = 30 + + +def descendant_ids(folder): + found = set() + stack = [folder.pk] + while stack: + parent_id = stack.pop() + children = list( + MindFolder.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 + + +class MindFolderForm(forms.Form): + id = forms.IntegerField(required=False, widget=forms.HiddenInput) + name = forms.CharField( + max_length=100, + label="目录名称", + widget=forms.TextInput(attrs={"class": "mm-input", "placeholder": "例如 C++、Python"}), + ) + slug = forms.CharField( + required=False, + max_length=100, + label="URL 别名", + widget=forms.TextInput(attrs={"class": "mm-input", "placeholder": "留空自动生成,建议英文"}), + ) + description = forms.CharField( + required=False, + label="简介", + widget=forms.Textarea(attrs={ + "class": "mm-input", + "rows": 2, + "placeholder": "这个目录学什么(可选)", + }), + ) + parent = forms.ModelChoiceField( + queryset=MindFolder.objects.none(), + required=False, + label="上级目录", + empty_label="无上级目录", + widget=forms.Select(attrs={"class": "mm-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 = MindFolder.objects.order_by("name") + if edit_id: + folder = MindFolder.objects.filter(pk=edit_id).first() + if folder: + queryset = queryset.exclude(pk__in={folder.pk} | descendant_ids(folder)) + self.fields["parent"].queryset = queryset + + +class MindMapUploadForm(forms.ModelForm): + class Meta: + model = MindMap + fields = ["xmind_file", "title", "folder", "description"] + widgets = { + "xmind_file": forms.ClearableFileInput(attrs={ + "class": "mm-file", + "accept": ".xmind", + }), + "title": forms.TextInput(attrs={ + "class": "mm-input", + "placeholder": "留空则使用脑图根节点标题", + }), + "folder": forms.Select(attrs={"class": "mm-input"}), + "description": forms.Textarea(attrs={ + "class": "mm-input", + "rows": 2, + "placeholder": "一句话说明这份脑图(可选)", + }), + } + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.fields["xmind_file"].required = True + self.fields["title"].required = False + self.fields["folder"].queryset = MindFolder.objects.order_by("name") + self.fields["folder"].empty_label = "不归入目录" + + def clean_xmind_file(self): + uploaded = self.cleaned_data["xmind_file"] + name = uploaded.name or "" + + if not name.lower().endswith(".xmind"): + raise ValidationError("只支持 .xmind 文件。") + if uploaded.size and uploaded.size > MAX_XMIND_MB * 1024 * 1024: + raise ValidationError("XMind 文件不能超过 {} MB。".format(MAX_XMIND_MB)) + + try: + if not zipfile.is_zipfile(uploaded): + raise ValidationError("不是有效的 XMind 文件。") + except ValidationError: + raise + except Exception: + raise ValidationError("不是有效的 XMind 文件。") + finally: + try: + uploaded.seek(0) + except Exception: + pass + + return uploaded + + +class MindMapEditForm(forms.ModelForm): + class Meta: + model = MindMap + fields = ["title", "folder", "description"] + widgets = { + "title": forms.TextInput(attrs={"class": "mm-input"}), + "folder": forms.Select(attrs={"class": "mm-input"}), + "description": forms.Textarea(attrs={"class": "mm-input", "rows": 2}), + } + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.fields["folder"].queryset = MindFolder.objects.order_by("name") + self.fields["folder"].empty_label = "不归入目录" diff --git a/mindmaps/migrations/0002_mindmap_original_name_mindmap_sheet_count_mindfolder_and_more.py b/mindmaps/migrations/0002_mindmap_original_name_mindmap_sheet_count_mindfolder_and_more.py new file mode 100644 index 0000000..27d34b5 --- /dev/null +++ b/mindmaps/migrations/0002_mindmap_original_name_mindmap_sheet_count_mindfolder_and_more.py @@ -0,0 +1,87 @@ +# Generated by Django 5.2.18 on 2026-11-21 04:56 + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ("mindmaps", "0001_initial"), + ] + + operations = [ + migrations.AddField( + model_name="mindmap", + name="original_name", + field=models.CharField( + blank=True, default="", max_length=255, verbose_name="原始文件名" + ), + ), + migrations.AddField( + model_name="mindmap", + name="sheet_count", + field=models.PositiveIntegerField(default=1, verbose_name="画布数量"), + ), + migrations.CreateModel( + name="MindFolder", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("name", models.CharField(max_length=100, verbose_name="名称")), + ( + "slug", + models.SlugField( + blank=True, max_length=100, unique=True, verbose_name="URL 别名" + ), + ), + ( + "description", + models.TextField(blank=True, default="", verbose_name="简介"), + ), + ( + "created_at", + models.DateTimeField(auto_now_add=True, verbose_name="创建时间"), + ), + ( + "updated_at", + models.DateTimeField(auto_now=True, verbose_name="更新时间"), + ), + ( + "parent", + models.ForeignKey( + blank=True, + null=True, + on_delete=django.db.models.deletion.CASCADE, + related_name="children", + to="mindmaps.mindfolder", + verbose_name="上级目录", + ), + ), + ], + options={ + "verbose_name": "脑图目录", + "verbose_name_plural": "脑图目录", + "ordering": ["name"], + }, + ), + migrations.AddField( + model_name="mindmap", + name="folder", + field=models.ForeignKey( + blank=True, + null=True, + on_delete=django.db.models.deletion.SET_NULL, + related_name="maps", + to="mindmaps.mindfolder", + verbose_name="所属目录", + ), + ), + ] diff --git a/mindmaps/models.py b/mindmaps/models.py index 0c7c2c3..2e9e900 100644 --- a/mindmaps/models.py +++ b/mindmaps/models.py @@ -1,46 +1,93 @@ -import json from django.db import models +from django.urls import reverse from django.utils.text import slugify -from django.urls import reverse # ← 加这个 import -from xmindparser import xmind_to_dict +from django.utils import timezone -def xmind_to_mindmap_format(parsed_data): - """ - 把 xmindparser 输出转成 simple-mind-map 标准格式 - """ - if not parsed_data: - raise ValueError("XMind 文件内容为空") - - sheet = parsed_data[0] - if "topic" not in sheet: - raise ValueError("XMind 第一个画布没有根节点") +def 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 conv(topic): - """递归转换节点""" - node = { - "data": { - "text": topic.get("title", "(无标题)") - } - } - subs = topic.get("topics") or [] - if subs: - node["children"] = [conv(t) for t in subs] - return node - return conv(sheet["topic"]) +def make_slug(value, fallback, max_length=200): + base = slugify(value or "") or slugify(fallback or "") + if not base: + base = "map-" + timezone.localtime().strftime("%Y%m%d-%H%M") + return base[:max_length] + + +class MindFolder(models.Model): + """学习目录,比如 C++ / Python;支持子目录。""" + + name = models.CharField("名称", max_length=100) + slug = models.SlugField("URL 别名", max_length=100, unique=True, blank=True) + description = models.TextField("简介", blank=True, default="") + parent = models.ForeignKey( + "self", + on_delete=models.CASCADE, + blank=True, + null=True, + related_name="children", + verbose_name="上级目录", + ) + created_at = models.DateTimeField("创建时间", auto_now_add=True) + updated_at = models.DateTimeField("更新时间", auto_now=True) + + class Meta: + ordering = ["name"] + verbose_name = "脑图目录" + verbose_name_plural = "脑图目录" + + def __str__(self): + return self.name + + def get_absolute_url(self): + return reverse("mindmaps:folder", args=[self.slug]) + + def save(self, *args, **kwargs): + if not self.slug: + base = slugify(self.name) or "folder" + if not slugify(self.name): + base = "folder-" + timezone.localtime().strftime("%Y%m%d-%H%M") + self.slug = unique_slug(self.__class__, base[:100], self.pk, 100) + super().save(*args, **kwargs) + + @property + def map_total(self): + return self.maps.count() class MindMap(models.Model): title = models.CharField("标题", max_length=200) slug = models.SlugField("别名", max_length=200, unique=True, blank=True) description = models.TextField("简介", blank=True, help_text="列表页显示") + folder = models.ForeignKey( + MindFolder, + on_delete=models.SET_NULL, + blank=True, + null=True, + related_name="maps", + verbose_name="所属目录", + ) xmind_file = models.FileField( "XMind 文件", upload_to="mindmaps/xmind/%Y/%m/", blank=True ) + original_name = models.CharField("原始文件名", max_length=255, blank=True, default="") + sheet_count = models.PositiveIntegerField("画布数量", default=1) mindmap_data = models.JSONField( - "脑图数据", default=dict, blank=True, - help_text="由 xmind 解析后生成的前端渲染数据" + "脑图数据", + default=dict, + blank=True, + help_text="由 xmind 解析后生成的前端渲染数据", ) created_at = models.DateTimeField("创建时间", auto_now_add=True) updated_at = models.DateTimeField("更新时间", auto_now=True) @@ -58,11 +105,32 @@ class MindMap(models.Model): def save(self, *args, **kwargs): if not self.slug: - self.slug = slugify(self.title) or f"mindmap-{self.pk or 'new'}" + base = make_slug(self.title, "mindmap", 200) + self.slug = unique_slug(self.__class__, base, self.pk, 200) super().save(*args, **kwargs) + @property + def node_total(self): + def count(node): + return 1 + sum(count(child) for child in node.get("children") or []) + + data = self.mindmap_data or {} + return count(data) if data.get("data") else 0 + def parse_and_store(self, file_path): - """解析 xmind 文件并存储为前端可用格式""" - parsed = xmind_to_dict(file_path) - self.mindmap_data = xmind_to_mindmap_format(parsed) - self.save() \ No newline at end of file + """解析 xmind 文件,写入脑图数据和元信息。""" + from .xmind import parse_xmind + + data, info = parse_xmind(file_path) + self.mindmap_data = data + self.sheet_count = info["sheet_count"] + if not (self.title or "").strip(): + self.title = (info["root_title"] or "未命名脑图")[:200] + if not self.slug: + self.slug = unique_slug( + self.__class__, + make_slug(self.title, "mindmap", 200), + self.pk, + 200, + ) + self.save() diff --git a/mindmaps/static/mindmaps/mindmaps.css b/mindmaps/static/mindmaps/mindmaps.css new file mode 100644 index 0000000..6cdc723 --- /dev/null +++ b/mindmaps/static/mindmaps/mindmaps.css @@ -0,0 +1,627 @@ +/* ========================================================= + 拾脉 · 学习脑图 + 目录 → XMind 文件 → 在线预览 + ========================================================= */ + +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; } + +.mm { + max-width: 1120px; + margin: 0 auto; +} + +/* ---------- 头部 ---------- */ +.mm-head { text-align: center; margin-bottom: 4px; } +.mm-head-left { text-align: left; } +.mm-eyebrow { + margin: 0 0 14px; + color: var(--ink-faint); + font-size: 10.5px; + font-weight: 500; + letter-spacing: .26em; +} +.mm-eyebrow span { margin-right: 8px; color: var(--gold); font-size: 10px; } +.mm-head h1 { + margin: 0 0 12px; + color: var(--ink); + font-family: 'Noto Serif SC', serif; + font-size: clamp(1.9rem, 4.2vw, 2.8rem); + font-weight: 900; + line-height: 1.35; + letter-spacing: .01em; + text-wrap: balance; +} +.mm-head-left h1 { font-size: clamp(1.7rem, 3.6vw, 2.4rem); } +.mm-head h1 em { + font-style: normal; + color: var(--accent); + background-image: linear-gradient(transparent 68%, var(--accent-soft) 68%); + padding: 0 .08em; +} +.mm-sub { + max-width: 620px; + margin: 0 auto; + color: var(--ink-faint); + font-size: 13px; + line-height: 1.9; +} +.mm-head-left .mm-sub { margin-left: 0; } +.mm-map-head { + display: flex; + align-items: flex-end; + justify-content: space-between; + gap: 20px; + flex-wrap: wrap; +} +.mm-head-actions { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; } + +/* ---------- 面包屑 ---------- */ +.mm-crumbs { + display: flex; + align-items: center; + gap: 6px; + flex-wrap: wrap; + margin-bottom: 22px; + color: var(--ink-faint); + font-size: 11.5px; +} +.mm-crumbs a { color: var(--ink-faint); text-decoration: none; transition: color .18s ease; } +.mm-crumbs a:hover { color: var(--accent); } +.mm-crumbs .is-current { color: var(--ink-soft); } + +/* ---------- 解锁条 ---------- */ +.mm-lock { + display: flex; + align-items: center; + gap: 10px; + flex-wrap: wrap; + margin-top: 26px; + padding: 10px 14px; + border: 1px solid var(--line); + border-radius: 14px; + background: var(--paper); + box-shadow: var(--shadow-sm); +} +.mm-lock-dot { + width: 7px; height: 7px; + flex: none; + border-radius: 50%; + background: var(--ink-faint); + opacity: .6; +} +.mm-lock.is-open .mm-lock-dot { + background: #6b8f71; + opacity: 1; + box-shadow: 0 0 0 3px rgba(107, 143, 113, .18); +} +.mm-lock-text { color: var(--ink-soft); font-size: 12px; } +.mm-lock.is-open .mm-lock-text { color: #5d7f63; } +:root[data-theme="dark"] .mm-lock.is-open .mm-lock-text { color: #8fc096; } +.mm-unlock { display: flex; align-items: center; gap: 6px; margin-left: auto; } +.mm-unlock input { + width: 150px; + padding: 6px 10px; + border: 1px solid var(--line); + border-radius: 8px; + background: var(--paper-soft); + color: var(--ink); + font-family: inherit; + font-size: 12px; + outline: none; +} +.mm-unlock input:focus { + border-color: color-mix(in srgb, var(--accent) 45%, transparent); + box-shadow: 0 0 0 3px var(--accent-soft); +} +.mm-lock > .mm-btn { margin-left: auto; } +.mm-lock-hint { color: var(--ink-faint); font-size: 10.5px; } +.mm-error { + margin-top: 10px; + padding: 9px 13px; + border: 1px solid color-mix(in srgb, var(--accent) 30%, var(--line)); + border-radius: 10px; + background: var(--accent-soft); + color: var(--accent); + font-size: 12px; + line-height: 1.7; +} + +/* ---------- 按钮 ---------- */ +.mm-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; +} +.mm-btn:hover { + color: var(--accent); + border-color: color-mix(in srgb, var(--accent) 45%, transparent); + background: var(--accent-soft); + transform: translateY(-1px); +} +.mm-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); +} +.mm-btn-primary:hover { + color: #fff; + border-color: transparent; + background: linear-gradient(135deg, var(--accent), var(--accent)); +} +.mm-btn-ghost { border-color: transparent; background: transparent; color: var(--ink-faint); } +.mm-btn-ghost:hover { background: var(--paper-soft); } +.mm-btn-danger { + border-color: color-mix(in srgb, var(--accent) 32%, var(--line)); + background: transparent; + color: var(--accent); +} +.mm-btn-danger:hover { background: var(--accent); color: #fff; border-color: var(--accent); } + +/* ---------- 统计 / 工具条 ---------- */ +.mm-stats { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 10px; + max-width: 520px; + margin: 20px auto 0; +} +.mm-stat { + padding: 12px 14px; + border: 1px solid var(--line); + border-radius: 12px; + background: var(--paper); + box-shadow: var(--shadow-sm); + text-align: center; +} +.mm-stat b { + display: block; + color: var(--ink); + font-family: 'Noto Serif SC', serif; + font-size: 21px; + font-weight: 900; + line-height: 1.2; +} +.mm-stat span { color: var(--ink-faint); font-size: 10px; letter-spacing: .05em; } + +.mm-toolbar { + display: flex; + align-items: center; + gap: 9px; + flex-wrap: wrap; + margin: 22px 0 14px; +} +.mm-toolbar-hint { color: var(--ink-faint); font-size: 10.5px; } + +/* ---------- 面板 / 表单 ---------- */ +.mm-panel { + margin-bottom: 18px; + padding: 18px 20px; + border: 1px solid var(--line); + border-radius: 16px; + background: var(--paper); + box-shadow: var(--shadow-sm); + animation: mm-rise .3s ease both; +} +.mm-panel[hidden] { display: none; } +.mm-form-grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 10px 16px; +} +.mm-form-grid label { + display: flex; + flex-direction: column; + gap: 5px; + color: var(--ink-faint); + font-size: 10.5px; + letter-spacing: .04em; +} +.mm-form-grid label.wide { grid-column: 1 / -1; } +.mm-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; +} +.mm-input:focus { + border-color: color-mix(in srgb, var(--accent) 45%, transparent); + box-shadow: 0 0 0 3px var(--accent-soft); +} +textarea.mm-input { resize: vertical; } +.mm-file { + width: 100%; + padding: 8px 10px; + border: 1px dashed var(--line); + border-radius: 8px; + background: var(--paper-soft); + color: var(--ink-soft); + font-family: inherit; + font-size: 11.5px; +} +.mm-form-actions { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; + margin-top: 12px; +} +.mm-delete-row { margin-top: 26px; } + +/* ---------- 区块 ---------- */ +.mm-section { margin-top: 30px; } +.mm-section-head { + display: flex; + align-items: center; + gap: 10px; + margin-bottom: 12px; +} +.mm-section-head h2 { + display: flex; + align-items: center; + gap: 9px; + margin: 0; + color: var(--ink); + font-family: 'Noto Serif SC', serif; + font-size: 16px; + font-weight: 700; + letter-spacing: .06em; +} +.mm-section-head h2::before { + content: '✦'; + color: var(--gold); + font-size: 10px; +} +.mm-section-head > span { + padding: 1px 8px; + border-radius: 999px; + background: var(--paper-soft); + color: var(--ink-faint); + font-size: 9.5px; +} + +/* ---------- 目录卡 ---------- */ +.mm-folders { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); + gap: 12px; +} +.mm-folder { + display: flex; + align-items: center; + gap: 13px; + padding: 16px 17px; + border: 1px solid var(--line); + border-radius: 16px; + background: var(--paper); + box-shadow: var(--shadow-sm); + text-decoration: none; + transition: transform .25s ease, box-shadow .25s ease, border-color .25s ease; +} +.mm-folder:hover { + transform: translateY(-3px); + border-color: color-mix(in srgb, var(--accent) 30%, var(--line)); + box-shadow: var(--shadow); +} +.mm-folder-mark { + display: grid; + place-items: center; + flex: none; + width: 38px; height: 38px; + border-radius: 11px; + background: var(--accent-soft); + color: var(--accent); + font-size: 15px; +} +.mm-folder-main { min-width: 0; flex: 1; display: flex; flex-direction: column; gap: 2px; } +.mm-folder-name { + overflow: hidden; + color: var(--ink); + font-family: 'Noto Serif SC', serif; + font-size: 14.5px; + font-weight: 700; + text-overflow: ellipsis; + white-space: nowrap; +} +.mm-folder-desc { + overflow: hidden; + color: var(--ink-faint); + font-size: 11px; + line-height: 1.6; + text-overflow: ellipsis; + white-space: nowrap; +} +.mm-folder-meta { color: var(--ink-faint); font-size: 10px; } +.mm-folder-arrow { flex: none; color: var(--ink-faint); font-size: 13px; transition: transform .2s ease, color .2s ease; } +.mm-folder:hover .mm-folder-arrow { color: var(--accent); transform: translateX(3px); } + +/* ---------- 脑图卡 ---------- */ +.mm-maps { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); + gap: 12px; +} +.mm-map-card { + display: flex; + align-items: flex-start; + gap: 13px; + padding: 15px 17px; + border: 1px solid var(--line); + border-radius: 16px; + background: var(--paper); + box-shadow: var(--shadow-sm); + text-decoration: none; + transition: transform .25s ease, box-shadow .25s ease, border-color .25s ease; +} +.mm-map-card:hover { + transform: translateY(-3px); + border-color: color-mix(in srgb, var(--c5) 32%, var(--line)); + box-shadow: var(--shadow); +} +.mm-map-mark { + display: grid; + place-items: center; + flex: none; + width: 38px; height: 38px; + border-radius: 11px; + background: rgba(141, 90, 131, .12); + color: var(--c5); + font-size: 15px; +} +.mm-map-main { min-width: 0; flex: 1; display: flex; flex-direction: column; gap: 3px; } +.mm-map-title { + overflow: hidden; + color: var(--ink); + font-family: 'Noto Serif SC', serif; + font-size: 14px; + font-weight: 700; + text-overflow: ellipsis; + white-space: nowrap; +} +.mm-map-desc { + overflow: hidden; + color: var(--ink-faint); + font-size: 11px; + line-height: 1.6; + text-overflow: ellipsis; + white-space: nowrap; +} +.mm-map-meta { color: var(--ink-faint); font-size: 10px; } +.mm-empty-line { + margin: 0; + padding: 20px; + border: 1px dashed var(--line); + border-radius: 12px; + color: var(--ink-faint); + font-size: 12px; +} + +/* ---------- 详情 ---------- */ +.mm-detail-grid { + display: grid; + grid-template-columns: minmax(0, 1fr) 310px; + gap: 16px; + align-items: start; + margin-top: 18px; +} +.mm-preview-card { + overflow: hidden; + border: 1px solid var(--line); + border-radius: 16px; + background: var(--paper); + box-shadow: var(--shadow-sm); +} +.mm-preview-toolbar { + display: flex; + align-items: center; + gap: 10px; + flex-wrap: wrap; + padding: 10px 13px; + border-bottom: 1px solid var(--line); + background: var(--paper); +} +.mm-view-title { + color: var(--ink); + font-family: 'Noto Serif SC', serif; + font-size: 12.5px; + font-weight: 700; +} +.mm-view-meta { color: var(--ink-faint); font-size: 10px; } +.mm-view-actions { + display: flex; + align-items: center; + gap: 4px; + flex-wrap: wrap; + margin-left: auto; +} +.mm-view-actions button { + min-width: 28px; + height: 26px; + padding: 0 8px; + border: 1px solid var(--line); + border-radius: 7px; + background: var(--paper-soft); + color: var(--ink-soft); + font-family: inherit; + font-size: 10.5px; + cursor: pointer; + transition: all .16s ease; +} +.mm-view-actions button:hover { + color: var(--accent); + border-color: var(--accent); + background: var(--accent-soft); +} +.mm-canvas { + position: relative; + height: min(70vh, 720px); + min-height: 480px; + overflow: hidden; + background: #fff; + touch-action: none; +} +.mm-canvas svg { width: 100% !important; height: 100% !important; } +.mm-canvas:fullscreen { width: 100vw; height: 100vh; background: #fff; } +.mm-loading { + position: absolute; + inset: 0; + display: grid; + place-items: center; + margin: 0; + color: #8a8279; + font-size: 12px; +} +.mm-fallback { + margin: 0; + padding: 12px 15px; + border-top: 1px solid var(--line); + background: var(--paper-soft); + color: var(--ink-faint); + font-size: 11px; + line-height: 1.8; +} + +.mm-side { display: flex; flex-direction: column; gap: 12px; } +.mm-meta-card, +.mm-outline-card { + padding: 16px 17px; + border: 1px solid var(--line); + border-radius: 14px; + background: var(--paper); + box-shadow: var(--shadow-sm); +} +.mm-meta-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; +} +.mm-meta-card dl { margin: 0; display: flex; flex-direction: column; gap: 8px; } +.mm-meta-card dl > div { display: flex; gap: 12px; align-items: baseline; } +.mm-meta-card dt { flex: none; width: 64px; color: var(--ink-faint); font-size: 10.5px; } +.mm-meta-card dd { margin: 0; min-width: 0; color: var(--ink-soft); font-size: 11.5px; word-break: break-word; } +.mm-meta-card dd a { color: var(--accent); text-decoration: none; } +.mm-meta-card .mm-file-name { + font-family: 'JetBrains Mono', monospace; + font-size: 10px; + color: var(--ink-faint); +} +.mm-meta-card .mm-btn { width: 100%; margin-top: 10px; } + +.mm-outline-card summary { + cursor: pointer; + color: var(--ink); + font-family: 'Noto Serif SC', serif; + font-size: 13px; + font-weight: 700; + letter-spacing: .06em; +} +.mm-outline-card summary::marker { color: var(--gold); } +.mm-outline { margin-top: 10px; max-height: 420px; overflow: auto; padding-right: 4px; } +.mm-outline ul { margin: 0; padding-left: 15px; } +.mm-outline li { margin: 3px 0; color: var(--ink-soft); font-size: 11.5px; line-height: 1.7; } +.mm-outline li > span { display: inline-block; padding: 1px 0; } +.mm-outline ul ul { margin-top: 2px; border-left: 1px dashed var(--line); padding-left: 12px; } +.mm-muted { margin: 0; color: var(--ink-faint); font-size: 11px; } + +.mm-note { + margin: 30px 0 0; + padding-top: 14px; + border-top: 1px dashed var(--line); + color: var(--ink-faint); + font-size: 10.5px; + line-height: 1.9; +} + +/* JS 提示 */ +.mm-js-toast { + position: fixed; + left: 50%; + bottom: 30px; + z-index: 1100; + max-width: min(90vw, 460px); + padding: 9px 15px; + 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; +} +.mm-js-toast.is-visible { opacity: 1; transform: translate(-50%, 0); } + +@keyframes mm-rise { + from { opacity: 0; transform: translateY(8px); } + to { opacity: 1; transform: none; } +} + +/* ---------- 响应式 ---------- */ +@media (max-width: 1000px) { + .mm-detail-grid { grid-template-columns: 1fr; } + .mm-side { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); } +} + +@media (max-width: 720px) { + .mm-head h1 { font-size: 1.85rem; } + .mm-map-head { align-items: flex-start; } + .mm-head-actions { width: 100%; } + .mm-stats { max-width: none; } + .mm-form-grid { grid-template-columns: 1fr; } + .mm-unlock { width: 100%; margin-left: 0; } + .mm-unlock input { flex: 1; width: auto; } + .mm-lock > .mm-btn { margin-left: 0; } + .mm-lock-hint { width: 100%; } + .mm-folders, .mm-maps { grid-template-columns: 1fr; } + .mm-canvas { height: 58vh; min-height: 380px; } + .mm-view-actions { width: 100%; margin-left: 0; } +} + +@media (max-width: 420px) { + .mm-stats { grid-template-columns: repeat(3, 1fr); gap: 6px; } + .mm-stat { padding: 9px 8px; } + .mm-stat b { font-size: 18px; } + .mm-folder, .mm-map-card { padding: 13px; } +} + +@media (prefers-reduced-motion: reduce) { + .mm-panel { animation: none; } + .mm-folder, .mm-map-card { transition: none; } +} diff --git a/mindmaps/static/mindmaps/mindmaps.js b/mindmaps/static/mindmaps/mindmaps.js new file mode 100644 index 0000000..f87877c --- /dev/null +++ b/mindmaps/static/mindmaps/mindmaps.js @@ -0,0 +1,294 @@ +/* ========================================================= + 拾脉 · 交互:解锁、面板、XMind 预览 + ========================================================= */ +(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('.mm-js-toast'); + if (!box) { + box = document.createElement('div'); + box.className = 'mm-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 = $('#mmError'); + if (box) { + box.textContent = message; + box.hidden = false; + return; + } + toast(message); + } + + function hideError() { + var box = $('#mmError'); + 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 = $('#mmUnlockForm'); + if (unlockForm) { + unlockForm.addEventListener('submit', async function (event) { + event.preventDefault(); + var input = $('#mmPassword'); + 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 = $('#mmLockBtn'); + 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; + } + }); + } + + /* ---------- 面板开关 ---------- */ + function togglePanel(panel) { + if (!panel) return; + Array.prototype.forEach.call(document.querySelectorAll('.mm-panel'), function (item) { + if (item !== panel) item.hidden = true; + }); + panel.hidden = !panel.hidden; + if (!panel.hidden && panel.scrollIntoView) { + panel.scrollIntoView({ behavior: 'smooth', block: 'center' }); + } + } + + [ + ['#mmNewFolderBtn', '#mmNewFolderForm'], + ['#mmUploadBtn', '#mmUploadForm'], + ['#mmFolderEditBtn', '#mmFolderEditForm'], + ['#mmMapEditBtn', '#mmMapEditForm'] + ].forEach(function (pair) { + var button = $(pair[0]); + var panel = $(pair[1]); + if (button && panel) { + button.addEventListener('click', function () { + togglePanel(panel); + }); + } + }); + + Array.prototype.forEach.call(document.querySelectorAll('[data-close-panel]'), function (button) { + button.addEventListener('click', function () { + var panel = document.getElementById(button.getAttribute('data-close-panel')); + if (panel) panel.hidden = true; + }); + }); + + /* ---------- 删除确认 ---------- */ + 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 canvas = $('#mmCanvas'); + var dataScript = $('#mindmap-data'); + if (!canvas) return; + + var raw = null; + try { + raw = dataScript ? JSON.parse(dataScript.textContent) : null; + } catch (error) { + raw = null; + } + + var outline = $('#mmOutline'); + if (outline && raw && raw.data) { + buildOutline(raw, outline); + } else if (outline) { + outline.innerHTML = '
没有可显示的大纲。
'; + } + + var MindMapLib = window.simpleMindMap + && (window.simpleMindMap.default || window.simpleMindMap); + + var fallback = $('#mmFallback'); + var loading = canvas.querySelector('.mm-loading'); + + if (!MindMapLib || !raw || !raw.data) { + showFallback(); + return; + } + + var mindMap = null; + + try { + mindMap = new MindMapLib({ + el: canvas, + data: raw, + readonly: true, + layout: 'logicalStructure', + theme: 'default', + fit: false, + center: true, + scale: 1, + maxScale: 3, + minScale: 0.2 + }); + } catch (error) { + showFallback(); + return; + } + + if (loading && loading.parentNode) loading.parentNode.removeChild(loading); + + var currentLayout = 'logicalStructure'; + + requestAnimationFrame(function () { + callMind('fit'); + }); + + bindToolbar(); + + function callMind(name, argument) { + if (!mindMap) return false; + if (typeof mindMap[name] === 'function') { + mindMap[name](argument); + return true; + } + if (mindMap.view && typeof mindMap.view[name] === 'function') { + mindMap.view[name](argument); + return true; + } + return false; + } + + function bindToolbar() { + Array.prototype.forEach.call(document.querySelectorAll('[data-mm]'), function (button) { + button.addEventListener('click', function () { + var action = button.getAttribute('data-mm'); + + if (action === 'zoom-in') { + callMind('scaleUp'); + } else if (action === 'zoom-out') { + callMind('scaleDown'); + } else if (action === 'fit') { + callMind('fit'); + } else if (action === 'expand') { + callMind('expandAll'); + } else if (action === 'collapse') { + callMind('unexpandAll'); + } else if (action === 'layout') { + if (callMind('setLayout', currentLayout === 'logicalStructure' ? 'mindMap' : 'logicalStructure')) { + currentLayout = currentLayout === 'logicalStructure' ? 'mindMap' : 'logicalStructure'; + } + } else if (action === 'full') { + toggleFullscreen(); + } + }); + }); + } + + function toggleFullscreen() { + if (!canvas.requestFullscreen) { + toast('当前浏览器不支持全屏'); + return; + } + if (document.fullscreenElement) { + document.exitFullscreen(); + return; + } + canvas.requestFullscreen().then(function () { + setTimeout(function () { callMind('fit'); }, 200); + }).catch(function () { + toast('全屏失败'); + }); + } + + function showFallback() { + if (loading && loading.parentNode) loading.parentNode.removeChild(loading); + if (fallback) fallback.hidden = false; + var actions = document.querySelector('.mm-view-actions'); + if (actions) actions.style.display = 'none'; + } + + function buildOutline(node, container) { + var root = document.createElement('ul'); + + function walk(current, parent) { + if (!current) return; + var item = document.createElement('li'); + var label = document.createElement('span'); + label.textContent = (current.data && current.data.text) || ''; + item.appendChild(label); + + var children = current.children || []; + if (children.length) { + var list = document.createElement('ul'); + children.forEach(function (child) { + walk(child, list); + }); + item.appendChild(list); + } + parent.appendChild(item); + } + + walk(node, root); + container.replaceChildren(root); + } +})(); diff --git a/mindmaps/templates/mindmaps/_lock.html b/mindmaps/templates/mindmaps/_lock.html new file mode 100644 index 0000000..ffc37c9 --- /dev/null +++ b/mindmaps/templates/mindmaps/_lock.html @@ -0,0 +1,17 @@ +{% comment %}拾脉:写操作解锁条,与拾匣共用密码{% endcomment %} +MINDMAP
+{% if mindmap.description %}{{ mindmap.description }}{% else %}一张可以拖动、缩放的学习脑图。{% endif %}
+正在加载预览…
++ 预览库没有加载成功。可以看右侧文字大纲,或下载 .xmind 文件。 +
+预览只读;拖动、缩放、全屏都在画布工具栏里。上传的 .xmind 文件保留在媒体目录,可随时下载。
+MINDMAP FOLDER
+{% if folder.description %}{{ folder.description }}{% else %}这个目录下的章节脑图。{% endif %}
+这个目录下还没有脑图。{% if unlocked %}点“上传 XMind”放一份。{% endif %}
+ {% endif %} +上传后自动解析 XMind 并生成预览;原文件下载链接在每张脑图的详情页里。
+拾脉 · MINDMAPS
+目录收着章节,XMind 收着思路。上传 .xmind,直接在页面里展开。
+还没有目录。{% if unlocked %}点“新建目录”,比如 C++、Python。{% endif %}
+ {% endif %} +脑图预览公开;新建目录、上传、编辑和删除需要密码,与拾匣共用。上传的 .xmind 原文件也可以直接下载。
+