Merge pull request 'feat: 完善主题导入、手账工作区与笔记元数据管理' (#27) from feat/theme-import-and-paper-workspace into main
Reviewed-on: #27
This commit was merged in pull request #27.
This commit is contained in:
@@ -134,3 +134,42 @@ pnpm build
|
||||
- 前端不直接访问 SQLite 或厂商模型协议;持久数据通过 FastAPI 服务读写。
|
||||
- 接口或数据结构变化时,同一提交同步更新前后端类型、契约和开发说明。
|
||||
- 当前行为以代码、测试和运行中的 `/openapi.json` 为准;规划能力必须在文档中明确标注。
|
||||
|
||||
## 主题包与仓库发布(临时规范)
|
||||
|
||||
主题页支持本地文件及 HTTP(S) 文件直链导入。两种入口均先解析、校验并展示清单和 CSS,用户点击安装后才写入本地存储。安装不会自动启用主题。
|
||||
|
||||
### 单文件
|
||||
|
||||
使用 UTF-8 编码,扩展名 `.theme`、`.yaml` 或 `.yml`。内容为 YAML 清单、一行 `---`、完整 CSS。可参考 `frontend/src/assets/themes/paper-moments.theme`。
|
||||
|
||||
### ZIP
|
||||
|
||||
一个 ZIP 只包含一个主题。清单命名为 `theme.yaml`、`theme.yml`、`manifest.yaml` 或 `manifest.yml`,可以放在顶层,也可以放在仓库压缩包的子目录中。
|
||||
|
||||
```text
|
||||
my-theme/
|
||||
theme.yaml
|
||||
styles/
|
||||
theme.css
|
||||
```
|
||||
|
||||
```yaml
|
||||
theme_id: my-theme
|
||||
name: My Theme
|
||||
version: 1.0.0
|
||||
author: your-name
|
||||
min_app_version: 0.2.0
|
||||
is_dark: false
|
||||
css_entry: styles/theme.css
|
||||
```
|
||||
|
||||
`css_entry` 相对于清单目录解析,不允许绝对路径、反斜杠及 `..`。CSS 应以 `[data-theme="my-theme"]` 限定主题样式。也支持仅包含一个 `.theme` 文件的 ZIP。
|
||||
|
||||
目前安装持久化的是清单和 CSS,不会托管 ZIP 内的图片、字体等资源;需要这些资源时请将它们内嵌为 CSS data URL。禁止 `@import` 和脚本表达式。
|
||||
|
||||
### URL 与社区仓库
|
||||
|
||||
发布主题仓库时可提供原始 `.theme` 文件链接或 ZIP 发布附件直链,不要使用仓库 HTML 浏览页面地址。下载请求不携带 Cookie 或 HTTP 登录信息,服务器需允许应用来源的 CORS 请求;暂不支持私有仓库认证。
|
||||
|
||||
下载和本地文件限制为 5 MB;ZIP 解压总大小限制为 10 MB,最多 100 个条目。URL 下载超时为 30 秒。取消导入会取消下载,过期请求不会替换当前待安装主题。更新时递增清单版本号,并保持 `theme_id` 稳定。
|
||||
|
||||
@@ -20,7 +20,6 @@ from app.errors import ApiError
|
||||
from app.textutils import count_tokens
|
||||
|
||||
_HEADING_RE = re.compile(r"^(#{1,6})[ \t]+(.*?)\s*$")
|
||||
_FRONTMATTER_KEY_RE = re.compile(r"^([A-Za-z0-9_-]+)\s*:\s*(.*)$")
|
||||
_FENCE_RE = re.compile(r"^[ \t]{0,3}(`{3,}|~{3,})(?:[^`]*)$")
|
||||
|
||||
|
||||
@@ -261,16 +260,29 @@ def _embedding_policy(markdown: str) -> bool:
|
||||
return value.value.lower() in {"true", "yes", "on"}
|
||||
|
||||
|
||||
def _extract_frontmatter(markdown: str) -> dict[str, str]:
|
||||
"""极简 frontmatter 解析,只提取 key: value 行。"""
|
||||
def _extract_frontmatter(markdown: str) -> dict[str, str | list[str]]:
|
||||
"""Read YAML scalars and tag sequences without constructing arbitrary objects."""
|
||||
header = _frontmatter(markdown)
|
||||
if header is None:
|
||||
return {}
|
||||
meta: dict[str, str] = {}
|
||||
for line in header[0].splitlines():
|
||||
m = _FRONTMATTER_KEY_RE.match(line)
|
||||
if m:
|
||||
meta[m.group(1).lower()] = m.group(2).strip()
|
||||
try:
|
||||
node = yaml.compose(header[0], Loader=yaml.SafeLoader)
|
||||
except yaml.YAMLError as exc:
|
||||
raise ApiError(422, "INVALID_EMBEDDING_POLICY", "Frontmatter YAML 无效,无法确认本地索引策略。") from exc
|
||||
meta: dict[str, str | list[str]] = {}
|
||||
if not isinstance(node, yaml.MappingNode):
|
||||
return meta # The policy validation below handles unsupported documents.
|
||||
for key, value in node.value:
|
||||
if not isinstance(key, yaml.ScalarNode):
|
||||
continue
|
||||
name = key.value.lower()
|
||||
if name not in {"title", "tags"}:
|
||||
continue
|
||||
if isinstance(value, yaml.ScalarNode):
|
||||
# Keep lexical values: YAML 1.1 would otherwise turn tags like on/yes into booleans.
|
||||
meta[name] = "" if value.tag == "tag:yaml.org,2002:null" else value.value
|
||||
elif name == "tags" and isinstance(value, yaml.SequenceNode):
|
||||
meta[name] = [item.value for item in value.value if isinstance(item, yaml.ScalarNode)]
|
||||
return meta
|
||||
|
||||
|
||||
@@ -282,10 +294,10 @@ def _first_heading(markdown: str) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def _parse_tags(raw: str | None) -> list[str]:
|
||||
def _parse_tags(raw: str | list[str] | None) -> list[str]:
|
||||
if isinstance(raw, list):
|
||||
return raw
|
||||
if not raw:
|
||||
return []
|
||||
raw = raw.strip()
|
||||
if raw.startswith("[") and raw.endswith("]"):
|
||||
raw = raw[1:-1]
|
||||
return [t.strip().strip("'\"") for t in raw.split(",") if t.strip()]
|
||||
return [t.strip() for t in raw.split(",") if t.strip()]
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import asyncio
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import pytest
|
||||
|
||||
from app.contracts import IndexRebuildRequest
|
||||
from app.knowledge.parser import parse_note
|
||||
from app.services import index_service, note_service
|
||||
|
||||
|
||||
@pytest.mark.parametrize(('header', 'expected'), [
|
||||
('tags:\n- python\n- rust', ['python', 'rust']),
|
||||
('tags:\n - python\n - rust', ['python', 'rust']),
|
||||
('"tags": ["a,b", "quote\\\"tag", "path\\\\tag"] # comment', ['a,b', 'quote"tag', 'path\\tag']),
|
||||
('tags: [on, yes, "true", "001"]', ['on', 'yes', 'true', '001']),
|
||||
('tags: python, rust', ['python', 'rust']),
|
||||
('tags: []', []),
|
||||
('tags: null', []),
|
||||
])
|
||||
def test_yaml_tags_are_parsed_as_complete_values(header, expected):
|
||||
now = datetime.now(timezone.utc)
|
||||
note = parse_note(
|
||||
markdown=f'---\ntitle: "Demo: YAML"\n{header}\n---\n# Body',
|
||||
file_path='demo.md', folder='', created_at=now, updated_at=now,
|
||||
)
|
||||
assert note.tags == expected
|
||||
assert note.title == 'Demo: YAML'
|
||||
|
||||
|
||||
def test_saved_metadata_survives_full_index_rebuild():
|
||||
async def scenario():
|
||||
note = await note_service.create_note(title='Demo', markdown='# Body', folder=None, tags=['old'])
|
||||
for tags, yaml_tags in [
|
||||
(['python', 'a,b', 'on'], '\n - python\n - a,b\n - on'),
|
||||
([], ' []'),
|
||||
]:
|
||||
markdown = f'---\ntitle: "Demo: updated"\ntags:{yaml_tags}\n---\n# Body\n'
|
||||
saved = await note_service.update_note(note.note_id, markdown=markdown, tags=tags)
|
||||
assert saved.tags == tags
|
||||
job = await index_service.rebuild(IndexRebuildRequest())
|
||||
assert job.status == 'completed'
|
||||
restored = await note_service.get_note(note.note_id)
|
||||
assert restored.tags == tags
|
||||
assert restored.title == 'Demo: updated'
|
||||
assert restored.markdown == markdown
|
||||
asyncio.run(scenario())
|
||||
@@ -27,6 +27,7 @@
|
||||
- [后端接口契约](contracts/后端接口契约-开发版.md)
|
||||
- [第二阶段接口契约](contracts/第二阶段接口契约-开发版.md)
|
||||
- [前端页面需求说明](contracts/前端页面需求说明-开发版.md)
|
||||
- [Tauri / Rust 桌面客户端需求说明(第三阶段,计划)](contracts/Tauri-Rust桌面客户端需求说明-第三阶段.md)
|
||||
|
||||
运行中的后端以 `/openapi.json` 为机器可读事实来源。接口契约用于描述设计意图、联调约束和实现状态;两者不一致时,应先确认代码行为,再在同一个 PR 中同步修正文档或实现。
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# Tauri / Rust 桌面客户端需求说明(第三阶段)
|
||||
|
||||
状态:需求预留,尚未实现桌面客户端。本文不表示已有可调用的 Tauri Command 或可发布安装包。
|
||||
|
||||
基线日期:2026-09-05。
|
||||
|
||||
## 1. 目标与边界
|
||||
|
||||
第三阶段在现有 Vue 编辑器和 FastAPI AI Core 上接入 Tauri 2 / Rust Host,提供原生窗口、菜单、多 Vault 文件管理、安全凭据存储和 Sidecar 生命周期管理。
|
||||
|
||||
- Vue 负责页面、编辑事务、主题和交互状态;通过既有 Service 边界调用能力,不在组件中散布平台判断。
|
||||
- Rust Host 负责系统能力、路径权限、原生菜单事件及受控进程生命周期。
|
||||
- FastAPI AI Core 保留笔记解析、索引、检索、模型和 Agent 业务职责;同一文件不得同时由 Host 和 AI Core 无协调地写入。
|
||||
- Web 模式保留可运行能力;桌面专有功能通过能力检测显隐,不用无响应按钮假装已实现。
|
||||
|
||||
架构依据:[技术栈说明](../architecture/AI笔记软件技术栈说明-团队版-v2.3.md)、[前端页面需求](前端页面需求说明-开发版.md)、[第二阶段接口契约](第二阶段接口契约-开发版.md)。
|
||||
|
||||
## 2. 顶部菜单与元数据格式一键导入
|
||||
|
||||
### 2.1 入口预留
|
||||
|
||||
桌面客户端顶部菜单栏的 **段落 → 导入为笔记属性…** 预留元数据格式导入功能,与标题、正文、列表等段落操作归组。它处理笔记内容中的元数据,不是主题包安装入口。
|
||||
|
||||
建议稳定的前端命令标识为 `editor.import-note-properties`,仅为设计标识,尚未注册为 Tauri IPC。原生菜单和编辑器命令面板应分发同一命令,避免两套转换逻辑。快捷键待第三阶段统一分配,不抢占现有编辑快捷键。
|
||||
|
||||
### 2.2 输入与转换规则
|
||||
|
||||
1. 无选区时识别当前笔记开头的属性块;有选区时只处理完整的属性块。无活动笔记、加载中、只读或冲突状态下禁用操作,并提供原因。
|
||||
2. 支持标准 YAML frontmatter,以及历史编辑器产生的 `***` 开头、`title:` / `tags:` 字段、横线结尾的兼容形式。普通分隔线、代码块和包含冒号的正文不得被误判。
|
||||
3. 将识别成功的内容规范化到文件头唯一的 `---` frontmatter 中,正文中的旧属性块仅在转换成功后移除。
|
||||
4. 写作模式显示独立标题和可编辑标签;源码模式显示真实 `title` / `tags` 字段。标签必须进入现有保存和索引链路,能被标签筛选使用,不能只创建装饰性标签元素。
|
||||
5. 保留未知属性及其类型,特别是 `embedding_local_only` 等行为配置。复杂 YAML 不得用正则拆分后静默丢弃;无法无损处理时说明原因,并保留原文供源码编辑。
|
||||
6. 标签支持字符串、逗号分隔值和 YAML 列表,去重并保留顺序;中文、空格、转义字符须正确往返。空标签与删除标签有明确语义。
|
||||
7. 已存在 frontmatter 时合并到同一个属性块;字段值冲突时展示差异供用户选择,禁止静默覆盖。重复执行不重复添加标签或属性块。
|
||||
|
||||
### 2.3 编辑与保存行为
|
||||
|
||||
- 无歧义转换一次菜单操作完成,并构成一个可撤销的编辑事务;转换失败不得改变文档或保存状态。
|
||||
- 转换作用于当前内存文档,不先从磁盘读取旧内容覆盖未保存编辑。操作绑定文件标识和文档版本,异步处理期间切换文件或继续编辑时,应取消或重新校验。
|
||||
- 成功后进入现有脏状态和自动保存流程。磁盘保存失败显示可重试状态,撤销/重做同时恢复正文、属性及标签。
|
||||
- 属性块不进入正文大纲;标题跳转、引用定位仍使用完整原文件的正确偏移。写作/源码切换、保存后重开不得改变属性语义。
|
||||
- 当前分支的 `frontend/src/features/editor/noteMetadata.ts` 仅是简单属性块展示与标签编辑基础;桌面阶段需补齐完整解析、合并冲突、单事务撤销和原生菜单分发,不能直接视为本节已经验收。
|
||||
|
||||
## 3. 桌面基础需求
|
||||
|
||||
| 模块 | 第三阶段要求 | 验收要点 |
|
||||
| --- | --- | --- |
|
||||
| 窗口与菜单 | 原生窗口控制、顶部菜单、焦点分发、关闭前未保存处理 | 菜单操作针对活动编辑器;多窗口不串文档;取消关闭保留编辑 |
|
||||
| Vault 与文件系统 | 原生目录选择、多 Vault、最近打开、文件监听、路径规范化 | 未授权目录不可访问;重命名同步树和打开文件;外部修改不静默覆盖 |
|
||||
| 写入与恢复 | 原子写入、版本/内容摘要校验、失败重试和异常退出恢复 | 不产生半写文件;并发保存不覆盖新版本;恢复流程可验证 |
|
||||
| AI Core Sidecar | 启停、健康检查、日志、崩溃恢复、退出清理 | 不残留进程;不可用时显示原因;本地通信有访问控制 |
|
||||
| 凭据 | 按既有架构接入 Stronghold/平台安全存储,制定开发凭据迁移方案 | 前端只持有凭据引用;不回显密钥;失败可恢复且不丢凭据 |
|
||||
| MCP 与插件 | 按已冻结的 Host 沙箱契约落实文件、网络和子进程授权 | 沿用审批边界,不因桌面集成默认放开权限 |
|
||||
| 主题 | 复用主题包校验;原生文件选择和下载适配共用检查流程 | 导入不自动启用;安装失败可恢复;ZIP 路径和资源限制继续有效 |
|
||||
| 外观与导航 | 继承主题、代码配色、相对纸页宽度、文件/大纲切换 | 窗口缩放、高 DPI、深浅主题下无截断;键盘导航完整 |
|
||||
| 发布 | Windows、macOS、Linux 构建与安装验证;签名、升级及回滚方案 | 未准备好签名和回滚前不启用自动更新;平台差异有说明 |
|
||||
|
||||
云同步服务、移动端和主题社区服务端不因本文自动纳入第三阶段必交范围;需要单独确认范围与接口。
|
||||
|
||||
## 4. 开发顺序与验收
|
||||
|
||||
1. 冻结 Host 能力与 Service 适配接口,明确每类数据的写入责任方及权限模型。
|
||||
2. 接入窗口、菜单与编辑命令路由,完成“段落 → 导入为笔记属性…”的编辑器事务。
|
||||
3. 接入 Vault、文件监听、冲突处理、Sidecar 和凭据迁移。
|
||||
4. 完成平台测试、安装包和升级恢复验收。
|
||||
|
||||
元数据导入专项测试至少覆盖:标准/历史格式、普通正文误判、代码围栏、未知字段、复杂 YAML、同名字段冲突、重复导入、中文标签、撤销重做、未保存文档、处理中切换文件、保存失败、重开后标签检索,以及写作/源码模式的大纲与引用偏移。
|
||||
|
||||
第三阶段实现 PR 必须补充实际 Command 名称、输入输出类型、错误码、平台差异和测试证据;在此之前本文所有 Host 能力均标为计划实现。
|
||||
@@ -35,12 +35,14 @@
|
||||
"@vueuse/core": "^14.0.0",
|
||||
"codemirror": "^6.0.0",
|
||||
"dompurify": "^3.4.14",
|
||||
"fflate": "^0.8.3",
|
||||
"marked": "^15.0.0",
|
||||
"mermaid": "^11.17.2",
|
||||
"pinia": "^4.0.0",
|
||||
"shiki": "^4.4.3",
|
||||
"vue": "^3.5.0",
|
||||
"vue-router": "^5.0.0"
|
||||
"vue-router": "^5.0.0",
|
||||
"yaml": "^2.9.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
|
||||
Generated
+38
-26
@@ -80,6 +80,9 @@ importers:
|
||||
dompurify:
|
||||
specifier: ^3.4.14
|
||||
version: 3.4.14
|
||||
fflate:
|
||||
specifier: ^0.8.3
|
||||
version: 0.8.3
|
||||
marked:
|
||||
specifier: ^15.0.0
|
||||
version: 15.0.12
|
||||
@@ -97,14 +100,17 @@ importers:
|
||||
version: 3.5.42(typescript@5.9.3)
|
||||
vue-router:
|
||||
specifier: ^5.0.0
|
||||
version: 5.3.0(@vue/compiler-sfc@3.5.42)(esbuild@0.25.12)(pinia@4.0.3(@vue/devtools-api@8.2.1)(typescript@5.9.3)(vue@3.5.42(typescript@5.9.3)))(rollup@4.63.1)(vite@6.4.3(@types/node@22.20.1))(vue@3.5.42(typescript@5.9.3))
|
||||
version: 5.3.0(@vue/compiler-sfc@3.5.42)(esbuild@0.25.12)(pinia@4.0.3(@vue/devtools-api@8.2.1)(typescript@5.9.3)(vue@3.5.42(typescript@5.9.3)))(rollup@4.63.1)(vite@6.4.3(@types/node@22.20.1)(yaml@2.9.0))(vue@3.5.42(typescript@5.9.3))
|
||||
yaml:
|
||||
specifier: ^2.9.0
|
||||
version: 2.9.0
|
||||
devDependencies:
|
||||
'@types/node':
|
||||
specifier: ^22.0.0
|
||||
version: 22.20.1
|
||||
'@vitejs/plugin-vue':
|
||||
specifier: ^5.0.0
|
||||
version: 5.2.4(vite@6.4.3(@types/node@22.20.1))(vue@3.5.42(typescript@5.9.3))
|
||||
version: 5.2.4(vite@6.4.3(@types/node@22.20.1)(yaml@2.9.0))(vue@3.5.42(typescript@5.9.3))
|
||||
'@vue/test-utils':
|
||||
specifier: ^2.5.0
|
||||
version: 2.5.0(@vue/compiler-dom@3.5.42)(@vue/server-renderer@3.5.42)(vue@3.5.42(typescript@5.9.3))
|
||||
@@ -116,10 +122,10 @@ importers:
|
||||
version: 5.9.3
|
||||
vite:
|
||||
specifier: ^6.0.0
|
||||
version: 6.4.3(@types/node@22.20.1)
|
||||
version: 6.4.3(@types/node@22.20.1)(yaml@2.9.0)
|
||||
vitest:
|
||||
specifier: ^4.1.11
|
||||
version: 4.1.11(@types/node@22.20.1)(happy-dom@20.11.15)(vite@6.4.3(@types/node@22.20.1))
|
||||
version: 4.1.11(@types/node@22.20.1)(happy-dom@20.11.15)(vite@6.4.3(@types/node@22.20.1)(yaml@2.9.0))
|
||||
vue-tsc:
|
||||
specifier: ^2.0.0
|
||||
version: 2.2.12(typescript@5.9.3)
|
||||
@@ -954,11 +960,6 @@ packages:
|
||||
|
||||
'@volar/typescript@2.4.15':
|
||||
resolution: {integrity: sha512-2aZ8i0cqPGjXb4BhkMsPYDkkuc2ZQ6yOpqwAuNwUoncELqoy5fRgOQtLR9gB0g902iS0NAkvpIzs27geVyVdPg==}
|
||||
peerDependencies:
|
||||
typescript: '*'
|
||||
peerDependenciesMeta:
|
||||
typescript:
|
||||
optional: true
|
||||
|
||||
'@vue-macros/common@3.1.4':
|
||||
resolution: {integrity: sha512-/5Fv+6DgIcM9ajY05ZmKBv+LMX1M9A0X+IUwDRVdt67ciw8OV9bvG2r34p3RiEadlsQybjhKPRKNXDC8Bp23cw==}
|
||||
@@ -1392,6 +1393,9 @@ packages:
|
||||
picomatch:
|
||||
optional: true
|
||||
|
||||
fflate@0.8.3:
|
||||
resolution: {integrity: sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==}
|
||||
|
||||
fsevents@2.3.3:
|
||||
resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
|
||||
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
|
||||
@@ -2149,6 +2153,11 @@ packages:
|
||||
utf-8-validate:
|
||||
optional: true
|
||||
|
||||
yaml@2.9.0:
|
||||
resolution: {integrity: sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==}
|
||||
engines: {node: '>= 14.6'}
|
||||
hasBin: true
|
||||
|
||||
zwitch@2.0.4:
|
||||
resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}
|
||||
|
||||
@@ -3258,9 +3267,9 @@ snapshots:
|
||||
d3-selection: 3.0.0
|
||||
d3-transition: 3.0.1(d3-selection@3.0.0)
|
||||
|
||||
'@vitejs/plugin-vue@5.2.4(vite@6.4.3(@types/node@22.20.1))(vue@3.5.42(typescript@5.9.3))':
|
||||
'@vitejs/plugin-vue@5.2.4(vite@6.4.3(@types/node@22.20.1)(yaml@2.9.0))(vue@3.5.42(typescript@5.9.3))':
|
||||
dependencies:
|
||||
vite: 6.4.3(@types/node@22.20.1)
|
||||
vite: 6.4.3(@types/node@22.20.1)(yaml@2.9.0)
|
||||
vue: 3.5.42(typescript@5.9.3)
|
||||
|
||||
'@vitest/expect@4.1.11':
|
||||
@@ -3272,13 +3281,13 @@ snapshots:
|
||||
chai: 6.2.2
|
||||
tinyrainbow: 3.1.1
|
||||
|
||||
'@vitest/mocker@4.1.11(vite@6.4.3(@types/node@22.20.1))':
|
||||
'@vitest/mocker@4.1.11(vite@6.4.3(@types/node@22.20.1)(yaml@2.9.0))':
|
||||
dependencies:
|
||||
'@vitest/spy': 4.1.11
|
||||
estree-walker: 3.0.3
|
||||
magic-string: 0.30.21
|
||||
optionalDependencies:
|
||||
vite: 6.4.3(@types/node@22.20.1)
|
||||
vite: 6.4.3(@types/node@22.20.1)(yaml@2.9.0)
|
||||
|
||||
'@vitest/pretty-format@4.1.11':
|
||||
dependencies:
|
||||
@@ -3310,13 +3319,11 @@ snapshots:
|
||||
|
||||
'@volar/source-map@2.4.15': {}
|
||||
|
||||
'@volar/typescript@2.4.15(typescript@5.9.3)':
|
||||
'@volar/typescript@2.4.15':
|
||||
dependencies:
|
||||
'@volar/language-core': 2.4.15
|
||||
path-browserify: 1.0.1
|
||||
vscode-uri: 3.2.0
|
||||
optionalDependencies:
|
||||
typescript: 5.9.3
|
||||
|
||||
'@vue-macros/common@3.1.4(vue@3.5.42(typescript@5.9.3))':
|
||||
dependencies:
|
||||
@@ -3805,6 +3812,8 @@ snapshots:
|
||||
optionalDependencies:
|
||||
picomatch: 4.0.7
|
||||
|
||||
fflate@0.8.3: {}
|
||||
|
||||
fsevents@2.3.3:
|
||||
optional: true
|
||||
|
||||
@@ -4679,7 +4688,7 @@ snapshots:
|
||||
pathe: 2.0.3
|
||||
picomatch: 4.0.7
|
||||
|
||||
unplugin@3.3.0(esbuild@0.25.12)(rollup@4.63.1)(vite@6.4.3(@types/node@22.20.1)):
|
||||
unplugin@3.3.0(esbuild@0.25.12)(rollup@4.63.1)(vite@6.4.3(@types/node@22.20.1)(yaml@2.9.0)):
|
||||
dependencies:
|
||||
'@jridgewell/remapping': 2.3.5
|
||||
picomatch: 4.0.7
|
||||
@@ -4687,7 +4696,7 @@ snapshots:
|
||||
optionalDependencies:
|
||||
esbuild: 0.25.12
|
||||
rollup: 4.63.1
|
||||
vite: 6.4.3(@types/node@22.20.1)
|
||||
vite: 6.4.3(@types/node@22.20.1)(yaml@2.9.0)
|
||||
|
||||
uuid@14.0.2: {}
|
||||
|
||||
@@ -4701,7 +4710,7 @@ snapshots:
|
||||
'@types/unist': 3.0.3
|
||||
vfile-message: 4.0.3
|
||||
|
||||
vite@6.4.3(@types/node@22.20.1):
|
||||
vite@6.4.3(@types/node@22.20.1)(yaml@2.9.0):
|
||||
dependencies:
|
||||
esbuild: 0.25.12
|
||||
fdir: 6.5.0(picomatch@4.0.7)
|
||||
@@ -4712,11 +4721,12 @@ snapshots:
|
||||
optionalDependencies:
|
||||
'@types/node': 22.20.1
|
||||
fsevents: 2.3.3
|
||||
yaml: 2.9.0
|
||||
|
||||
vitest@4.1.11(@types/node@22.20.1)(happy-dom@20.11.15)(vite@6.4.3(@types/node@22.20.1)):
|
||||
vitest@4.1.11(@types/node@22.20.1)(happy-dom@20.11.15)(vite@6.4.3(@types/node@22.20.1)(yaml@2.9.0)):
|
||||
dependencies:
|
||||
'@vitest/expect': 4.1.11
|
||||
'@vitest/mocker': 4.1.11(vite@6.4.3(@types/node@22.20.1))
|
||||
'@vitest/mocker': 4.1.11(vite@6.4.3(@types/node@22.20.1)(yaml@2.9.0))
|
||||
'@vitest/pretty-format': 4.1.11
|
||||
'@vitest/runner': 4.1.11
|
||||
'@vitest/snapshot': 4.1.11
|
||||
@@ -4733,7 +4743,7 @@ snapshots:
|
||||
tinyexec: 1.3.0
|
||||
tinyglobby: 0.2.17
|
||||
tinyrainbow: 3.1.1
|
||||
vite: 6.4.3(@types/node@22.20.1)
|
||||
vite: 6.4.3(@types/node@22.20.1)(yaml@2.9.0)
|
||||
why-is-node-running: 2.3.0
|
||||
optionalDependencies:
|
||||
'@types/node': 22.20.1
|
||||
@@ -4745,7 +4755,7 @@ snapshots:
|
||||
|
||||
vue-component-type-helpers@3.3.11: {}
|
||||
|
||||
vue-router@5.3.0(@vue/compiler-sfc@3.5.42)(esbuild@0.25.12)(pinia@4.0.3(@vue/devtools-api@8.2.1)(typescript@5.9.3)(vue@3.5.42(typescript@5.9.3)))(rollup@4.63.1)(vite@6.4.3(@types/node@22.20.1))(vue@3.5.42(typescript@5.9.3)):
|
||||
vue-router@5.3.0(@vue/compiler-sfc@3.5.42)(esbuild@0.25.12)(pinia@4.0.3(@vue/devtools-api@8.2.1)(typescript@5.9.3)(vue@3.5.42(typescript@5.9.3)))(rollup@4.63.1)(vite@6.4.3(@types/node@22.20.1)(yaml@2.9.0))(vue@3.5.42(typescript@5.9.3)):
|
||||
dependencies:
|
||||
'@vue-macros/common': 3.1.4(vue@3.5.42(typescript@5.9.3))
|
||||
'@vue/devtools-api': 8.2.1
|
||||
@@ -4761,13 +4771,13 @@ snapshots:
|
||||
picomatch: 4.0.7
|
||||
scule: 1.3.0
|
||||
tinyglobby: 0.2.17
|
||||
unplugin: 3.3.0(esbuild@0.25.12)(rollup@4.63.1)(vite@6.4.3(@types/node@22.20.1))
|
||||
unplugin: 3.3.0(esbuild@0.25.12)(rollup@4.63.1)(vite@6.4.3(@types/node@22.20.1)(yaml@2.9.0))
|
||||
unplugin-utils: 0.3.2
|
||||
vue: 3.5.42(typescript@5.9.3)
|
||||
optionalDependencies:
|
||||
'@vue/compiler-sfc': 3.5.42
|
||||
pinia: 4.0.3(@vue/devtools-api@8.2.1)(typescript@5.9.3)(vue@3.5.42(typescript@5.9.3))
|
||||
vite: 6.4.3(@types/node@22.20.1)
|
||||
vite: 6.4.3(@types/node@22.20.1)(yaml@2.9.0)
|
||||
transitivePeerDependencies:
|
||||
- '@farmfe/core'
|
||||
- '@rspack/core'
|
||||
@@ -4780,7 +4790,7 @@ snapshots:
|
||||
|
||||
vue-tsc@2.2.12(typescript@5.9.3):
|
||||
dependencies:
|
||||
'@volar/typescript': 2.4.15(typescript@5.9.3)
|
||||
'@volar/typescript': 2.4.15
|
||||
'@vue/language-core': 2.2.12(typescript@5.9.3)
|
||||
typescript: 5.9.3
|
||||
|
||||
@@ -4807,4 +4817,6 @@ snapshots:
|
||||
|
||||
ws@8.21.3: {}
|
||||
|
||||
yaml@2.9.0: {}
|
||||
|
||||
zwitch@2.0.4: {}
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
theme_id: paper-moments
|
||||
name: 纸间时光 · Paper Moments
|
||||
version: 1.4.1
|
||||
author: NotesAgent
|
||||
description: 奶油纸张、手帐虚线与粉蓝胶带,把每天的灵感好好收藏。
|
||||
min_app_version: 0.2.0
|
||||
is_dark: false
|
||||
css_entry: theme.css
|
||||
license: MIT
|
||||
---
|
||||
[data-theme="paper-moments"] {
|
||||
color-scheme: light;
|
||||
--color-background-primary: #faf7ee;
|
||||
--color-background-secondary: #f3eee3;
|
||||
--color-background-tertiary: #ece5d7;
|
||||
--color-background-hover: #f1e5da;
|
||||
--color-background-active: #ecdbd2;
|
||||
--color-background-overlay: rgba(65, 55, 45, .35);
|
||||
--color-surface-primary: #fffdf5;
|
||||
--color-surface-secondary: #f7f1e5;
|
||||
--color-surface-elevated: #fffdf7;
|
||||
--color-text-primary: #493f35;
|
||||
--color-text-secondary: #6e6053;
|
||||
--color-text-tertiary: #7d6b5e;
|
||||
--color-text-inverse: #fffdf5;
|
||||
--color-text-link: #875343;
|
||||
--color-text-disabled: #9c9081;
|
||||
--color-accent-primary: #875343;
|
||||
--color-accent-primary-hover: #704334;
|
||||
--color-accent-primary-active: #5e382b;
|
||||
--color-accent-secondary: #a77a67;
|
||||
--color-accent-soft: #f3e1d8;
|
||||
--color-accent-soft-hover: #ecd3c7;
|
||||
--color-border-default: #b5a693;
|
||||
--color-border-subtle: #ded5c5;
|
||||
--color-border-focus: #875343;
|
||||
--color-border-disabled: #e2dacc;
|
||||
--color-success: #526849;
|
||||
--color-success-soft: #e5ecd9;
|
||||
--color-warning: #806323;
|
||||
--color-warning-soft: #faf0cb;
|
||||
--color-error: #a0423c;
|
||||
--color-error-soft: #f8e2dc;
|
||||
--color-info: #456671;
|
||||
--color-info-soft: #e1eef0;
|
||||
--color-markdown-grid: #ded5c5;
|
||||
--color-markdown-marker: #a77a67;
|
||||
--color-markdown-table-header: #eee7d7;
|
||||
--shadow-sm: 2px 3px 0 #e5ded0;
|
||||
--shadow-md: 3px 4px 0 #dae5df, 6px 7px 0 #f0d8cf;
|
||||
--shadow-lg: 4px 5px 0 #dae5df, 8px 9px 0 #f0d8cf;
|
||||
--shadow-xl: 5px 6px 0 #dae5df, 10px 11px 0 #f0d8cf, 0 18px 42px #493f3520;
|
||||
}
|
||||
|
||||
[data-theme="paper-moments"] body,
|
||||
[data-theme="paper-moments"] .feature-page,
|
||||
[data-theme="paper-moments"] .main-content {
|
||||
background-color: var(--color-background-primary);
|
||||
background-image: radial-gradient(#b5a69350 .8px, transparent .8px);
|
||||
background-size: 20px 20px;
|
||||
}
|
||||
|
||||
[data-theme="paper-moments"] .feature-header {
|
||||
flex-wrap: wrap;
|
||||
position: relative;
|
||||
padding: 24px;
|
||||
margin-top: 12px;
|
||||
border: 1px solid #685949;
|
||||
outline: 1px dashed #b5a693;
|
||||
outline-offset: -8px;
|
||||
border-radius: 12px 5px 12px 5px;
|
||||
background: #fffdf5;
|
||||
box-shadow: var(--shadow-md);
|
||||
}
|
||||
|
||||
[data-theme="paper-moments"] .feature-header::before,
|
||||
[data-theme="paper-moments"] .editor-preview::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -10px;
|
||||
left: 42%;
|
||||
width: 86px;
|
||||
height: 22px;
|
||||
background: repeating-linear-gradient(45deg, #c5dfe0b0 0 8px, #daeceba0 8px 16px);
|
||||
transform: rotate(-3deg);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
[data-theme="paper-moments"] .feature-header h1,
|
||||
[data-theme="paper-moments"] .panel-title,
|
||||
[data-theme="paper-moments"] .preview-heading h3 {
|
||||
color: #875343;
|
||||
font-family: Georgia, 'Noto Serif SC', 'Songti SC', SimSun, serif;
|
||||
letter-spacing: .04em;
|
||||
}
|
||||
|
||||
[data-theme="paper-moments"] .panel,
|
||||
[data-theme="paper-moments"] .item-card {
|
||||
border-color: #b5a693;
|
||||
border-radius: 8px;
|
||||
box-shadow: var(--shadow-sm);
|
||||
}
|
||||
|
||||
[data-theme="paper-moments"] .theme-card:nth-child(3n + 1) { background: #f8e9e3; }
|
||||
[data-theme="paper-moments"] .theme-card:nth-child(3n + 2) { background: #e8f0f0; }
|
||||
[data-theme="paper-moments"] .theme-card:nth-child(3n) { background: #fbf3d8; }
|
||||
|
||||
[data-theme="paper-moments"] .editor-preview {
|
||||
position: relative;
|
||||
border: 1px solid #685949;
|
||||
border-radius: 4px 14px 4px 10px;
|
||||
background-color: #fffef8;
|
||||
background-image: linear-gradient(90deg, transparent 20px, #e9cfc780 20px 22px, transparent 22px), repeating-linear-gradient(transparent 0 31px, #b6c7bd55 31px 32px);
|
||||
box-shadow: 4px 5px 0 #e3e9d7;
|
||||
}
|
||||
|
||||
[data-theme="paper-moments"] .editor-preview::before {
|
||||
background: repeating-linear-gradient(45deg, #e7bcb3b0 0 8px, #f2d4cba0 8px 16px);
|
||||
}
|
||||
|
||||
[data-theme="paper-moments"] .modal { border-color: #685949; border-radius: 12px; }
|
||||
[data-theme="paper-moments"] .upload-area { background: #fbf6e7; }
|
||||
[data-theme="paper-moments"] .button-secondary { background: #fff9e5; }
|
||||
|
||||
[data-theme="paper-moments"] .workspace-view,
|
||||
[data-theme="paper-moments"] .visual-editor {
|
||||
background: radial-gradient(#b5a69355 .8px, transparent .8px) 0 0 / 20px 20px #f3eee3;
|
||||
}
|
||||
[data-theme="paper-moments"] .secondary-sidebar {
|
||||
background: #fff9e9;
|
||||
border-right: 1px dashed #b5a693;
|
||||
}
|
||||
[data-theme="paper-moments"] .primary-sidebar { background: #f1e9dc; }
|
||||
[data-theme="paper-moments"] .file-tree-panel { background: #fff9e9; }
|
||||
[data-theme="paper-moments"] .workspace-tabs { background: #e5eeee; border-bottom: 1px dashed #b5a693; }
|
||||
[data-theme="paper-moments"] .workspace-tabs button[aria-selected="true"] { background: #f8e9e3; color: #875343; box-shadow: inset 0 -2px #a77a67; }
|
||||
[data-theme="paper-moments"] .outline-filename { border-bottom: 1px dashed #b5a693; }
|
||||
[data-theme="paper-moments"] .file-tree-panel .toolbar,
|
||||
[data-theme="paper-moments"] .sidebar-header { background: #e5eeee; border-bottom: 1px dashed #b5a693; }
|
||||
[data-theme="paper-moments"] .editor-header { background: #f8e9e3; border-bottom: 1px solid #b5a693; }
|
||||
[data-theme="paper-moments"] .markdown-toolbar { background: #fff9e9; border-bottom: 1px dashed #b5a693; }
|
||||
[data-theme="paper-moments"] .milkdown-host { padding: 30px 24px 40px; }
|
||||
[data-theme="paper-moments"] .milkdown-host .milkdown { background: transparent; }
|
||||
[data-theme="paper-moments"] .visual-editor .milkdown-host .ProseMirror {
|
||||
width: 90%;
|
||||
max-width: none;
|
||||
position: relative;
|
||||
min-height: calc(100vh - 220px);
|
||||
padding: 44px 40px 60px 52px;
|
||||
border: 1px solid #685949;
|
||||
border-radius: 8px 16px 8px 8px;
|
||||
outline: 1px dashed #c5b9a7;
|
||||
outline-offset: -10px;
|
||||
background: linear-gradient(90deg, transparent 32px, #e9cfc7 32px 34px, transparent 34px), #fffef8;
|
||||
box-shadow: 6px 6px 0 #d8e6e2, 12px 12px 0 #f0d8cf;
|
||||
}
|
||||
[data-theme="paper-moments"] .milkdown-host .ProseMirror::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -11px;
|
||||
left: calc(50% - 48px);
|
||||
width: 96px;
|
||||
height: 24px;
|
||||
background: repeating-linear-gradient(45deg, #e7bcb3c0 0 8px, #f2d4cbc0 8px 16px);
|
||||
transform: rotate(-3deg);
|
||||
pointer-events: none;
|
||||
}
|
||||
[data-theme="paper-moments"] .milkdown-host .ProseMirror > p {
|
||||
background-image: repeating-linear-gradient(transparent 0 calc(1lh - 1px), #b6c7bd55 calc(1lh - 1px) 1lh);
|
||||
}
|
||||
[data-theme="paper-moments"] .milkdown-host .ProseMirror > :is(h1, h2, h3) { color: #875343; }
|
||||
[data-theme="paper-moments"] .editor-pane.source { margin: 20px; width: calc(100% - 40px); border: 1px solid #b5a693; border-radius: 8px; background: #fffef8; box-shadow: var(--shadow-md); }
|
||||
@media (max-width: 720px) {
|
||||
[data-theme="paper-moments"] .milkdown-host { padding: 20px 12px 28px; }
|
||||
[data-theme="paper-moments"] .visual-editor .milkdown-host .ProseMirror { width: 100%; padding: 30px 18px 40px 38px; }
|
||||
}
|
||||
|
||||
/* Warm neutral surfaces preserve the contrast of the selected Shiki palette. */
|
||||
[data-theme="paper-moments"][data-code-theme="github-light"] {
|
||||
--color-code-background: #f1ecdf;
|
||||
--color-code-text: #302b25;
|
||||
--color-code-muted: #6d6256;
|
||||
--color-code-border: #b1a18b;
|
||||
}
|
||||
[data-theme="paper-moments"][data-code-theme="github-dark"] {
|
||||
--color-code-background: #282723;
|
||||
--color-code-text: #f1e9da;
|
||||
--color-code-muted: #bdb19f;
|
||||
--color-code-border: #786b59;
|
||||
}
|
||||
[data-theme="paper-moments"] .milkdown-host .milkdown-code-block {
|
||||
position: relative;
|
||||
padding-top: 34px;
|
||||
padding-bottom: 30px;
|
||||
border-color: var(--color-code-border);
|
||||
box-shadow: 3px 4px 0 #d8cebd;
|
||||
}
|
||||
[data-theme="paper-moments"] .milkdown-code-block::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 15px;
|
||||
left: 18px;
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 50%;
|
||||
background: #c77768;
|
||||
box-shadow: 18px 0 0 #c9a65d, 36px 0 0 #819b75;
|
||||
pointer-events: none;
|
||||
}
|
||||
[data-theme="paper-moments"] .milkdown-code-block::after {
|
||||
content: attr(data-language-label);
|
||||
position: absolute;
|
||||
right: 18px;
|
||||
bottom: 9px;
|
||||
max-width: calc(100% - 36px);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: var(--color-code-muted);
|
||||
font: 600 12px/1.4 var(--font-ui-mono);
|
||||
pointer-events: none;
|
||||
}
|
||||
[data-theme="paper-moments"] .milkdown-code-block .tools { margin-left: 72px; }
|
||||
[data-theme="paper-moments"] .milkdown-code-block .cm-activeLine,
|
||||
[data-theme="paper-moments"] .milkdown-code-block .cm-activeLineGutter { background: color-mix(in srgb, var(--color-code-text) 7%, transparent); }
|
||||
|
||||
[data-theme="paper-moments"] .note-metadata {
|
||||
position: relative;
|
||||
width: 90%;
|
||||
margin: 8px auto 30px;
|
||||
padding: 24px 30px;
|
||||
border: 1px solid #887460;
|
||||
border-radius: 8px 14px 8px 8px;
|
||||
outline: 1px dashed #c5b9a7;
|
||||
outline-offset: -8px;
|
||||
background: linear-gradient(110deg, #fffdf5, #fbf5e4);
|
||||
box-shadow: 4px 5px 0 #d8e6e2, 8px 9px 0 #f0d8cf;
|
||||
}
|
||||
[data-theme="paper-moments"] .note-metadata::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -10px;
|
||||
right: 36px;
|
||||
width: 78px;
|
||||
height: 22px;
|
||||
background: repeating-linear-gradient(45deg, #c5dfe0c0 0 8px, #daecebb0 8px 16px);
|
||||
transform: rotate(3deg);
|
||||
pointer-events: none;
|
||||
}
|
||||
[data-theme="paper-moments"] .metadata-caption { color: #806b58; letter-spacing: .12em; }
|
||||
[data-theme="paper-moments"] .note-metadata h1 {
|
||||
margin: 12px 0 18px;
|
||||
color: #875343;
|
||||
font-family: Georgia, 'Noto Serif SC', 'Songti SC', SimSun, serif;
|
||||
font-size: clamp(20px, 2vw, 28px);
|
||||
line-height: 1.4;
|
||||
}
|
||||
[data-theme="paper-moments"] .metadata-tags { padding-top: 14px; border-top: 1px dashed #c5b9a7; gap: 8px; }
|
||||
[data-theme="paper-moments"] .metadata-tag { border: 1px solid #d6b5a8; border-radius: 5px; background: #f5e3da; color: #704b3d; }
|
||||
[data-theme="paper-moments"] .metadata-tag:nth-of-type(2n + 1) { border-color: #b5cdcf; background: #e5eeee; color: #456671; }
|
||||
[data-theme="paper-moments"] .metadata-tag button { border-radius: 3px; cursor: pointer; }
|
||||
[data-theme="paper-moments"] .metadata-tag button:hover { background: #ffffff80; }
|
||||
[data-theme="paper-moments"] .metadata-tags input { border-color: #b5a693; background: #fffdf580; }
|
||||
[data-theme="paper-moments"] .metadata-tags form button { padding: 4px 10px; border: 1px solid #b5a693; border-radius: 5px; background: #f7edce; color: #704b3d; cursor: pointer; }
|
||||
[data-theme="paper-moments"] .metadata-tags button:focus-visible { outline: 2px solid #875343; outline-offset: 2px; }
|
||||
@media (max-width: 720px) {
|
||||
[data-theme="paper-moments"] .note-metadata { width: 100%; padding: 22px 18px; }
|
||||
}
|
||||
@@ -11,11 +11,11 @@ let renderVersion = 0
|
||||
const diagramTheme = computed<'light' | 'dark'>(() => (themeStore.isDark ? 'dark' : 'light'))
|
||||
|
||||
// 主题切换需要重渲染:Mermaid SVG 的配色在渲染时烘焙,无法靠 CSS 变量事后调整。
|
||||
watch([() => props.source, diagramTheme], async ([source, theme]) => {
|
||||
watch([() => props.source, diagramTheme, () => themeStore.currentThemeId], async ([source, theme]) => {
|
||||
const version = ++renderVersion
|
||||
const result = await renderMarkdown(source, { theme })
|
||||
if (version === renderVersion) html.value = result
|
||||
}, { immediate: true })
|
||||
}, { immediate: true, flush: 'post' })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -13,7 +13,7 @@ const emit = defineEmits<{
|
||||
(e: 'rendered', info: { width: number; height: number }): void
|
||||
}>()
|
||||
|
||||
const { mermaidTheme } = useMermaidTheme()
|
||||
const { mermaidTheme, themeId } = useMermaidTheme()
|
||||
const svgHtml = ref('')
|
||||
const isLoading = ref(true)
|
||||
const hasError = ref(false)
|
||||
@@ -52,7 +52,7 @@ async function doRender() {
|
||||
|
||||
onMounted(doRender)
|
||||
|
||||
watch(() => [props.source, mermaidTheme.value], () => { scale.value = 1; doRender() })
|
||||
watch(() => [props.source, mermaidTheme.value, themeId.value], () => { scale.value = 1; doRender() }, { flush: 'post' })
|
||||
|
||||
function zoomIn() { scale.value = Math.min(scale.value * 1.2, 5) }
|
||||
function zoomOut() { scale.value = Math.max(scale.value / 1.2, 0.2) }
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { expect, it } from 'vitest'
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { createRouter, createMemoryHistory } from 'vue-router'
|
||||
import SecondarySidebar from './SecondarySidebar.vue'
|
||||
|
||||
it('resizes by keyboard, clamps bounds and restores the saved width', async () => {
|
||||
localStorage.removeItem('workspace-sidebar-width')
|
||||
const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/', component: { template: '<div />' } }] })
|
||||
await router.push('/')
|
||||
const options = { props: { component: 'file-tree' }, global: { plugins: [router], stubs: { FileTreePanel: true } } }
|
||||
let wrapper = mount(SecondarySidebar, options)
|
||||
await wrapper.get('[role="separator"]').trigger('keydown', { key: 'ArrowRight' })
|
||||
expect(localStorage.getItem('workspace-sidebar-width')).toBe('288')
|
||||
wrapper.unmount()
|
||||
wrapper = mount(SecondarySidebar, options)
|
||||
await wrapper.vm.$nextTick()
|
||||
expect(wrapper.get('aside').attributes('style')).toContain('288px')
|
||||
await wrapper.get('[role="separator"]').trigger('keydown', { key: 'Home' })
|
||||
expect(wrapper.get('aside').attributes('style')).toContain('200px')
|
||||
wrapper.unmount()
|
||||
localStorage.removeItem('workspace-sidebar-width')
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import FileTreePanel from '@/features/workspace/FileTreePanel.vue'
|
||||
import ConversationListPanel from '@/features/chat/ConversationListPanel.vue'
|
||||
import RunListPanel from '@/features/agent/RunListPanel.vue'
|
||||
@@ -15,6 +15,40 @@ const props = defineProps<{
|
||||
|
||||
const route = useRoute()
|
||||
const routeName = computed(() => route.name as string)
|
||||
const sidebar = ref<HTMLElement | null>(null)
|
||||
const width = ref(272)
|
||||
const maxWidth = ref(520)
|
||||
let dragging = false
|
||||
function saveWidth() { try { localStorage.setItem('workspace-sidebar-width', String(width.value)) } catch { /* Keep resizing available when storage is unavailable. */ } }
|
||||
function clampWidth(value: number) { return Math.max(200, Math.min(maxWidth.value, value)) }
|
||||
function updateBounds() {
|
||||
maxWidth.value = Math.max(200, Math.min(520, window.innerWidth - (sidebar.value?.getBoundingClientRect().left ?? 0) - 320))
|
||||
width.value = clampWidth(width.value)
|
||||
}
|
||||
function beginResize(event: PointerEvent) {
|
||||
if (event.button !== 0) return
|
||||
event.preventDefault()
|
||||
updateBounds()
|
||||
dragging = true
|
||||
;(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId)
|
||||
}
|
||||
function resize(event: PointerEvent) {
|
||||
if (dragging) width.value = clampWidth(event.clientX - (sidebar.value?.getBoundingClientRect().left ?? 0))
|
||||
}
|
||||
function endResize() { if (dragging) { dragging = false; saveWidth() } }
|
||||
function resizeWithKeyboard(event: KeyboardEvent) {
|
||||
if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return
|
||||
event.preventDefault()
|
||||
updateBounds()
|
||||
width.value = event.key === 'Home' ? 200 : event.key === 'End' ? maxWidth.value : clampWidth(width.value + (event.key === 'ArrowLeft' ? -16 : 16))
|
||||
saveWidth()
|
||||
}
|
||||
onMounted(() => {
|
||||
try { const saved = Number(localStorage.getItem('workspace-sidebar-width')); if (saved >= 200 && Number.isFinite(saved)) width.value = saved } catch { /* Use default width. */ }
|
||||
updateBounds()
|
||||
window.addEventListener('resize', updateBounds)
|
||||
})
|
||||
onBeforeUnmount(() => { endResize(); window.removeEventListener('resize', updateBounds) })
|
||||
|
||||
const sidebarTitle = computed(() => {
|
||||
const titles: Record<string, string> = {
|
||||
@@ -32,15 +66,15 @@ const showSkillToggle = computed(() => routeName.value === 'skills' || routeName
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<aside class="secondary-sidebar">
|
||||
<div class="sidebar-header">
|
||||
<aside ref="sidebar" class="secondary-sidebar" :style="component === 'file-tree' ? { width: `${width}px` } : undefined">
|
||||
<div v-if="component !== 'file-tree'" class="sidebar-header">
|
||||
<h3 class="sidebar-title">{{ sidebarTitle }}</h3>
|
||||
<div v-if="showSkillToggle" class="sidebar-tabs">
|
||||
<router-link to="/extensions/skills" class="tab" :class="{ active: routeName === 'skills' }">Skill</router-link>
|
||||
<router-link to="/extensions/plugins" class="tab" :class="{ active: routeName === 'plugins' }">Plugin</router-link>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sidebar-content">
|
||||
<div class="sidebar-content" :class="{ 'file-sidebar-content': component === 'file-tree' }">
|
||||
<FileTreePanel v-if="component === 'file-tree'" />
|
||||
<ConversationListPanel v-else-if="component === 'conversation-list'" />
|
||||
<RunListPanel v-else-if="component === 'run-list'" />
|
||||
@@ -48,11 +82,13 @@ const showSkillToggle = computed(() => routeName.value === 'skills' || routeName
|
||||
<TaskFiltersPanel v-else-if="component === 'task-filters'" />
|
||||
<ExtensionListPanel v-else-if="component === 'extension-list'" />
|
||||
</div>
|
||||
<div v-if="component === 'file-tree'" class="sidebar-resizer" role="separator" aria-orientation="vertical" :aria-label="t('调整文件侧栏宽度', 'Resize file sidebar')" :aria-valuenow="width" :aria-valuemin="200" :aria-valuemax="maxWidth" tabindex="0" @pointerdown="beginResize" @pointermove="resize" @pointerup="endResize" @pointercancel="endResize" @lostpointercapture="endResize" @keydown="resizeWithKeyboard" @dblclick="width = clampWidth(272); saveWidth()" />
|
||||
</aside>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.secondary-sidebar {
|
||||
position: relative;
|
||||
width: var(--sidebar-secondary-width);
|
||||
background: var(--color-surface-secondary);
|
||||
border-right: 1px solid var(--color-border-default);
|
||||
@@ -111,5 +147,8 @@ const showSkillToggle = computed(() => routeName.value === 'skills' || routeName
|
||||
overflow-x: hidden;
|
||||
scrollbar-gutter: stable;
|
||||
}
|
||||
.sidebar-resizer { position: absolute; top: 0; bottom: 0; right: -3px; width: 6px; z-index: 20; cursor: col-resize; touch-action: none; }
|
||||
.sidebar-resizer:hover, .sidebar-resizer:focus-visible { background: var(--color-accent-secondary); outline: none; }
|
||||
.file-sidebar-content { min-height: 0; overflow: hidden; scrollbar-gutter: auto; }
|
||||
|
||||
</style>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue'
|
||||
import { useEditorStore } from '@/stores/editor'
|
||||
import { useSettingsStore } from '@/stores/settings'
|
||||
import { useThemeStore } from '@/stores/theme'
|
||||
@@ -7,6 +8,15 @@ import VisualMarkdownEditor from './VisualMarkdownEditor.vue'
|
||||
const editorStore = useEditorStore()
|
||||
const settingsStore = useSettingsStore()
|
||||
const themeStore = useThemeStore()
|
||||
const sourceEditor = ref<HTMLTextAreaElement | null>(null)
|
||||
watch(() => editorStore.headingRequest, request => {
|
||||
const input = sourceEditor.value
|
||||
if (!request || !input || request.path !== editorStore.currentFilePath) return
|
||||
input.focus()
|
||||
input.setSelectionRange(request.offset, request.offset)
|
||||
const lines = input.value.slice(0, request.offset).split('\n').length - 1
|
||||
input.scrollTop = lines * (parseFloat(getComputedStyle(input).lineHeight) || 24)
|
||||
})
|
||||
function updateContent(event: Event) {
|
||||
editorStore.updateContent((event.target as HTMLTextAreaElement).value)
|
||||
editorStore.scheduleAutoSave(settingsStore.autoSaveInterval)
|
||||
@@ -16,7 +26,7 @@ function updateContent(event: Event) {
|
||||
<template>
|
||||
<VisualMarkdownEditor v-if="editorStore.mode === 'wysiwyg'" :key="`${editorStore.currentFilePath ?? 'empty'}:${themeStore.resolvedCodeBlockTheme}:${settingsStore.language}`"
|
||||
:initial-content="editorStore.content" />
|
||||
<textarea v-else class="editor-pane source" :value="editorStore.content" :spellcheck="settingsStore.spellCheck"
|
||||
<textarea v-else ref="sourceEditor" class="editor-pane source" :value="editorStore.content" :spellcheck="settingsStore.spellCheck"
|
||||
:lang="settingsStore.language" :aria-label="settingsStore.language === 'en' ? 'Markdown source editor' : 'Markdown 源码编辑器'" @input="updateContent" />
|
||||
</template>
|
||||
|
||||
|
||||
@@ -9,6 +9,10 @@ import { indentWithTab } from '@codemirror/commands'
|
||||
import { shikiEditorTheme, shikiLanguages, renderCodeLanguage } from './shikiCodeMirror'
|
||||
import './language-icons.css'
|
||||
import { installLanguagePickerPopover } from './languagePickerPopover'
|
||||
import { installCodeBlockLabels } from './codeBlockLabels'
|
||||
import { createMermaidPreview } from './mermaidPreview'
|
||||
import { splitNoteMetadata, updateMetadataTags } from './noteMetadata'
|
||||
import { getMarkdown } from '@milkdown/kit/utils'
|
||||
import {
|
||||
createCodeBlockCommand,
|
||||
toggleEmphasisCommand,
|
||||
@@ -33,6 +37,22 @@ import '@milkdown/crepe/theme/common/style.css'
|
||||
import '@milkdown/crepe/theme/frame.css'
|
||||
|
||||
const props = defineProps<{ initialContent: string }>()
|
||||
const metadata = ref(splitNoteMetadata(props.initialContent))
|
||||
const tagDraft = ref('')
|
||||
function setTags(tags: string[]) {
|
||||
if (!metadata.value || !crepe) return
|
||||
const prefix = updateMetadataTags(metadata.value, tags)
|
||||
const body = crepe.editor.action(getMarkdown())
|
||||
metadata.value = splitNoteMetadata(prefix + body)
|
||||
editorStore.updateContent(prefix + body)
|
||||
editorStore.scheduleAutoSave(settingsStore.autoSaveInterval)
|
||||
}
|
||||
function addTags() {
|
||||
const tags = tagDraft.value.split(/[,,]/).map(tag => tag.trim()).filter(tag => tag && !/[\r\n"\\]/.test(tag))
|
||||
if (!tags.length || !metadata.value) return
|
||||
setTags([...metadata.value.tags, ...tags])
|
||||
tagDraft.value = ''
|
||||
}
|
||||
const editorStore = useEditorStore()
|
||||
const settingsStore = useSettingsStore()
|
||||
const themeStore = useThemeStore()
|
||||
@@ -41,6 +61,23 @@ const loading = ref(true)
|
||||
const fontSizeInput = ref(16)
|
||||
let crepe: Crepe | null = null
|
||||
let disposeLanguagePicker: (() => void) | undefined
|
||||
let disposeCodeLabels: (() => void) | undefined
|
||||
const diagramPreviews = new Map<string, { source: string; apply: (value: HTMLElement) => void }>()
|
||||
function renderDiagram(source: string, apply: (value: HTMLElement) => void) {
|
||||
for (const [id, entry] of diagramPreviews) {
|
||||
if (entry.apply === apply) diagramPreviews.delete(id)
|
||||
}
|
||||
const element = createMermaidPreview(source, themeStore.isDark, apply)
|
||||
diagramPreviews.set(element.id, { source, apply })
|
||||
return element
|
||||
}
|
||||
watch(() => themeStore.currentThemeId, () => {
|
||||
const current = [...diagramPreviews.entries()]
|
||||
diagramPreviews.clear()
|
||||
for (const [id, entry] of current) {
|
||||
if (editorRoot.value?.querySelector(`[id="${id}"]`)) entry.apply(renderDiagram(entry.source, entry.apply))
|
||||
}
|
||||
}, { flush: 'post' })
|
||||
|
||||
function applyProofingPreferences() {
|
||||
const editable = editorRoot.value?.querySelector<HTMLElement>('.ProseMirror')
|
||||
@@ -120,12 +157,14 @@ function applyFontSizeValue() {
|
||||
onMounted(async () => {
|
||||
crepe = new Crepe({
|
||||
root: editorRoot.value,
|
||||
defaultValue: props.initialContent,
|
||||
defaultValue: metadata.value?.body ?? props.initialContent,
|
||||
features: { [Crepe.Feature.TopBar]: false },
|
||||
featureConfigs: {
|
||||
[Crepe.Feature.Placeholder]: { text: t('开始记录你的想法…', 'Start writing your thoughts…') },
|
||||
[Crepe.Feature.CodeMirror]: {
|
||||
previewOnlyByDefault: false,
|
||||
previewOnlyByDefault: true,
|
||||
previewToggleText: previewOnly => previewOnly ? t('编辑', 'Edit') : t('预览', 'Preview'),
|
||||
previewLabel: t('图表预览', 'Preview'),
|
||||
searchPlaceholder: t('搜索语言', 'Search languages'),
|
||||
noResultText: t('没有匹配的语言', 'No matching language'),
|
||||
copyText: t('复制', 'Copy'),
|
||||
@@ -182,26 +221,44 @@ onMounted(async () => {
|
||||
...config,
|
||||
languages: shikiLanguages(themeStore.resolvedCodeBlockTheme),
|
||||
renderLanguage: renderCodeLanguage,
|
||||
renderPreview: (language, content, applyPreview) => language.trim().toLowerCase() === 'mermaid'
|
||||
? renderDiagram(content, applyPreview)
|
||||
: config.renderPreview(language, content, applyPreview),
|
||||
extensions: [basicSetup, keymap.of([indentWithTab]), shikiEditorTheme(themeStore.resolvedCodeBlockTheme)],
|
||||
})))
|
||||
crepe.editor.use(fontSizeMarkdownPlugin)
|
||||
crepe.on((listener) => {
|
||||
listener.markdownUpdated((_ctx, markdown, previousMarkdown) => {
|
||||
// 忽略编辑器初始化/回显事件,防止无内容变化时触发自动保存循环。
|
||||
if (markdown === previousMarkdown || markdown === editorStore.content) return
|
||||
editorStore.updateContent(markdown)
|
||||
const fullMarkdown = (metadata.value?.prefix ?? '') + markdown
|
||||
if (markdown === previousMarkdown || fullMarkdown === editorStore.content) return
|
||||
editorStore.updateContent(fullMarkdown)
|
||||
editorStore.scheduleAutoSave(settingsStore.autoSaveInterval)
|
||||
})
|
||||
})
|
||||
await crepe.create()
|
||||
if (editorRoot.value) disposeLanguagePicker = installLanguagePickerPopover(editorRoot.value)
|
||||
if (editorRoot.value) disposeCodeLabels = installCodeBlockLabels(editorRoot.value)
|
||||
applyProofingPreferences()
|
||||
loading.value = false
|
||||
})
|
||||
|
||||
watch([() => settingsStore.spellCheck, () => settingsStore.language], applyProofingPreferences)
|
||||
watch(() => editorStore.headingRequest, request => {
|
||||
if (!request || request.path !== editorStore.currentFilePath || !crepe) return
|
||||
crepe.editor.action(ctx => {
|
||||
const view = ctx.get(editorViewCtx)
|
||||
let index = 0
|
||||
view.state.doc.forEach((node, offset) => {
|
||||
if (node.type.name !== 'heading') return
|
||||
if (index++ !== request.index) return
|
||||
view.dispatch(view.state.tr.setSelection(TextSelection.create(view.state.doc, offset + 1)).scrollIntoView())
|
||||
view.focus()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => { disposeLanguagePicker?.(); void crepe?.destroy() })
|
||||
onBeforeUnmount(() => { diagramPreviews.clear(); disposeCodeLabels?.(); disposeLanguagePicker?.(); void crepe?.destroy() })
|
||||
|
||||
defineExpose({ getEditor: () => crepe?.editor })
|
||||
</script>
|
||||
@@ -244,7 +301,18 @@ defineExpose({ getEditor: () => crepe?.editor })
|
||||
<button type="button" :title="t('插入链接', 'Insert link')" :aria-label="t('插入链接', 'Insert link')" @pointerdown.prevent="applyLink"><AppIcon :icon="Link" :size="17" /></button>
|
||||
</div>
|
||||
<div v-if="loading" class="editor-loading">{{ t('正在加载编辑器…', 'Loading editor…') }}</div>
|
||||
<div ref="editorRoot" class="milkdown-host" :class="{ loading }" />
|
||||
<div class="milkdown-host" :class="{ loading }">
|
||||
<section v-if="metadata" class="note-metadata" :aria-label="t('笔记属性', 'Note properties')">
|
||||
<span class="metadata-caption">{{ t('笔记属性', 'Note properties') }}</span>
|
||||
<h1 v-if="metadata.title">{{ metadata.title }}</h1>
|
||||
<div class="metadata-tags">
|
||||
<span class="metadata-label">{{ t('标签', 'Tags') }}</span>
|
||||
<span v-for="tag in metadata.tags" :key="tag" class="metadata-tag"><span>{{ tag }}</span><button type="button" :aria-label="`${t('移除标签', 'Remove tag')} ${tag}`" @click="setTags(metadata.tags.filter(item => item !== tag))">×</button></span>
|
||||
<form @submit.prevent="addTags"><input v-model="tagDraft" :aria-label="t('添加标签', 'Add tag')" :placeholder="t('+ 添加标签', '+ Add tag')" /><button v-if="tagDraft.trim()" type="submit">{{ t('添加', 'Add') }}</button></form>
|
||||
</div>
|
||||
</section>
|
||||
<div ref="editorRoot" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -273,6 +341,20 @@ defineExpose({ getEditor: () => crepe?.editor })
|
||||
.toolbar-divider { width: 1px; height: 20px; margin: 0 var(--space-xs); background: var(--color-border-default); }
|
||||
.milkdown-host { flex: 1; min-height: 0; overflow: auto; color: var(--color-text-primary); }
|
||||
.milkdown-host.loading { visibility: hidden; }
|
||||
.note-metadata { box-sizing: border-box; width: 90%; margin: 0 auto 20px; padding: 20px 24px; border: 1px solid var(--color-border-default); border-radius: var(--radius-md); background: var(--color-surface-primary); }
|
||||
.metadata-caption { color: var(--color-text-secondary); font-size: var(--font-size-xs); }
|
||||
.note-metadata h1 { margin: 10px 0 16px; font-size: 24px; color: var(--color-text-primary); overflow-wrap: anywhere; }
|
||||
.metadata-tags { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
|
||||
.metadata-label { margin-right: 4px; color: var(--color-text-secondary); font-size: var(--font-size-sm); }
|
||||
.metadata-tag { display: inline-flex; align-items: center; gap: 6px; max-width: 100%; padding: 4px 8px; border-radius: var(--radius-full); background: var(--color-accent-soft); color: var(--color-accent-primary); font-size: var(--font-size-sm); }
|
||||
.metadata-tag > span { overflow-wrap: anywhere; min-width: 0; }
|
||||
.metadata-tag button { color: inherit; padding: 0 3px; }
|
||||
.metadata-tags form { display: flex; gap: 6px; }
|
||||
.metadata-tags input { width: 110px; padding: 5px 8px; border: 1px dashed var(--color-border-default); border-radius: var(--radius-sm); background: transparent; color: var(--color-text-primary); }
|
||||
.metadata-tags input:focus { outline: 2px solid var(--color-border-focus); }
|
||||
.milkdown-host :deep(.editor-mermaid-preview) { padding: 20px; overflow: auto; background: var(--color-surface-primary); color: var(--color-text-primary); }
|
||||
.milkdown-host :deep(.editor-mermaid-preview svg) { display: block; max-width: 100%; height: auto; margin: auto; }
|
||||
.milkdown-host :deep(.editor-mermaid-preview.has-error) { color: var(--color-error); white-space: pre-wrap; }
|
||||
.editor-loading { padding: var(--space-xl); color: var(--color-text-tertiary); }
|
||||
.milkdown-host :deep(.milkdown) {
|
||||
min-height: 100%;
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { expect, it } from 'vitest'
|
||||
import { installCodeBlockLabels } from './codeBlockLabels'
|
||||
|
||||
it('keeps footer labels in sync when the language changes and stops after disposal', async () => {
|
||||
const root = document.createElement('div')
|
||||
root.innerHTML = '<div class="milkdown-code-block"><button class="language-button">Python</button></div>'
|
||||
const dispose = installCodeBlockLabels(root)
|
||||
const block = root.firstElementChild as HTMLElement
|
||||
expect(block.dataset.languageLabel).toBe('Python')
|
||||
block.querySelector('button')!.textContent = 'TypeScript'
|
||||
await new Promise(resolve => setTimeout(resolve, 0))
|
||||
expect(block.dataset.languageLabel).toBe('TypeScript')
|
||||
dispose()
|
||||
block.querySelector('button')!.textContent = 'Rust'
|
||||
await new Promise(resolve => setTimeout(resolve, 0))
|
||||
expect(block.dataset.languageLabel).toBe('TypeScript')
|
||||
})
|
||||
@@ -0,0 +1,11 @@
|
||||
/** Mirror the live picker label for theme decorations without changing Markdown. */
|
||||
export function installCodeBlockLabels(root: HTMLElement): () => void {
|
||||
const sync = () => root.querySelectorAll<HTMLElement>('.milkdown-code-block').forEach(block => {
|
||||
const label = block.querySelector('.language-button')?.textContent?.trim() || 'Plain text'
|
||||
if (block.dataset.languageLabel !== label) block.dataset.languageLabel = label
|
||||
})
|
||||
const observer = new MutationObserver(sync)
|
||||
observer.observe(root, { subtree: true, childList: true, characterData: true })
|
||||
sync()
|
||||
return () => observer.disconnect()
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { expect, it, vi } from 'vitest'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import { renderMermaid } from '@/services/mermaidService'
|
||||
import { createMermaidPreview } from './mermaidPreview'
|
||||
|
||||
vi.mock('@/services/mermaidService', () => ({ renderMermaid: vi.fn() }))
|
||||
|
||||
it('renders SVG with the requested theme and keeps async revisions isolated', async () => {
|
||||
let finish!: (value: any) => void
|
||||
vi.mocked(renderMermaid).mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
|
||||
vi.mocked(renderMermaid).mockResolvedValueOnce({ svg: '<svg><text>new</text></svg>', warnings: [], width: 10, height: 10 })
|
||||
const oldPublish = vi.fn()
|
||||
const latestPublish = vi.fn()
|
||||
const old = createMermaidPreview('graph TD; A-->B', false, oldPublish)
|
||||
const latest = createMermaidPreview('graph TD; A-->C', true, latestPublish)
|
||||
document.body.append(latest.cloneNode(true))
|
||||
await flushPromises()
|
||||
finish({ svg: '<svg><text>old</text></svg>', warnings: [] })
|
||||
await flushPromises()
|
||||
expect(latest.querySelector('svg')?.textContent).toBe('new')
|
||||
expect(old.querySelector('svg')?.textContent).toBe('old')
|
||||
expect(oldPublish).not.toHaveBeenCalled()
|
||||
expect(latestPublish).toHaveBeenCalledWith(latest)
|
||||
expect(latestPublish.mock.calls[0]![0]).not.toBe(latest)
|
||||
document.getElementById(latest.id)?.remove()
|
||||
expect(renderMermaid).toHaveBeenLastCalledWith('graph TD; A-->C', { theme: 'dark' })
|
||||
})
|
||||
|
||||
it('shows syntax errors as text without executing markup', async () => {
|
||||
vi.mocked(renderMermaid).mockResolvedValueOnce({ svg: '', warnings: ['<img src=x onerror=alert(1)>'], width: 0, height: 0 })
|
||||
const preview = createMermaidPreview('invalid', false, vi.fn())
|
||||
await flushPromises()
|
||||
expect(preview.classList.contains('has-error')).toBe(true)
|
||||
expect(preview.querySelector('img')).toBeNull()
|
||||
expect(preview.textContent).toContain('点击编辑')
|
||||
})
|
||||
@@ -0,0 +1,39 @@
|
||||
import { nextTick } from 'vue'
|
||||
import { renderMermaid } from '@/services/mermaidService'
|
||||
import { t } from '@/i18n'
|
||||
|
||||
let previewId = 0
|
||||
export function createMermaidPreview(source: string, dark: boolean, applyPreview: (value: HTMLElement) => void): HTMLElement {
|
||||
// Each revision owns its element, so a slow render cannot replace newer content.
|
||||
const container = document.createElement('div')
|
||||
container.className = 'editor-mermaid-preview'
|
||||
container.id = `editor-mermaid-preview-${++previewId}`
|
||||
container.setAttribute('aria-live', 'polite')
|
||||
container.textContent = t('正在渲染图表…', 'Rendering diagram…')
|
||||
const publish = async () => {
|
||||
await nextTick()
|
||||
// Milkdown sanitizes and copies this element. Publish only if its revision
|
||||
// still exists; edits, language changes and unmounts remove the old marker.
|
||||
const visible = document.getElementById(container.id)
|
||||
if (visible) {
|
||||
// PreviewPanel copies HTML instead of retaining the supplied element.
|
||||
// Update the current copy through Milkdown's reactive callback.
|
||||
applyPreview(container.cloneNode(true) as HTMLElement)
|
||||
}
|
||||
}
|
||||
void renderMermaid(source, { theme: dark ? 'dark' : 'light' }).then(result => {
|
||||
if (result.warnings.length) {
|
||||
container.classList.add('has-error')
|
||||
container.textContent = `${t('图表语法有误,可点击编辑修改:', 'Diagram syntax error. Choose Edit to fix:')} ${result.warnings.join('\n')}`
|
||||
void publish()
|
||||
return
|
||||
}
|
||||
// Mermaid runs in strict mode; Milkdown sanitizes the preview before insertion.
|
||||
container.innerHTML = result.svg
|
||||
void publish()
|
||||
}).catch(() => {
|
||||
container.textContent = t('图表渲染失败,请点击编辑检查源码。', 'Unable to render diagram. Choose Edit to inspect the source.')
|
||||
void publish()
|
||||
})
|
||||
return container
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { expect, it } from 'vitest'
|
||||
import { parseDocument } from 'yaml'
|
||||
import { splitNoteMetadata, updateMetadataTags } from './noteMetadata'
|
||||
|
||||
it('renders legacy properties and saves real frontmatter without losing other fields', () => {
|
||||
const note = '***\n\ntitle: Python\ntags: python, 编程\nembedding_local_only: true\n----------------\n\n# 正文\n'
|
||||
const metadata = splitNoteMetadata(note)!
|
||||
expect(metadata.tags).toEqual(['python', '编程'])
|
||||
expect(metadata.body).toBe('\n# 正文\n')
|
||||
const prefix = updateMetadataTags(metadata, ['编程', '学习', '学习'])
|
||||
expect(prefix).toContain('embedding_local_only: true')
|
||||
expect(prefix.startsWith('---\n')).toBe(true)
|
||||
expect(splitNoteMetadata(prefix + metadata.body)!.tags).toEqual(['编程', '学习'])
|
||||
})
|
||||
|
||||
it('does not mistake ordinary Markdown for metadata', () => {
|
||||
expect(splitNoteMetadata('---\nA paragraph\n---\n')).toBeNull()
|
||||
})
|
||||
|
||||
it.each(['- python\n- rust', ' - python\n - rust', '[python, rust]'])('replaces the complete YAML tag list: %s', (list) => {
|
||||
const metadata = splitNoteMetadata(`---\ntitle: Demo\ntags:\n${list.startsWith('[') ? ' ' : ''}${list}\nextra:\n enabled: true # keep this\n---\n# Body\n`)!
|
||||
expect(metadata.tags).toEqual(['python', 'rust'])
|
||||
const prefix = updateMetadataTags(metadata, [...metadata.tags, 'new'])
|
||||
const updated = splitNoteMetadata(prefix + metadata.body)!
|
||||
expect(updated.tags).toEqual(['python', 'rust', 'new'])
|
||||
expect(updated.body).toBe('# Body\n')
|
||||
const document = parseDocument(updated.yaml)
|
||||
expect(document.errors).toEqual([])
|
||||
expect(document.toJS().extra).toEqual({ enabled: true })
|
||||
expect(prefix).toContain('# keep this')
|
||||
expect(splitNoteMetadata(updateMetadataTags(updated, []))!.tags).toEqual([])
|
||||
})
|
||||
|
||||
it('preserves quoted commas, escapes, multiline titles and nested properties', () => {
|
||||
const tags = ['a,b', 'quote"tag', 'path\\tag', 'true']
|
||||
const metadata = splitNoteMetadata(`---\ntitle: |\n A multiline\n title\ntags: ${JSON.stringify(tags)}\nextra: {count: 2, enabled: false}\n---\n正文`)!
|
||||
expect(metadata.tags).toEqual(tags)
|
||||
const updated = splitNoteMetadata(updateMetadataTags(metadata, tags) + metadata.body)!
|
||||
expect(updated.tags).toEqual(tags)
|
||||
expect(updated.title).toBe(metadata.title)
|
||||
expect(parseDocument(updated.yaml).toJS().extra).toEqual({ count: 2, enabled: false })
|
||||
})
|
||||
|
||||
it('preserves document encoding markers and tag anchors', () => {
|
||||
const metadata = splitNoteMetadata('\uFEFF---\r\ntitle: Demo\r\ntags: &labels [python]\r\nrelated: *labels\r\n---\r\nBody')!
|
||||
const prefix = updateMetadataTags(metadata, ['rust'])
|
||||
expect(prefix.startsWith('\uFEFF---\r\n')).toBe(true)
|
||||
expect(prefix.replace(/\r\n/g, '')).not.toContain('\n')
|
||||
expect(parseDocument(splitNoteMetadata(prefix)!.yaml).toJS().related).toEqual(['rust'])
|
||||
})
|
||||
|
||||
it.each(['tags: [broken', 'tags: [one]\ntags: [two]', 'tags: {nested: value}', 'tags: [1, true]', 'tags: [&label python]\nother: *label'])('leaves invalid or unsupported tag data in source mode: %s', (yaml) => {
|
||||
expect(splitNoteMetadata(`---\ntitle: Demo\n${yaml}\n---\nBody`)).toBeNull()
|
||||
})
|
||||
@@ -0,0 +1,2 @@
|
||||
export { splitNoteMetadata, updateMetadataTags } from '@/utils/noteMetadata'
|
||||
export type { NoteMetadata } from '@/utils/noteMetadata'
|
||||
@@ -16,10 +16,15 @@ const previewDocument = computed(() => {
|
||||
style.textContent = `${tokensCss}\n${getCommunityThemePreviewCss(props.themeId)}\nbody { margin:0; padding:24px; background:var(--color-background-primary); color:var(--color-text-primary); font:16px/1.6 system-ui; } article { padding:20px; border:1px solid var(--color-border-default); border-radius:8px; background:var(--color-surface-primary); } p { color:var(--color-text-secondary); } button { padding:8px 16px; border:0; border-radius:6px; background:var(--color-accent-primary); color:white; }`
|
||||
doc.head.append(style)
|
||||
const article = doc.createElement('article')
|
||||
article.className = 'panel'
|
||||
const header = doc.createElement('header'); header.className = 'feature-header'
|
||||
const heading = doc.createElement('h1'); heading.textContent = theme.value?.name ?? props.themeId
|
||||
header.append(heading)
|
||||
const journal = doc.createElement('section'); journal.className = 'editor-preview'; journal.style.cssText = 'padding:24px;margin:28px 0;'
|
||||
const text = doc.createElement('p'); text.textContent = t('知识的价值不只在于保存,更在于被重新发现和使用。', 'Knowledge gains value when it can be rediscovered and used.')
|
||||
const button = doc.createElement('button'); button.textContent = t('示例按钮', 'Example button')
|
||||
article.append(heading, text, button); doc.body.append(article)
|
||||
journal.append(text)
|
||||
article.append(header, journal, button); doc.body.append(article)
|
||||
return '<!doctype html>' + doc.documentElement.outerHTML
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -5,10 +5,62 @@ import { createPinia, setActivePinia } from 'pinia'
|
||||
import ThemesView from './ThemesView.vue'
|
||||
import { useThemeStore } from '@/stores/theme'
|
||||
import { mockCommunityThemes, getCommunityThemePreviewCss } from '@/services/themePackageService'
|
||||
import paperPackage from '@/assets/themes/paper-moments.theme?raw'
|
||||
|
||||
let wrapper: VueWrapper
|
||||
beforeEach(() => { localStorage.clear(); setActivePinia(createPinia()) })
|
||||
afterEach(() => { wrapper?.unmount(); vi.useRealTimers() })
|
||||
afterEach(() => { useThemeStore().applyTheme('light'); wrapper?.unmount(); vi.restoreAllMocks(); vi.unstubAllGlobals(); vi.useRealTimers() })
|
||||
|
||||
it('downloads a URL for inspection without automatically installing it', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(paperPackage)))
|
||||
wrapper = mount(ThemesView, { global: { stubs: { MarkdownContent: true } } })
|
||||
await flushPromises()
|
||||
await wrapper.findAll('button').find(button => button.text() === '导入主题')!.trigger('click')
|
||||
await wrapper.get('#theme-package-url').setValue('https://example.com/paper.theme')
|
||||
await wrapper.get('.url-import').trigger('submit')
|
||||
await vi.waitFor(() => expect(useThemeStore().pendingInspection?.compatible).toBe(true))
|
||||
expect(useThemeStore().isThemeInstalled('paper-moments')).toBe(false)
|
||||
expect(wrapper.get('.inspection-result').text()).toContain('纸间时光')
|
||||
})
|
||||
|
||||
it('ignores a URL response after the dialog is cancelled', async () => {
|
||||
let respond!: (response: Response) => void
|
||||
vi.stubGlobal('fetch', vi.fn(() => new Promise(resolve => { respond = resolve })))
|
||||
wrapper = mount(ThemesView, { global: { stubs: { MarkdownContent: true } } })
|
||||
await flushPromises()
|
||||
await wrapper.findAll('button').find(button => button.text() === '导入主题')!.trigger('click')
|
||||
await wrapper.get('#theme-package-url').setValue('https://example.com/paper.theme')
|
||||
await wrapper.get('.url-import').trigger('submit')
|
||||
await wrapper.get('.import-modal .inline-actions button').trigger('click')
|
||||
respond(new Response(paperPackage))
|
||||
await flushPromises()
|
||||
expect(useThemeStore().pendingInspection).toBeNull()
|
||||
expect(wrapper.find('.import-modal').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('opens the file picker from the styled button and imports the actual paper theme', async () => {
|
||||
const store = useThemeStore()
|
||||
wrapper = mount(ThemesView, { global: { stubs: { MarkdownContent: true } } })
|
||||
await flushPromises()
|
||||
await wrapper.findAll('button').find(button => button.text() === '导入主题')!.trigger('click')
|
||||
const input = wrapper.get<HTMLInputElement>('input[type="file"]')
|
||||
const click = vi.spyOn(input.element, 'click').mockImplementation(() => {})
|
||||
await wrapper.get('.upload-area .button-primary').trigger('click')
|
||||
expect(click).toHaveBeenCalledOnce()
|
||||
Object.defineProperty(input.element, 'files', { value: [new File([paperPackage], 'paper-moments.theme', { type: 'text/plain' })] })
|
||||
await input.trigger('change')
|
||||
await vi.waitFor(() => expect(store.pendingInspection?.compatible).toBe(true))
|
||||
expect(store.pendingInspection!.warnings).toEqual([])
|
||||
await wrapper.get('.import-modal .inline-actions .button-primary').trigger('click')
|
||||
await flushPromises()
|
||||
expect(store.isThemeInstalled('paper-moments')).toBe(true)
|
||||
expect(localStorage.getItem('installed-themes-css-paper-moments')).toBe(getCommunityThemePreviewCss('paper-moments'))
|
||||
expect(document.getElementById('theme-style-paper-moments')).toBeNull()
|
||||
store.applyTheme('paper-moments')
|
||||
expect(document.getElementById('theme-style-paper-moments')!.textContent).toBe(getCommunityThemePreviewCss('paper-moments'))
|
||||
store.applyTheme('light')
|
||||
expect(document.getElementById('theme-style-paper-moments')).toBeNull()
|
||||
})
|
||||
|
||||
it.each(mockCommunityThemes)('previews uninstalled $theme_id using its actual CSS without changing the active theme', async theme => {
|
||||
const store = useThemeStore()
|
||||
|
||||
@@ -1,19 +1,58 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { computed, onMounted, onBeforeUnmount, ref } from 'vue'
|
||||
import MarkdownContent from '@/components/common/MarkdownContent.vue'
|
||||
import { useThemeStore } from '@/stores/theme'
|
||||
import { mockCommunityThemes } from '@/services/themePackageService'
|
||||
import { mockCommunityThemes, decodeThemePackage, fetchThemePackage, inspectThemePackage, MAX_THEME_BYTES } from '@/services/themePackageService'
|
||||
import type { ThemePackageInspection } from '@/contracts'
|
||||
import { t } from '@/i18n'
|
||||
import CommunityThemePreview from './CommunityThemePreview.vue'
|
||||
import paperMomentsUrl from '@/assets/themes/paper-moments.theme?url'
|
||||
|
||||
const themeStore = useThemeStore()
|
||||
|
||||
const activeTab = ref<'installed' | 'community'>('installed')
|
||||
const showImportDialog = ref(false)
|
||||
const fileInput = ref<HTMLInputElement | null>(null)
|
||||
const previewThemeId = ref<string | null>(null)
|
||||
const communityPreviewId = ref<string | null>(null)
|
||||
const actionError = ref('')
|
||||
const importUrl = ref('')
|
||||
const importing = ref(false)
|
||||
let importGeneration = 0
|
||||
let downloadController: AbortController | undefined
|
||||
|
||||
function resetImport() {
|
||||
importGeneration++
|
||||
downloadController?.abort()
|
||||
importing.value = false
|
||||
themeStore.pendingInspection = null
|
||||
themeStore.importError = null
|
||||
actionError.value = ''
|
||||
}
|
||||
function closeImport() { resetImport(); showImportDialog.value = false }
|
||||
function openImport() { resetImport(); showImportDialog.value = true }
|
||||
onBeforeUnmount(resetImport)
|
||||
|
||||
async function importPackage(load: () => Promise<string>) {
|
||||
resetImport()
|
||||
const generation = importGeneration
|
||||
importing.value = true
|
||||
try {
|
||||
const result = await inspectThemePackage(await load())
|
||||
if (generation !== importGeneration) return
|
||||
themeStore.pendingInspection = result
|
||||
if (!result.compatible) actionError.value = result.warnings[0] ?? '主题包无法解析'
|
||||
} catch (error) {
|
||||
if (generation === importGeneration) actionError.value = error instanceof Error ? error.message : '导入失败'
|
||||
} finally { if (generation === importGeneration) importing.value = false }
|
||||
}
|
||||
|
||||
function importFromUrl() {
|
||||
void importPackage(() => {
|
||||
downloadController = new AbortController()
|
||||
return fetchThemePackage(importUrl.value, downloadController.signal)
|
||||
})
|
||||
}
|
||||
|
||||
const shikiPreview = `\`\`\`typescript
|
||||
const notes = await search('本地优先')
|
||||
@@ -30,23 +69,16 @@ function handleFileImport(event: Event) {
|
||||
const file = input.files?.[0]
|
||||
input.value = ''
|
||||
if (!file) return
|
||||
actionError.value = ''
|
||||
const reader = new FileReader()
|
||||
reader.onload = async () => {
|
||||
try {
|
||||
const result = await themeStore.inspectThemePackage(String(reader.result ?? ''))
|
||||
if (result.compatible) {
|
||||
previewThemeId.value = result.manifest.theme_id
|
||||
} else {
|
||||
actionError.value = result.warnings[0] ?? '主题包无法解析'
|
||||
}
|
||||
} catch (error) {
|
||||
actionError.value = error instanceof Error ? error.message : '导入失败'
|
||||
}
|
||||
}
|
||||
reader.onerror = () => { actionError.value = '文件读取失败' }
|
||||
// 主题包是文本格式(YAML 清单 + --- + CSS),二进制包在解析阶段会被拒绝。
|
||||
reader.readAsText(file)
|
||||
void importPackage(async () => {
|
||||
if (file.size > MAX_THEME_BYTES) throw new Error('主题包不能超过 5 MB')
|
||||
const bytes = await new Promise<ArrayBuffer>((resolve, reject) => {
|
||||
const reader = new FileReader()
|
||||
reader.onload = () => resolve(reader.result as ArrayBuffer)
|
||||
reader.onerror = () => reject(new Error('文件读取失败'))
|
||||
reader.readAsArrayBuffer(file)
|
||||
})
|
||||
return decodeThemePackage(new Uint8Array(bytes))
|
||||
})
|
||||
}
|
||||
|
||||
async function confirmInstall(inspection: ThemePackageInspection) {
|
||||
@@ -90,7 +122,7 @@ onMounted(() => {
|
||||
<p>浏览、导入和管理主题,打造你的知识工作流。</p>
|
||||
</div>
|
||||
<div class="inline-actions">
|
||||
<button class="button-secondary" @click="showImportDialog = true">导入主题</button>
|
||||
<button class="button-secondary" @click="openImport">导入主题</button>
|
||||
<button class="button-secondary" @click="themeStore.resetToDefault()">{{ t('恢复默认', 'Reset defaults') }}</button>
|
||||
</div>
|
||||
</header>
|
||||
@@ -124,7 +156,7 @@ onMounted(() => {
|
||||
:class="{ selected: themeStore.currentThemeId === theme.theme_id }"
|
||||
@click="themeStore.applyTheme(theme.theme_id)"
|
||||
>
|
||||
<div class="theme-preview" :class="theme.is_dark ? 'preview-dark' : (theme.theme_id === 'sepia' ? 'preview-sepia' : 'preview-light')">
|
||||
<div class="theme-preview" :class="theme.theme_id === 'paper-moments' ? 'preview-paper' : theme.is_dark ? 'preview-dark' : (theme.theme_id === 'sepia' ? 'preview-sepia' : 'preview-light')">
|
||||
<span></span><span></span><span></span><div></div>
|
||||
</div>
|
||||
<div class="theme-info">
|
||||
@@ -150,7 +182,7 @@ onMounted(() => {
|
||||
:key="theme.theme_id"
|
||||
class="item-card theme-card"
|
||||
>
|
||||
<div class="theme-preview" :class="theme.is_dark ? 'preview-dark' : 'preview-light'">
|
||||
<div class="theme-preview" :class="theme.theme_id === 'paper-moments' ? 'preview-paper' : theme.is_dark ? 'preview-dark' : 'preview-light'">
|
||||
<span></span><span></span><span></span><div></div>
|
||||
</div>
|
||||
<div class="theme-info">
|
||||
@@ -165,14 +197,15 @@ onMounted(() => {
|
||||
<span v-for="tag in theme.tags" :key="tag" class="tag">{{ tag }}</span>
|
||||
</div>
|
||||
<div class="theme-actions">
|
||||
<a v-if="theme.theme_id === 'paper-moments'" class="button-secondary small" :href="paperMomentsUrl" download="paper-moments.theme">下载主题包</a>
|
||||
<button
|
||||
v-if="themeStore.isThemeInstalled(theme.theme_id)"
|
||||
v-if="themeStore.allThemes.some(installed => installed.theme_id === theme.theme_id && installed.version === theme.version)"
|
||||
class="button-secondary small"
|
||||
@click="themeStore.applyTheme(theme.theme_id)"
|
||||
>启用</button>
|
||||
<template v-else>
|
||||
<button class="button-secondary small" @click="previewCommunity(theme.theme_id)">预览</button>
|
||||
<button class="button-primary small" @click="installFromCommunity(theme.theme_id)">安装</button>
|
||||
<button class="button-primary small" @click="installFromCommunity(theme.theme_id)">{{ themeStore.isThemeInstalled(theme.theme_id) ? '更新' : '安装' }}</button>
|
||||
</template>
|
||||
</div>
|
||||
</article>
|
||||
@@ -193,11 +226,12 @@ onMounted(() => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="showImportDialog" class="modal-backdrop" @click.self="showImportDialog = false">
|
||||
<div v-if="showImportDialog" class="modal-backdrop" @click.self="closeImport">
|
||||
<div class="modal import-modal">
|
||||
<span class="badge info">主题导入</span>
|
||||
<h2>导入主题包</h2>
|
||||
<p class="subtle">单文件主题包:YAML 清单 + 一行 <code>---</code> + 主题 CSS。安装前会校验清单与 CSS 安全性。</p>
|
||||
<p class="subtle">选择本地文件或粘贴主题包直链。支持单文件主题与 ZIP,安装前会校验清单和 CSS。</p>
|
||||
<p v-if="actionError" class="error-banner" role="alert">{{ actionError }}</p>
|
||||
|
||||
<div v-if="themeStore.pendingInspection?.compatible" class="inspection-result">
|
||||
<div class="inspect-head">
|
||||
@@ -222,13 +256,21 @@ onMounted(() => {
|
||||
</div>
|
||||
|
||||
<div v-else class="upload-area">
|
||||
<input type="file" accept=".yaml,.yml,.theme" @change="handleFileImport" />
|
||||
<p>点击选择主题包文件</p>
|
||||
<p class="subtle">支持 .yaml / .yml / .theme;ZIP 需要 Host 端解压,暂不支持。</p>
|
||||
<input ref="fileInput" class="theme-file-input" type="file" accept=".yaml,.yml,.theme,.zip" tabindex="-1" aria-label="主题包文件" @change="handleFileImport" />
|
||||
<button type="button" class="button-primary" :disabled="importing" @click="fileInput?.click()">选择主题包文件</button>
|
||||
<p>从本地导入你喜欢的主题</p>
|
||||
<p class="subtle">支持 .yaml / .yml / .theme / .zip,最大 5 MB。</p>
|
||||
<form class="url-import" @submit.prevent="importFromUrl">
|
||||
<label for="theme-package-url">从 URL 导入</label>
|
||||
<input id="theme-package-url" v-model="importUrl" class="input" type="url" required placeholder="https://example.com/theme.zip" :disabled="importing" />
|
||||
<button class="button-secondary" type="submit" :disabled="importing">{{ importing ? '正在读取…' : '下载并校验' }}</button>
|
||||
<p class="subtle">请使用文件直链;远程服务器需允许跨域访问。</p>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="inline-actions">
|
||||
<button class="button-secondary" @click="showImportDialog = false">取消</button>
|
||||
<button v-if="themeStore.pendingInspection?.compatible" class="button-secondary" @click="resetImport">重新选择</button>
|
||||
<button class="button-secondary" @click="closeImport">取消</button>
|
||||
<button
|
||||
v-if="themeStore.pendingInspection?.compatible"
|
||||
class="button-primary"
|
||||
@@ -262,9 +304,16 @@ onMounted(() => {
|
||||
.preview-sepia { background: #fbf3df; border-color: #ddcfad; }
|
||||
.preview-sepia span { background: #d8c69c; }
|
||||
.preview-sepia div { background: #f4e8ca; }
|
||||
.preview-paper { background: #fffdf5; border: 1px dashed #8b7865; box-shadow: 3px 3px 0 #d8e6e2, 6px 6px 0 #f0d8cf; }
|
||||
.preview-paper span { background: #efd8d0; }
|
||||
.preview-paper span:nth-child(2) { background: #d8e7e8; }
|
||||
.preview-paper span:nth-child(3) { background: #f6e9b8; }
|
||||
.preview-paper div { border: 1px solid #b5a693; background: repeating-linear-gradient(#fffef8 0 14px, #dce4db 14px 15px); }
|
||||
.theme-actions a { text-decoration: none; }
|
||||
|
||||
.theme-info { display: flex; justify-content: space-between; gap: var(--space-md); align-items: flex-start; }
|
||||
.theme-info strong { display: block; margin-bottom: 2px; }
|
||||
.theme-info > .badge { flex-shrink: 0; white-space: nowrap; }
|
||||
|
||||
.theme-tags { display: flex; flex-wrap: wrap; gap: 4px; }
|
||||
.tag {
|
||||
@@ -347,10 +396,10 @@ onMounted(() => {
|
||||
transition: border-color var(--motion-fast);
|
||||
}
|
||||
.upload-area:hover { border-color: var(--color-accent-secondary); }
|
||||
.upload-area input {
|
||||
display: block;
|
||||
margin: 0 auto var(--space-md);
|
||||
}
|
||||
.url-import { display: grid; gap: 10px; margin-top: 20px; padding-top: 20px; border-top: 1px solid var(--color-border-default); text-align: left; }
|
||||
.url-import .input { width: 100%; min-width: 0; }
|
||||
.upload-area .theme-file-input { display: none; }
|
||||
.upload-area > button { margin-bottom: var(--space-md); }
|
||||
.upload-area p { color: var(--color-text-secondary); }
|
||||
|
||||
.inspection-result {
|
||||
|
||||
@@ -48,6 +48,77 @@ afterEach(() => {
|
||||
})
|
||||
|
||||
describe('FileTreePanel file switching', () => {
|
||||
it('expands every nested folder from the toolbar', async () => {
|
||||
const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/workspace', component: { template: '<div />' } }] })
|
||||
await router.push('/workspace')
|
||||
const store = useWorkspaceStore()
|
||||
store.fileTree = [{ id: 'a', name: 'A', path: '/a', type: 'folder', is_open: false, children: [{ id: 'b', name: 'B', path: '/a/b', type: 'folder', is_open: false }] }]
|
||||
wrapper = mount(FileTreePanel, { global: { plugins: [router] } })
|
||||
await wrapper.get('[aria-label="全部展开文件夹"]').trigger('click')
|
||||
expect(store.fileTree[0]!.is_open).toBe(true)
|
||||
expect(store.fileTree[0]!.children![0]!.is_open).toBe(true)
|
||||
})
|
||||
it('switches full-height panels using tabs and preserves the file search', async () => {
|
||||
const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/workspace', component: { template: '<div />' } }] })
|
||||
await router.push('/workspace')
|
||||
wrapper = mount(FileTreePanel, { attachTo: document.body, global: { plugins: [router] } })
|
||||
expect(wrapper.get('#workspace-files-panel').isVisible()).toBe(true)
|
||||
expect(wrapper.get('#workspace-outline-panel').isVisible()).toBe(false)
|
||||
await wrapper.get('.file-tree-panel').trigger('wheel', { deltaY: -50 })
|
||||
await wrapper.get('.file-search input').setValue('笔记')
|
||||
await wrapper.get('#workspace-outline-tab').trigger('click')
|
||||
expect(wrapper.get('#workspace-files-panel').isVisible()).toBe(false)
|
||||
expect(wrapper.get('#workspace-outline-panel').isVisible()).toBe(true)
|
||||
expect(wrapper.get('#workspace-outline-tab').attributes('aria-selected')).toBe('true')
|
||||
await wrapper.get('#workspace-outline-tab').trigger('keydown', { key: 'ArrowLeft' })
|
||||
expect(wrapper.get('#workspace-files-panel').isVisible()).toBe(true)
|
||||
expect((wrapper.get('.file-search input').element as HTMLInputElement).value).toBe('笔记')
|
||||
})
|
||||
it('reveals search on upward wheel and filters without changing folder state', async () => {
|
||||
const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/workspace', component: { template: '<div />' } }] })
|
||||
await router.push('/workspace')
|
||||
const store = useWorkspaceStore()
|
||||
await store.openVault('C:/vault')
|
||||
store.toggleFolder('/数据结构')
|
||||
wrapper = mount(FileTreePanel, { global: { plugins: [router] } })
|
||||
expect(wrapper.find('.file-search').exists()).toBe(false)
|
||||
await wrapper.get('.file-tree-panel').trigger('wheel', { deltaY: -50 })
|
||||
await wrapper.get('.file-search input').setValue('红黑')
|
||||
expect(wrapper.findAll('.tree-node').map(node => node.text())).toEqual(['数据结构', '红黑树.md'])
|
||||
expect(store.fileTree[0]!.is_open).toBe(false)
|
||||
await wrapper.get('.file-tree-panel').trigger('wheel', { deltaY: 50 })
|
||||
expect(wrapper.find('.file-search').exists()).toBe(true)
|
||||
})
|
||||
|
||||
it('creates a folder through the file context menu in its containing directory', async () => {
|
||||
const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/workspace', component: { template: '<div />' } }] })
|
||||
await router.push('/workspace')
|
||||
await useWorkspaceStore().openVault('C:/vault')
|
||||
const create = vi.spyOn(workspaceService, 'createFolder').mockResolvedValue({ id: 'new', name: '子目录', path: '/数据结构/子目录', type: 'folder' })
|
||||
wrapper = mount(FileTreePanel, { attachTo: document.body, global: { plugins: [router] } })
|
||||
await wrapper.findAll('.tree-node').find(node => node.text().includes('红黑树'))!.trigger('contextmenu')
|
||||
const button = [...document.querySelectorAll<HTMLButtonElement>('.context-menu button')].find(item => item.textContent === '新建文件夹')!
|
||||
button.click()
|
||||
await wrapper.vm.$nextTick()
|
||||
await wrapper.get('.new-item input').setValue('子目录')
|
||||
await wrapper.get('.new-item').trigger('submit')
|
||||
expect(create).toHaveBeenCalledWith('/数据结构', '子目录')
|
||||
})
|
||||
|
||||
it('collapses nested headings and requests navigation to a duplicate heading', async () => {
|
||||
const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/workspace', component: { template: '<div />' } }] })
|
||||
await router.push('/workspace')
|
||||
const store = useEditorStore()
|
||||
store.currentFilePath = '/note.md'
|
||||
store.content = '# 标题\n\n## 子标题\n\n# 标题\n'
|
||||
wrapper = mount(FileTreePanel, { global: { plugins: [router] } })
|
||||
await wrapper.get('#workspace-outline-tab').trigger('click')
|
||||
expect(wrapper.findAll('.outline-title')).toHaveLength(3)
|
||||
await wrapper.get('.outline-row button[aria-expanded]').trigger('click')
|
||||
expect(wrapper.findAll('.outline-title')).toHaveLength(2)
|
||||
await wrapper.findAll('.outline-title')[1]!.trigger('click')
|
||||
expect(store.headingRequest).toEqual({ index: 2, offset: store.content.lastIndexOf('# 标题'), path: '/note.md' })
|
||||
})
|
||||
it('switches both workspace selection and editor content on consecutive clicks', async () => {
|
||||
const router = createRouter({
|
||||
history: createMemoryHistory(),
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue'
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
import { noteOutline } from './outline'
|
||||
import { useRouter } from 'vue-router'
|
||||
import type { FileNode } from '@/contracts'
|
||||
import * as workspaceService from '@/services/workspaceService'
|
||||
import { useEditorStore } from '@/stores/editor'
|
||||
import { useWorkspaceStore } from '@/stores/workspace'
|
||||
import FileTreeNode from './FileTreeNode.vue'
|
||||
import { DocumentAdd, FolderAdd } from '@element-plus/icons-vue'
|
||||
import { Document, DocumentAdd, FolderAdd, ArrowRight } from '@element-plus/icons-vue'
|
||||
import AppIcon from '@/components/common/AppIcon.vue'
|
||||
import { t } from '@/i18n'
|
||||
|
||||
@@ -22,6 +23,70 @@ const selectedFolderPath = ref(
|
||||
)
|
||||
const contextTarget = ref<FileNode | null>(null)
|
||||
const contextMenuPosition = ref({ x: 0, y: 0 })
|
||||
const searchVisible = ref(false)
|
||||
const activeTab = ref<'files' | 'outline'>('files')
|
||||
function switchTab(tab: 'files' | 'outline') { activeTab.value = tab; closeContextMenu() }
|
||||
function navigateTabs(event: KeyboardEvent) {
|
||||
if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return
|
||||
event.preventDefault()
|
||||
switchTab(event.key === 'Home' ? 'files' : event.key === 'End' ? 'outline' : activeTab.value === 'files' ? 'outline' : 'files')
|
||||
const parent = (event.target as HTMLElement).parentElement
|
||||
void nextTick(() => parent?.querySelector<HTMLButtonElement>('[aria-selected="true"]')?.focus())
|
||||
}
|
||||
const searchQuery = ref('')
|
||||
const searchFocused = ref(false)
|
||||
const createInput = ref<HTMLInputElement | null>(null)
|
||||
const createError = ref('')
|
||||
const creating = ref(false)
|
||||
const outline = computed(() => noteOutline(editorStore.content))
|
||||
const collapsedHeadings = ref(new Set<number>())
|
||||
const visibleHeadings = computed(() => {
|
||||
let hiddenBelow = 7
|
||||
return outline.value.filter(heading => {
|
||||
if (heading.level > hiddenBelow) return false
|
||||
hiddenBelow = collapsedHeadings.value.has(heading.index) ? heading.level : 7
|
||||
return true
|
||||
})
|
||||
})
|
||||
const hasChildren = (index: number) => {
|
||||
const position = outline.value.findIndex(heading => heading.index === index)
|
||||
return (outline.value[position + 1]?.level ?? 0) > (outline.value[position]?.level ?? 6)
|
||||
}
|
||||
function toggleHeading(index: number) {
|
||||
const next = new Set(collapsedHeadings.value)
|
||||
if (next.has(index)) next.delete(index); else next.add(index)
|
||||
collapsedHeadings.value = next
|
||||
}
|
||||
watch(() => editorStore.content, () => { collapsedHeadings.value = new Set() })
|
||||
const filteredTree = computed(() => {
|
||||
const query = searchQuery.value.trim().toLocaleLowerCase()
|
||||
if (!query) return workspaceStore.fileTree
|
||||
const filter = (nodes: FileNode[]): FileNode[] => nodes.flatMap(node => {
|
||||
if (node.name.toLocaleLowerCase().includes(query)) return [{ ...node, is_open: true }]
|
||||
const children = filter(node.children ?? [])
|
||||
return children.length ? [{ ...node, children, is_open: true }] : []
|
||||
})
|
||||
return filter(workspaceStore.fileTree)
|
||||
})
|
||||
function expandAllFiles() {
|
||||
const expand = (nodes: FileNode[]) => nodes.forEach(node => {
|
||||
if (node.type === 'folder') { node.is_open = true; expand(node.children ?? []) }
|
||||
})
|
||||
expand(workspaceStore.fileTree)
|
||||
}
|
||||
let lastScrollTop = 0
|
||||
function revealSearch(event: WheelEvent) {
|
||||
if (activeTab.value !== 'files') return
|
||||
if (event.deltaY < 0) searchVisible.value = true
|
||||
else if (event.deltaY > 0 && !searchFocused.value && !searchQuery.value) searchVisible.value = false
|
||||
}
|
||||
function onTreeScroll(event: Event) {
|
||||
const top = (event.target as HTMLElement).scrollTop
|
||||
if (top < lastScrollTop) searchVisible.value = true
|
||||
else if (top > lastScrollTop && !searchFocused.value && !searchQuery.value) searchVisible.value = false
|
||||
lastScrollTop = top
|
||||
closeContextMenu()
|
||||
}
|
||||
|
||||
watch(() => workspaceStore.activeFilePath, (path) => {
|
||||
if (!path) return
|
||||
@@ -30,14 +95,23 @@ watch(() => workspaceStore.activeFilePath, (path) => {
|
||||
})
|
||||
|
||||
function beginCreate(type: 'file' | 'folder', parent = '/') {
|
||||
if (creating.value) return
|
||||
closeContextMenu()
|
||||
createError.value = ''
|
||||
newItemType.value = type
|
||||
newItemName.value = ''
|
||||
parentPath.value = parent
|
||||
void nextTick(() => createInput.value?.focus())
|
||||
}
|
||||
|
||||
async function createItem() {
|
||||
const rawName = newItemName.value.trim()
|
||||
if (!rawName || !newItemType.value) return
|
||||
if (creating.value) return
|
||||
if (/[\\/]/.test(rawName) || ['.', '..'].includes(rawName)) { createError.value = t('请输入有效名称,不要包含路径分隔符', 'Enter a name without path separators'); return }
|
||||
creating.value = true
|
||||
createError.value = ''
|
||||
try {
|
||||
if (newItemType.value === 'file') {
|
||||
const name = rawName.endsWith('.md') ? rawName : `${rawName}.md`
|
||||
const file = await workspaceService.createFile(parentPath.value, name, `# ${rawName}\n\n`)
|
||||
@@ -55,6 +129,8 @@ async function createItem() {
|
||||
}
|
||||
newItemType.value = null
|
||||
newItemName.value = ''
|
||||
} catch (error) { createError.value = error instanceof Error ? error.message : t('创建失败', 'Creation failed') }
|
||||
finally { creating.value = false }
|
||||
}
|
||||
|
||||
async function openNode(node: FileNode) {
|
||||
@@ -84,7 +160,7 @@ function openContextMenu(event: MouseEvent, node: FileNode) {
|
||||
selectedTreePath.value = node.path
|
||||
selectedFolderPath.value = node.type === 'folder' ? node.path : containingFolder(node.path)
|
||||
contextTarget.value = node
|
||||
contextMenuPosition.value = { x: event.clientX, y: event.clientY }
|
||||
contextMenuPosition.value = { x: Math.max(8, Math.min(event.clientX, window.innerWidth - 170)), y: Math.max(8, Math.min(event.clientY, window.innerHeight - 170)) }
|
||||
}
|
||||
|
||||
function closeContextMenu() { contextTarget.value = null }
|
||||
@@ -136,38 +212,106 @@ function containingFolder(path: string): string {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="file-tree-panel" @click="closeContextMenu">
|
||||
<section class="file-tree-panel" @click="closeContextMenu" @keydown.esc="closeContextMenu" @wheel.passive="revealSearch">
|
||||
<div class="workspace-tabs" role="tablist" :aria-label="t('工作区导航', 'Workspace navigation')" @keydown="navigateTabs">
|
||||
<button id="workspace-files-tab" role="tab" aria-controls="workspace-files-panel" :aria-selected="activeTab === 'files'" :tabindex="activeTab === 'files' ? 0 : -1" @click="switchTab('files')">{{ t('文件', 'Files') }}</button>
|
||||
<button id="workspace-outline-tab" role="tab" aria-controls="workspace-outline-panel" :aria-selected="activeTab === 'outline'" :tabindex="activeTab === 'outline' ? 0 : -1" @click="switchTab('outline')">{{ t('大纲', 'Outline') }}</button>
|
||||
</div>
|
||||
<div v-show="activeTab === 'files'" id="workspace-files-panel" class="files-panel" role="tabpanel" aria-labelledby="workspace-files-tab">
|
||||
<div class="toolbar">
|
||||
<button type="button" :title="t('新建笔记', 'New note')" :aria-label="t('新建笔记', 'New note')" @click.stop="beginCreate('file', selectedFolderPath)"><AppIcon :icon="DocumentAdd" /></button>
|
||||
<button type="button" :title="t('新建文件夹', 'New folder')" :aria-label="t('新建文件夹', 'New folder')" @click.stop="beginCreate('folder', selectedFolderPath)"><AppIcon :icon="FolderAdd" /></button>
|
||||
<button type="button" :aria-label="t('搜索文件', 'Search files')" :aria-expanded="searchVisible" @click="searchVisible = !searchVisible">{{ t('搜索', 'Search') }}</button>
|
||||
<button type="button" :aria-label="t('全部展开文件夹', 'Expand all folders')" @click="expandAllFiles">{{ t('全部展开', 'Expand all') }}</button>
|
||||
</div>
|
||||
<div v-if="searchVisible || searchQuery || searchFocused" class="file-search">
|
||||
<input v-model="searchQuery" type="search" :placeholder="t('搜索文件或文件夹…', 'Search files or folders…')" :aria-label="t('搜索文件或文件夹', 'Search files or folders')" @focus="searchFocused = true" @blur="searchFocused = false" />
|
||||
</div>
|
||||
<form v-if="newItemType" class="new-item" @submit.prevent="createItem">
|
||||
<input v-model="newItemName" :placeholder="newItemType === 'file' ? t('笔记名称', 'Note name') : t('文件夹名称', 'Folder name')" autofocus />
|
||||
<button type="submit">{{ t('创建', 'Create') }}</button>
|
||||
<button type="button" @click="newItemType = null">{{ t('取消', 'Cancel') }}</button>
|
||||
<input ref="createInput" v-model="newItemName" :disabled="creating" :placeholder="newItemType === 'file' ? t('笔记名称', 'Note name') : t('文件夹名称', 'Folder name')" />
|
||||
<button type="submit" :disabled="creating">{{ t('创建', 'Create') }}</button>
|
||||
<button type="button" :disabled="creating" @click="newItemType = null">{{ t('取消', 'Cancel') }}</button>
|
||||
</form>
|
||||
<div class="tree">
|
||||
<FileTreeNode v-for="node in workspaceStore.fileTree" :key="node.id" :node="node"
|
||||
<p v-if="createError" class="create-error" role="alert">{{ createError }}</p>
|
||||
<div class="tree" @scroll.passive="onTreeScroll" @contextmenu.self="openContextMenu($event, { id: 'root', name: '/', path: '/', type: 'folder' })">
|
||||
<FileTreeNode v-for="node in filteredTree" :key="node.id" :node="node"
|
||||
:active-path="selectedTreePath" @open="openNode" @context-menu="openContextMenu" />
|
||||
<p v-if="searchQuery && !filteredTree.length" class="subtle">{{ t('没有匹配的文件', 'No matching files') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div v-show="activeTab === 'outline'" id="workspace-outline-panel" class="outline-panel" role="tabpanel" aria-labelledby="workspace-outline-tab">
|
||||
<div class="outline-document">
|
||||
<span class="outline-document-icon"><AppIcon :icon="Document" :size="18" /></span>
|
||||
<div class="outline-document-info">
|
||||
<p class="outline-filename" :title="editorStore.currentFilePath ?? ''">{{ editorStore.currentFilePath?.split('/').pop() ?? t('未打开笔记', 'No note open') }}</p>
|
||||
<span class="outline-meta">{{ t('文档目录', 'Contents') }} · {{ outline.length }} {{ t('个标题', 'headings') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="outline.length" class="outline-controls">
|
||||
<span>{{ t('目录', 'Contents') }}</span>
|
||||
<button :title="t('展开全部标题', 'Expand all headings')" @click="collapsedHeadings = new Set()">{{ t('全部展开', 'Expand all') }}</button>
|
||||
</div>
|
||||
<nav class="outline-list" :aria-label="t('当前笔记大纲', 'Current note outline')">
|
||||
<div v-for="heading in visibleHeadings" :key="heading.index" class="outline-row" :class="{ 'is-selected': editorStore.headingRequest?.path === editorStore.currentFilePath && editorStore.headingRequest?.index === heading.index, 'is-nested': heading.level > 1 }" :style="{ marginLeft: `${(heading.level - 1) * 10}px` }">
|
||||
<button v-if="hasChildren(heading.index)" class="outline-toggle" :aria-label="t('折叠或展开标题', 'Toggle heading')" :aria-expanded="!collapsedHeadings.has(heading.index)" @click="toggleHeading(heading.index)"><AppIcon :icon="ArrowRight" :size="10" /></button>
|
||||
<span v-else class="outline-spacer" />
|
||||
<button class="outline-title" :title="heading.title" :aria-current="editorStore.headingRequest?.path === editorStore.currentFilePath && editorStore.headingRequest?.index === heading.index ? 'location' : undefined" @click="editorStore.jumpToHeading(heading.index, heading.offset)"><span class="outline-text">{{ heading.title }}</span><span class="outline-level" aria-hidden="true">H{{ heading.level }}</span></button>
|
||||
</div>
|
||||
<div v-if="!outline.length" class="outline-empty"><AppIcon :icon="Document" :size="28" /><strong>{{ t('还没有目录', 'No outline yet') }}</strong><p>{{ t('在笔记中添加标题,即可在这里浏览和跳转。', 'Add headings to your note to navigate here.') }}</p></div>
|
||||
</nav>
|
||||
</div>
|
||||
<Teleport to="body">
|
||||
<div v-if="contextTarget" class="context-menu"
|
||||
:style="{ left: `${contextMenuPosition.x}px`, top: `${contextMenuPosition.y}px` }" @click.stop>
|
||||
<button @click="renameTarget">{{ t('重命名', 'Rename') }}</button>
|
||||
<button class="danger" @click="deleteTarget">{{ t('删除', 'Delete') }}</button>
|
||||
<button @click="beginCreate('file', selectedFolderPath)">{{ t('新建文件', 'New file') }}</button>
|
||||
<button @click="beginCreate('folder', selectedFolderPath)">{{ t('新建文件夹', 'New folder') }}</button>
|
||||
<button v-if="contextTarget.path !== '/'" @click="renameTarget">{{ t('重命名', 'Rename') }}</button>
|
||||
<button v-if="contextTarget.path !== '/'" class="danger" @click="deleteTarget">{{ t('删除', 'Delete') }}</button>
|
||||
</div>
|
||||
</Teleport>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.file-tree-panel { height: 100%; }
|
||||
.file-tree-panel { height: 100%; min-height: 0; display: flex; flex-direction: column; background: var(--color-surface-secondary); color: var(--color-text-primary); }
|
||||
.workspace-tabs { display: flex; flex-shrink: 0; gap: 4px; padding: 8px; border-bottom: 1px solid var(--color-border-default); background: var(--color-background-secondary); }
|
||||
.workspace-tabs button { flex: 1; min-height: 34px; font-weight: 600; color: var(--color-text-secondary); }
|
||||
.workspace-tabs button[aria-selected="true"] { background: var(--color-accent-soft); color: var(--color-accent-primary); box-shadow: inset 0 -2px var(--color-accent-primary); }
|
||||
.files-panel { display: flex; flex: 1; min-height: 0; flex-direction: column; }
|
||||
.file-tree-panel button:focus-visible, .context-menu button:focus-visible { outline: 2px solid var(--color-border-focus); outline-offset: -2px; }
|
||||
.file-search { padding: 8px; }
|
||||
.file-search input { width: 100%; box-sizing: border-box; padding: 6px 8px; border: 1px solid var(--color-border-default); border-radius: var(--radius-sm); background: var(--color-surface-primary); color: var(--color-text-primary); }
|
||||
.create-error { padding: 8px; color: var(--color-error); }
|
||||
.outline-panel { flex: 1; min-height: 0; overflow: auto; }
|
||||
.outline-document { display: flex; align-items: center; gap: 10px; margin: 12px 10px; padding: 12px 10px; border: 1px solid var(--color-border-subtle); border-radius: var(--radius-md); background: var(--color-surface-primary); box-shadow: var(--shadow-sm); }
|
||||
.outline-document-icon { display: grid; place-items: center; flex-shrink: 0; width: 32px; height: 36px; border-radius: var(--radius-sm); background: var(--color-accent-soft); color: var(--color-accent-primary); }
|
||||
.outline-document-info { min-width: 0; }
|
||||
.outline-filename { margin: 0 0 4px; padding: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--color-text-primary); font-size: var(--font-size-sm); font-weight: 600; border: 0; }
|
||||
.outline-meta { font-size: var(--font-size-xs); color: var(--color-text-secondary); }
|
||||
.outline-controls { display: flex; align-items: center; justify-content: space-between; padding: 4px 12px 8px; color: var(--color-text-secondary); font-size: var(--font-size-xs); }
|
||||
.outline-controls button { color: var(--color-accent-primary); font-size: inherit; }
|
||||
.outline-list { padding: 0 10px 16px; }
|
||||
.outline-row { position: relative; display: flex; align-items: center; min-height: 34px; margin-bottom: 2px; padding: 0 6px 0 2px; border: 1px solid transparent; border-radius: var(--radius-sm); transition: background-color var(--motion-fast); }
|
||||
.outline-row:hover { background: var(--color-background-hover); }
|
||||
.outline-row.is-selected { background: var(--color-accent-soft); box-shadow: inset 2px 0 var(--color-accent-primary); }
|
||||
.outline-spacer, .outline-toggle { width: 18px; flex-shrink: 0; }
|
||||
.outline-row .outline-toggle { display: grid; place-items: center; padding: 4px 0; color: var(--color-text-secondary); }
|
||||
.outline-toggle[aria-expanded="true"] :deep(svg) { transform: rotate(90deg); }
|
||||
.outline-row .outline-title { display: flex; align-items: center; gap: 8px; flex: 1; min-width: 0; padding: 6px 2px; text-align: left; background: transparent; }
|
||||
.outline-level { flex-shrink: 0; color: var(--color-text-tertiary); font: 400 10px/18px var(--font-ui-mono); }
|
||||
.outline-text { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: var(--font-size-sm); line-height: 20px; }
|
||||
.is-selected .outline-text { color: var(--color-accent-primary); font-weight: 600; }
|
||||
.is-selected .outline-level { color: var(--color-accent-primary); }
|
||||
.outline-empty { display: grid; justify-items: center; gap: 10px; padding: 32px 16px; text-align: center; color: var(--color-text-secondary); }
|
||||
.outline-empty strong { color: var(--color-text-primary); font-size: var(--font-size-sm); }
|
||||
.outline-empty p { margin: 0; font-size: var(--font-size-xs); line-height: 1.7; }
|
||||
.toolbar { display: flex; gap: var(--space-xs); padding: var(--space-sm); border-bottom: 1px solid var(--color-border-subtle); }
|
||||
button { border: 0; border-radius: var(--radius-sm); padding: var(--space-xs) var(--space-sm); background: transparent; color: inherit; cursor: pointer; }
|
||||
button:hover { background: var(--color-background-secondary); }
|
||||
button:hover { background: var(--color-background-hover); }
|
||||
.new-item { display: flex; gap: var(--space-xs); padding: var(--space-sm); }
|
||||
.new-item input { min-width: 0; flex: 1; }
|
||||
.tree { padding: var(--space-xs); }
|
||||
.new-item input { min-width: 0; flex: 1; padding: 6px 8px; border: 1px solid var(--color-border-default); border-radius: var(--radius-sm); background: var(--color-surface-primary); color: var(--color-text-primary); }
|
||||
.file-search input:focus, .new-item input:focus { outline: 2px solid var(--color-border-focus); outline-offset: 1px; }
|
||||
.tree { padding: var(--space-xs); flex: 1; min-height: 80px; overflow: auto; }
|
||||
.context-menu { position: fixed; z-index: 1000; display: grid; min-width: 130px; padding: var(--space-xs); border: 1px solid var(--color-border-default); border-radius: var(--radius-md); background: var(--color-background-primary); box-shadow: var(--shadow-md); }
|
||||
.context-menu button { text-align: left; }
|
||||
.context-menu .danger { color: var(--color-error); }
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { expect, it } from 'vitest'
|
||||
import { noteOutline } from './outline'
|
||||
|
||||
it('hides legacy metadata while preserving editor heading positions', () => {
|
||||
const source = '***\n\ntitle: Python\ntags: python\n---\n\n# Variables\n'
|
||||
expect(noteOutline(source)).toEqual([{ index: 0, level: 1, title: 'Variables', offset: source.indexOf('# Variables') }])
|
||||
})
|
||||
|
||||
it('keeps duplicate headings distinct and skips code fences', () => {
|
||||
const source = '# Same\n\n```md\n# Not a heading\n```\n\n## Same\n\nSetext\n---\n'
|
||||
expect(noteOutline(source).map(h => [h.index, h.level, h.title, source.slice(h.offset, h.offset + 2)])).toEqual([
|
||||
[0, 1, 'Same', '# '], [1, 2, 'Same', '##'], [2, 2, 'Setext', 'Se'],
|
||||
])
|
||||
})
|
||||
@@ -0,0 +1,20 @@
|
||||
import { marked } from 'marked'
|
||||
import { splitNoteMetadata } from '../editor/noteMetadata'
|
||||
|
||||
export interface OutlineHeading { index: number; level: number; title: string; offset: number }
|
||||
|
||||
export function noteOutline(source: string): OutlineHeading[] {
|
||||
const headings: OutlineHeading[] = []
|
||||
const metadata = splitNoteMetadata(source)
|
||||
let offset = metadata?.prefix.length ?? 0
|
||||
let headingIndex = 0
|
||||
for (const token of marked.lexer(metadata?.body ?? source)) {
|
||||
const start = source.indexOf(token.raw, offset)
|
||||
if (token.type === 'heading') {
|
||||
const index = headingIndex++
|
||||
headings.push({ index, level: token.depth, title: token.text.replace(/[*_`]/g, ''), offset: Math.max(0, start) })
|
||||
}
|
||||
if (start >= 0) offset = start + token.raw.length
|
||||
}
|
||||
return headings
|
||||
}
|
||||
@@ -1,31 +1,45 @@
|
||||
import mermaid from 'mermaid'
|
||||
import { ref, watch } from 'vue'
|
||||
import { computed } from 'vue'
|
||||
import { useThemeStore } from '@/stores/theme'
|
||||
|
||||
let initialized = false
|
||||
let initTheme: 'light' | 'dark' = 'light'
|
||||
export function mermaidThemeVariables(dark: boolean) {
|
||||
const style = typeof document === 'undefined' ? null : getComputedStyle(document.documentElement)
|
||||
const color = (name: string, fallback: string) => style?.getPropertyValue(`--color-${name}`).trim() || fallback
|
||||
const text = color('text-primary', dark ? '#e6edf3' : '#1f2328')
|
||||
const border = color('border-default', dark ? '#484f58' : '#d0d7de')
|
||||
const surface = color('surface-primary', dark ? '#161b22' : '#ffffff')
|
||||
const primary = color('accent-soft', dark ? '#30363d' : '#eef0ff')
|
||||
const line = color('text-secondary', dark ? '#b1bac4' : '#656d76')
|
||||
return {
|
||||
darkMode: dark, background: surface, primaryColor: primary, primaryTextColor: text, primaryBorderColor: border,
|
||||
secondaryColor: color('info-soft', primary), secondaryTextColor: text, secondaryBorderColor: border,
|
||||
tertiaryColor: color('success-soft', primary), tertiaryTextColor: text, tertiaryBorderColor: border,
|
||||
textColor: text, lineColor: line, mainBkg: primary, nodeBorder: border,
|
||||
clusterBkg: surface, clusterBorder: border, edgeLabelBackground: surface,
|
||||
actorBkg: primary, actorBorder: border, actorTextColor: text, actorLineColor: line,
|
||||
signalColor: line, signalTextColor: text, labelBoxBkgColor: surface, labelBoxBorderColor: border, labelTextColor: text,
|
||||
noteBkgColor: color('warning-soft', primary), noteTextColor: text, noteBorderColor: border,
|
||||
activationBkgColor: primary, activationBorderColor: border,
|
||||
}
|
||||
}
|
||||
|
||||
function ensureInitialized(theme: 'light' | 'dark') {
|
||||
if (!initialized) {
|
||||
mermaid.initialize({
|
||||
startOnLoad: false,
|
||||
theme: theme === 'dark' ? 'dark' : 'default',
|
||||
theme: 'base',
|
||||
themeVariables: mermaidThemeVariables(theme === 'dark'),
|
||||
securityLevel: 'strict',
|
||||
fontFamily: 'var(--font-ui-sans)',
|
||||
flowchart: { useMaxWidth: true, htmlLabels: true },
|
||||
sequence: { useMaxWidth: true },
|
||||
gantt: { useMaxWidth: true },
|
||||
})
|
||||
initialized = true
|
||||
initTheme = theme
|
||||
return
|
||||
}
|
||||
if (initTheme !== theme) {
|
||||
mermaid.initialize({
|
||||
theme: theme === 'dark' ? 'dark' : 'default',
|
||||
})
|
||||
initTheme = theme
|
||||
}
|
||||
}
|
||||
let queue: Promise<unknown> = Promise.resolve()
|
||||
function serialized<T>(work: () => Promise<T>): Promise<T> {
|
||||
const result = queue.then(work)
|
||||
queue = result.catch(() => {})
|
||||
return result
|
||||
}
|
||||
|
||||
export interface MermaidRenderResult {
|
||||
@@ -43,7 +57,11 @@ export interface MermaidParseError {
|
||||
|
||||
let renderCounter = 0
|
||||
|
||||
export async function renderMermaid(
|
||||
export function renderMermaid(source: string, options: { theme?: 'light' | 'dark'; mode?: 'interactive' | 'static' } = {}): Promise<MermaidRenderResult> {
|
||||
return serialized(() => renderMermaidNow(source, options))
|
||||
}
|
||||
|
||||
async function renderMermaidNow(
|
||||
source: string,
|
||||
options: { theme?: 'light' | 'dark'; mode?: 'interactive' | 'static' } = {}
|
||||
): Promise<MermaidRenderResult> {
|
||||
@@ -106,18 +124,14 @@ function escapeXml(str: string): string {
|
||||
|
||||
export function useMermaidTheme() {
|
||||
const themeStore = useThemeStore()
|
||||
const mermaidTheme = ref<'light' | 'dark'>(themeStore.isDark ? 'dark' : 'light')
|
||||
watch(() => themeStore.isDark, (isDark) => {
|
||||
mermaidTheme.value = isDark ? 'dark' : 'light'
|
||||
ensureInitialized(mermaidTheme.value)
|
||||
})
|
||||
return { mermaidTheme }
|
||||
const mermaidTheme = computed<'light' | 'dark'>(() => themeStore.isDark ? 'dark' : 'light')
|
||||
const themeId = computed(() => themeStore.currentThemeId)
|
||||
return { mermaidTheme, themeId }
|
||||
}
|
||||
|
||||
export async function validateMermaid(source: string): Promise<{ valid: boolean; error?: MermaidParseError }> {
|
||||
try {
|
||||
ensureInitialized('light')
|
||||
await mermaid.parse(source)
|
||||
await serialized(async () => { ensureInitialized('light'); await mermaid.parse(source) })
|
||||
return { valid: true }
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : '未知错误'
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import mermaid from 'mermaid'
|
||||
import { mermaidThemeVariables, renderMermaid } from './mermaidService'
|
||||
|
||||
vi.mock('mermaid', () => ({ default: { initialize: vi.fn(), render: vi.fn().mockResolvedValue({ svg: '<svg viewBox="0 0 10 10"></svg>' }) } }))
|
||||
afterEach(() => { document.documentElement.removeAttribute('style'); vi.clearAllMocks() })
|
||||
it('uses the current theme tokens for nodes, actors, text and lines', () => {
|
||||
document.documentElement.style.setProperty('--color-accent-soft', '#f3e1d8')
|
||||
document.documentElement.style.setProperty('--color-text-primary', '#493f35')
|
||||
const theme = mermaidThemeVariables(false)
|
||||
expect(theme.primaryColor).toBe('#f3e1d8')
|
||||
expect(theme.actorBkg).toBe('#f3e1d8')
|
||||
expect(theme.primaryTextColor).toBe('#493f35')
|
||||
expect(theme.actorTextColor).toBe('#493f35')
|
||||
})
|
||||
it('keeps explicit diagram styling and initializes base palette on each render', async () => {
|
||||
const source = 'graph TD; A-->B; style A fill:#f9f'
|
||||
await renderMermaid(source)
|
||||
expect(mermaid.initialize).toHaveBeenCalledWith(expect.objectContaining({ theme: 'base', securityLevel: 'strict', themeVariables: expect.any(Object) }))
|
||||
expect(mermaid.render).toHaveBeenCalledWith(expect.any(String), source)
|
||||
})
|
||||
@@ -0,0 +1,34 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { strToU8, zipSync } from 'fflate'
|
||||
import { decodeThemePackage, fetchThemePackage, inspectThemePackage, MAX_THEME_BYTES } from './themePackageService'
|
||||
import paper from '@/assets/themes/paper-moments.theme?raw'
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
it('reads ZIP manifests under repository folders and validates the bundled CSS', async () => {
|
||||
const [yaml, css] = paper.split('\n---\n')
|
||||
const zip = zipSync({ 'repo-main/theme.yaml': strToU8(yaml!), 'repo-main/theme.css': strToU8(css!) })
|
||||
const result = await inspectThemePackage(await decodeThemePackage(zip))
|
||||
expect(result.compatible).toBe(true)
|
||||
expect(result.css).toBe(css!.trim())
|
||||
})
|
||||
it('accepts a zipped single-file theme', async () => {
|
||||
expect(await decodeThemePackage(zipSync({ 'paper.theme': strToU8(paper) }))).toBe(paper)
|
||||
})
|
||||
it('rejects unsafe paths, ambiguous manifests and oversized input', async () => {
|
||||
await expect(decodeThemePackage(zipSync({ '../paper.theme': strToU8(paper) }))).rejects.toThrow('非法')
|
||||
await expect(decodeThemePackage(zipSync({ 'theme.yaml': strToU8(paper), 'manifest.yml': strToU8(paper) }))).rejects.toThrow('多个')
|
||||
await expect(decodeThemePackage(new Uint8Array(MAX_THEME_BYTES + 1))).rejects.toThrow('5 MB')
|
||||
})
|
||||
it('uses the same ZIP parser for URL downloads without sending credentials', async () => {
|
||||
const fetcher = vi.fn().mockResolvedValue(new Response(zipSync({ 'paper.theme': strToU8(paper) })))
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
expect(await fetchThemePackage('https://example.com/theme.zip')).toBe(paper)
|
||||
expect(fetcher).toHaveBeenCalledWith('https://example.com/theme.zip', expect.objectContaining({ credentials: 'omit' }))
|
||||
await expect(fetchThemePackage('file:///theme.zip')).rejects.toThrow('HTTP(S)')
|
||||
})
|
||||
it('reports HTTP and streaming size failures', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValueOnce(new Response('', { status: 404 })).mockResolvedValueOnce(new Response(new Uint8Array(MAX_THEME_BYTES + 1))))
|
||||
await expect(fetchThemePackage('https://example.com/theme')).rejects.toThrow('404')
|
||||
await expect(fetchThemePackage('https://example.com/theme')).rejects.toThrow('5 MB')
|
||||
})
|
||||
@@ -1,7 +1,83 @@
|
||||
import type { InstalledTheme, ThemeManifest, ThemePackageInspection } from '@/contracts'
|
||||
import paperMomentsPackage from '@/assets/themes/paper-moments.theme?raw'
|
||||
|
||||
const STORAGE_KEY = 'installed-themes'
|
||||
const ACTIVE_CUSTOM_KEY = 'active-custom-theme'
|
||||
export const MAX_THEME_BYTES = 5 * 1024 * 1024
|
||||
|
||||
/** Normalize all transports to the existing single-file inspection format. */
|
||||
export async function decodeThemePackage(bytes: Uint8Array): Promise<string> {
|
||||
if (bytes.length > MAX_THEME_BYTES) throw new Error('主题包不能超过 5 MB')
|
||||
const decode = (data: Uint8Array) => new TextDecoder('utf-8', { fatal: true }).decode(data)
|
||||
if (bytes[0] !== 0x50 || bytes[1] !== 0x4b) return decode(bytes)
|
||||
const { unzipSync } = await import('fflate')
|
||||
let total = 0
|
||||
let count = 0
|
||||
const names = new Set<string>()
|
||||
const safePath = (path: string) => path.length > 0 && !path.startsWith('/') && !path.includes('\\') && !path.includes(':') && !path.split('/').some(part => part === '..' || part === '.')
|
||||
const files = unzipSync(bytes, { filter: file => {
|
||||
if (!safePath(file.name) || names.has(file.name)) throw new Error('ZIP 包含非法或重复路径')
|
||||
names.add(file.name)
|
||||
total += file.originalSize
|
||||
if (++count > 100 || total > 10 * 1024 * 1024) throw new Error('ZIP 解压内容不能超过 10 MB 或 100 个文件')
|
||||
return !file.name.endsWith('/')
|
||||
} })
|
||||
const entries = Object.keys(files)
|
||||
const manifests = entries.filter(name => /(^|\/)(theme|manifest)\.ya?ml$/i.test(name))
|
||||
if (!manifests.length) {
|
||||
const single = entries.filter(name => name.endsWith('.theme'))
|
||||
if (single.length !== 1) throw new Error('ZIP 需要唯一的 theme.yaml / manifest.yaml,或一个 .theme 文件')
|
||||
return decode(files[single[0]!]!)
|
||||
}
|
||||
if (manifests.length !== 1) throw new Error('ZIP 中存在多个主题清单,请每包只放一个主题')
|
||||
const manifestPath = manifests[0]!
|
||||
const yaml = decode(files[manifestPath]!)
|
||||
const manifest = inspectYamlContent(yaml)
|
||||
if (!safePath(manifest.css_entry)) throw new Error('css_entry 必须是包内相对路径')
|
||||
const base = manifestPath.slice(0, manifestPath.lastIndexOf('/') + 1)
|
||||
const css = files[base + manifest.css_entry]
|
||||
if (!css) throw new Error(`ZIP 中找不到 CSS 文件:${manifest.css_entry}`)
|
||||
return `${yaml}\n---\n${decode(css)}`
|
||||
}
|
||||
|
||||
export async function fetchThemePackage(urlText: string, signal?: AbortSignal): Promise<string> {
|
||||
const url = new URL(urlText.trim())
|
||||
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw new Error('请输入不含账号密码的 HTTP(S) 主题包直链')
|
||||
const controller = new AbortController()
|
||||
const abort = () => controller.abort()
|
||||
signal?.addEventListener('abort', abort, { once: true })
|
||||
if (signal?.aborted) abort()
|
||||
const timeout = setTimeout(abort, 30000)
|
||||
try {
|
||||
const response = await fetch(url.href, { signal: controller.signal, credentials: 'omit', referrerPolicy: 'no-referrer' })
|
||||
if (!response.ok) throw new Error(`下载失败:HTTP ${response.status}`)
|
||||
if (Number(response.headers.get('content-length')) > MAX_THEME_BYTES) throw new Error('主题包不能超过 5 MB')
|
||||
if (!response.body) throw new Error('下载内容为空')
|
||||
const reader = response.body.getReader()
|
||||
const chunks: Uint8Array[] = []
|
||||
let size = 0
|
||||
try {
|
||||
while (true) {
|
||||
const { value, done } = await reader.read()
|
||||
if (done) break
|
||||
size += value.length
|
||||
if (size > MAX_THEME_BYTES) throw new Error('主题包不能超过 5 MB')
|
||||
chunks.push(value)
|
||||
}
|
||||
} finally { await reader.cancel() }
|
||||
const bytes = new Uint8Array(size)
|
||||
let offset = 0
|
||||
for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.length }
|
||||
return await decodeThemePackage(bytes)
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted) throw new Error('下载已取消或超时,请重试')
|
||||
if (error instanceof TypeError) throw new Error('无法下载,请检查直链及服务器是否允许跨域访问(CORS)')
|
||||
throw error
|
||||
} finally {
|
||||
clearTimeout(timeout)
|
||||
signal?.removeEventListener('abort', abort)
|
||||
}
|
||||
}
|
||||
|
||||
function loadStoredThemes(): InstalledTheme[] {
|
||||
try {
|
||||
@@ -113,8 +189,7 @@ function inspectYamlContent(yamlText: string): ThemeManifest {
|
||||
* ---
|
||||
* [data-theme="my-theme"] { --color-... }
|
||||
*
|
||||
* 浏览器端没有解压能力,所以不支持 ZIP —— 与其把二进制当文本解析出
|
||||
* 一堆乱码再报「清单无效」,不如直接告诉用户格式不支持。
|
||||
* ZIP 必须先通过 decodeThemePackage 解码;此函数只处理规范化后的文本。
|
||||
*/
|
||||
export function parseThemePackage(packageData: string): { manifestText: string; css: string } {
|
||||
if (looksLikeZip(packageData)) {
|
||||
@@ -146,19 +221,19 @@ function looksLikeZip(data: string): boolean {
|
||||
}
|
||||
|
||||
export async function selectThemePackage(): Promise<string | null> {
|
||||
return new Promise((resolve) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const input = document.createElement('input')
|
||||
input.type = 'file'
|
||||
// 只接受能在浏览器里解析的单文件主题;ZIP 需要 Host 端解压,暂不支持。
|
||||
input.accept = '.yaml,.yml,.theme'
|
||||
input.accept = '.yaml,.yml,.theme,.zip'
|
||||
input.multiple = false
|
||||
input.onchange = () => {
|
||||
const file = input.files?.[0]
|
||||
if (!file) { resolve(null); return }
|
||||
if (file.size > MAX_THEME_BYTES) { reject(new Error('主题包不能超过 5 MB')); return }
|
||||
const reader = new FileReader()
|
||||
reader.onload = () => resolve(reader.result as string)
|
||||
reader.onload = () => { void decodeThemePackage(new Uint8Array(reader.result as ArrayBuffer)).then(resolve, reject) }
|
||||
reader.onerror = () => resolve(null)
|
||||
reader.readAsText(file)
|
||||
reader.readAsArrayBuffer(file)
|
||||
}
|
||||
input.oncancel = () => resolve(null)
|
||||
input.click()
|
||||
@@ -280,7 +355,10 @@ export function setActiveCustomTheme(themeId: string | null) {
|
||||
else localStorage.removeItem(ACTIVE_CUSTOM_KEY)
|
||||
}
|
||||
|
||||
const paperMoments = parseThemePackage(paperMomentsPackage)
|
||||
|
||||
export const mockCommunityThemes: ThemeManifest[] = [
|
||||
{ ...inspectYamlContent(paperMoments.manifestText), tags: ['浅色', '手帐', '纸张'] },
|
||||
{
|
||||
theme_id: 'ocean-blue',
|
||||
name: 'Ocean Blue',
|
||||
@@ -293,18 +371,6 @@ export const mockCommunityThemes: ThemeManifest[] = [
|
||||
tags: ['浅色', '蓝色', '阅读'],
|
||||
license: 'MIT',
|
||||
},
|
||||
{
|
||||
theme_id: 'forest-green',
|
||||
name: 'Forest Green',
|
||||
version: '1.0.1',
|
||||
author: 'nature-collection',
|
||||
description: '森林绿色护眼主题',
|
||||
min_app_version: '0.2.0',
|
||||
is_dark: false,
|
||||
css_entry: 'theme.css',
|
||||
tags: ['浅色', '绿色', '护眼'],
|
||||
license: 'MIT',
|
||||
},
|
||||
{
|
||||
theme_id: 'midnight-purple',
|
||||
name: 'Midnight Purple',
|
||||
@@ -317,39 +383,12 @@ export const mockCommunityThemes: ThemeManifest[] = [
|
||||
tags: ['深色', '紫色', '极客'],
|
||||
license: 'Apache-2.0',
|
||||
},
|
||||
{
|
||||
theme_id: 'solarized-light',
|
||||
name: 'Solarized Light',
|
||||
version: '1.1.0',
|
||||
author: 'solarized',
|
||||
description: '经典 Solarized 浅色主题',
|
||||
min_app_version: '0.1.0',
|
||||
is_dark: false,
|
||||
css_entry: 'theme.css',
|
||||
tags: ['浅色', '经典', '阅读'],
|
||||
license: 'MIT',
|
||||
},
|
||||
{
|
||||
theme_id: 'dracula',
|
||||
name: 'Dracula',
|
||||
version: '3.0.0',
|
||||
author: 'dracula-theme',
|
||||
description: '流行的 Dracula 暗色主题',
|
||||
min_app_version: '0.2.0',
|
||||
is_dark: true,
|
||||
css_entry: 'theme.css',
|
||||
tags: ['深色', '紫色', '高对比'],
|
||||
license: 'MIT',
|
||||
},
|
||||
]
|
||||
|
||||
function buildCommunityThemeCss(themeId: string, isDark: boolean, accent: string): string {
|
||||
function buildCommunityThemeCss(themeId: string, isDark: boolean): string {
|
||||
const palettes: Record<string, { primary: string; soft: string; hover: string }> = {
|
||||
'ocean-blue': { primary: '#0077b6', soft: '#e0f0fa', hover: '#005f92' },
|
||||
'forest-green': { primary: '#2d6a4f', soft: '#e8f5ec', hover: '#1b4332' },
|
||||
'midnight-purple': { primary: '#9d4edd', soft: '#2b1a3e', hover: '#7b2cbf' },
|
||||
'solarized-light': { primary: '#b58900', soft: '#fdf6e3', hover: '#8a6d0b' },
|
||||
'dracula': { primary: '#bd93f9', soft: '#2d2a3e', hover: '#a77bf5' },
|
||||
}
|
||||
const p = palettes[themeId] ?? palettes['ocean-blue']
|
||||
if (isDark) {
|
||||
@@ -415,12 +454,13 @@ function buildCommunityThemeCss(themeId: string, isDark: boolean, accent: string
|
||||
export async function installCommunityTheme(themeId: string): Promise<InstalledTheme> {
|
||||
const themeManifest = mockCommunityThemes.find((t) => t.theme_id === themeId)
|
||||
if (!themeManifest) throw new Error('THEME_PACKAGE_NOT_FOUND')
|
||||
const css = buildCommunityThemeCss(themeId, themeManifest.is_dark, themeManifest.theme_id)
|
||||
const css = getCommunityThemePreviewCss(themeId)
|
||||
return installTheme(themeManifest, css)
|
||||
}
|
||||
|
||||
export function getCommunityThemePreviewCss(themeId: string): string {
|
||||
if (themeId === 'paper-moments') return paperMoments.css
|
||||
const t = mockCommunityThemes.find((m) => m.theme_id === themeId)
|
||||
if (!t) return ''
|
||||
return buildCommunityThemeCss(themeId, t.is_dark, themeId)
|
||||
return buildCommunityThemeCss(themeId, t.is_dark)
|
||||
}
|
||||
|
||||
@@ -50,6 +50,25 @@ afterEach(() => {
|
||||
})
|
||||
|
||||
describe('workspaceService backend adapter', () => {
|
||||
it.each([
|
||||
['tags:\n- python\n- rust', { tags: ['python', 'rust'] }],
|
||||
['tags: []', { tags: [] }],
|
||||
['tags:', { tags: [] }],
|
||||
['tags: ["a,b", rust]', { tags: ['a,b', 'rust'] }],
|
||||
['title: Demo', {}],
|
||||
['tags: [broken', {}],
|
||||
])('saves explicit metadata tags with the same Markdown snapshot: %s', async (yaml, tagPayload) => {
|
||||
const fetchMock = vi.mocked(fetch)
|
||||
fetchMock.mockImplementation(async (input) => String(input) === '/api/workspace/open'
|
||||
? jsonResponse(workspaceSnapshot) : jsonResponse({}))
|
||||
await workspaceService.openVault('C:\\data\\vault')
|
||||
const markdown = `---\n${yaml}\n---\n# Body\n`
|
||||
await workspaceService.saveFileContent('/课程/操作系统.md', markdown)
|
||||
const patchCall = fetchMock.mock.calls.find(([, init]) => init?.method === 'PATCH')
|
||||
expect(String(patchCall?.[0])).toBe('/api/notes/note-os')
|
||||
expect(JSON.parse(String(patchCall?.[1]?.body))).toEqual({ markdown, ...tagPayload })
|
||||
})
|
||||
|
||||
it('opens the configured Vault and reads/saves Markdown through Note API', async () => {
|
||||
const fetchMock = vi.mocked(fetch)
|
||||
fetchMock.mockImplementation(async (input, init) => {
|
||||
|
||||
@@ -9,6 +9,7 @@ import type {
|
||||
import apiClient from './apiClient'
|
||||
import { t } from '@/i18n'
|
||||
import * as noteService from './noteService'
|
||||
import { splitNoteMetadata } from '@/utils/noteMetadata'
|
||||
|
||||
/** Web 联调只连接 AI Core 配置的单一 Vault;多 Vault 选择由 Tauri Host 接管。 */
|
||||
export interface VaultInfo {
|
||||
@@ -122,7 +123,12 @@ export async function getNoteId(filePath: string): Promise<string> {
|
||||
}
|
||||
|
||||
export async function saveFileContent(filePath: string, content: string): Promise<void> {
|
||||
await noteService.updateNote(await requireNoteId(filePath), { markdown: content })
|
||||
const metadata = splitNoteMetadata(content)
|
||||
await noteService.updateNote(await requireNoteId(filePath), {
|
||||
markdown: content,
|
||||
// Explicit [] clears the index; absent tags retain API-managed tags.
|
||||
...(metadata?.hasTags ? { tags: metadata.tags } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
export async function createFile(
|
||||
|
||||
@@ -13,6 +13,10 @@ export const useEditorStore = defineStore('editor', () => {
|
||||
const currentFilePath = ref<string | null>(null)
|
||||
const highlightBlockId = ref<string | null>(null)
|
||||
const cursorPosition = ref({ line: 0, column: 0 })
|
||||
const headingRequest = ref<{ index: number; offset: number; path: string | null } | null>(null)
|
||||
function jumpToHeading(index: number, offset: number) {
|
||||
headingRequest.value = { index, offset, path: currentFilePath.value }
|
||||
}
|
||||
|
||||
const wordCount = computed(() => {
|
||||
const text = content.value.replace(/[#*`>\-_\[\]()!]/g, '')
|
||||
@@ -144,6 +148,8 @@ export const useEditorStore = defineStore('editor', () => {
|
||||
}
|
||||
|
||||
return {
|
||||
headingRequest,
|
||||
jumpToHeading,
|
||||
mode,
|
||||
content,
|
||||
saveStatus,
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { isMap, isScalar, isSeq, parseDocument } from 'yaml'
|
||||
|
||||
export interface NoteMetadata {
|
||||
prefix: string
|
||||
yaml: string
|
||||
body: string
|
||||
title: string
|
||||
tags: string[]
|
||||
hasTags: boolean
|
||||
}
|
||||
|
||||
function parseProperties(yaml: string) {
|
||||
const document = parseDocument(yaml)
|
||||
// Unsupported YAML stays available in source mode without partial rewriting.
|
||||
if (document.errors.length || document.warnings.length || !isMap(document.contents)) return null
|
||||
return document
|
||||
}
|
||||
|
||||
export function splitNoteMetadata(source: string): NoteMetadata | null {
|
||||
const match = source.match(/^\uFEFF?(---|\*\*\*)[ \t]*\r?\n([\s\S]*?)\r?\n(?:-{3,}|\.\.\.)[ \t]*(?:\r?\n|$)/)
|
||||
if (!match) return null
|
||||
const yaml = match[2]!
|
||||
const document = parseProperties(yaml)
|
||||
if (!document || (!document.has('title') && !document.has('tags'))) return null
|
||||
const title = document.get('title') ?? ''
|
||||
if (typeof title !== 'string') return null
|
||||
const tagNode = document.get('tags', true)
|
||||
let tags: string[] = []
|
||||
if (isSeq(tagNode)) {
|
||||
// Do not remove anchored list items that other properties may reference.
|
||||
if (!tagNode.items.every(item => isScalar(item) && typeof item.value === 'string' && !item.anchor)) return null
|
||||
tags = tagNode.items.map(item => (item as { value: string }).value)
|
||||
} else if (isScalar(tagNode)) {
|
||||
if (typeof tagNode.value === 'string') tags = tagNode.value.split(',').map(tag => tag.trim()).filter(Boolean)
|
||||
else if (tagNode.value !== null) return null
|
||||
} else if (tagNode !== undefined) return null
|
||||
return { prefix: match[0], yaml, body: source.slice(match[0].length), title, tags, hasTags: document.has('tags') }
|
||||
}
|
||||
|
||||
export function updateMetadataTags(metadata: NoteMetadata, tags: string[]): string {
|
||||
const document = parseProperties(metadata.yaml)
|
||||
if (!document) throw new Error('Invalid note metadata')
|
||||
const previous = document.get('tags', true)
|
||||
const replacement = document.createNode([...new Set(tags)])
|
||||
if (isScalar(previous) || isSeq(previous)) {
|
||||
replacement.anchor = previous.anchor
|
||||
replacement.comment = previous.comment
|
||||
replacement.commentBefore = previous.commentBefore
|
||||
}
|
||||
document.set('tags', replacement)
|
||||
const newline = metadata.prefix.includes('\r\n') ? '\r\n' : '\n'
|
||||
const prefix = `---\n${document.toString()}---\n`.replace(/\n/g, newline)
|
||||
return (metadata.prefix.startsWith('\uFEFF') ? '\uFEFF' : '') + prefix
|
||||
}
|
||||
Reference in New Issue
Block a user