AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
refactor: split API seeds and iOS editor helpers
tianma-iff39c24b96d51
diff --git a/apps/api/src/demo-seed-data.test.mjs b/apps/api/src/demo-seed-data.test.mjsnew file mode 100644index 00000000..84b8df5d--- /dev/null+++ b/apps/api/src/demo-seed-data.test.mjs@@ -0,0 +1,41 @@+import { describe, expect, test } from "bun:test";+import {+ decodeDemoAttachment,+ DEMO_SEED_ATTACHMENT_RESOURCES,+ DEMO_SEED_MEMOS,+ DEMO_SEED_NOTEBOOKS,+ DEMO_SEED_REVISIONS,+} from "./demo-seed-data.ts";++describe("demo seed catalog", () => {+ test("keeps bilingual memos attached to valid notebooks", () => {+ const notebookIds = new Set(DEMO_SEED_NOTEBOOKS.map((notebook) => notebook.id));+ const memoIds = new Set(DEMO_SEED_MEMOS.map((memo) => memo.id));++ expect(notebookIds.size).toBe(DEMO_SEED_NOTEBOOKS.length);+ expect(memoIds.size).toBe(DEMO_SEED_MEMOS.length);+ expect(memoIds.has("memo_demo_overview")).toBe(true);+ expect(memoIds.has("memo_demo_overview_en")).toBe(true);+ for (const memo of DEMO_SEED_MEMOS) {+ expect(notebookIds.has(memo.notebookId)).toBe(true);+ }+ for (const revision of DEMO_SEED_REVISIONS) {+ expect(memoIds.has(revision.memoId)).toBe(true);+ }+ });++ test("keeps every seeded resource decodable and owned by a seeded memo", () => {+ const memoIds = new Set(DEMO_SEED_MEMOS.map((memo) => memo.id));+ const resourceIds = new Set();++ for (const resource of DEMO_SEED_ATTACHMENT_RESOURCES) {+ expect(resourceIds.has(resource.id)).toBe(false);+ resourceIds.add(resource.id);+ expect(memoIds.has(resource.memoId)).toBe(true);+ const bytes = "svg" in resource+ ? new TextEncoder().encode(resource.svg)+ : decodeDemoAttachment(resource);+ expect(bytes.byteLength).toBeGreaterThan(0);+ }+ });+});diff --git a/apps/api/src/demo-seed-data.ts b/apps/api/src/demo-seed-data.tsnew file mode 100644index 00000000..21076ab8--- /dev/null+++ b/apps/api/src/demo-seed-data.ts@@ -0,0 +1,87 @@+import {+ decodeDemoAttachment,+ DEMO_ATTACHMENT_MARKDOWN_EN,+ DEMO_ATTACHMENT_MARKDOWN_ZH,+ DEMO_ATTACHMENT_RESOURCES,+} from "./demo-attachments";++export { decodeDemoAttachment };++export const DEMO_SEED_NOTEBOOKS = [+ { id: "nb_inbox", parentId: null, name: "等待分类", slug: "inbox", icon: "notebook", color: "#0f766e", sortOrder: 10 },+ { id: "nb_projects", parentId: null, name: "工作项目", slug: "work-projects", icon: "notebook", color: "#2563eb", sortOrder: 20 },+ { id: "nb_learning", parentId: null, name: "学习资料", slug: "learning-resources", icon: "notebook", color: "#7c3aed", sortOrder: 30 },+ { id: "nb_creative", parentId: null, name: "灵感创作", slug: "creative-ideas", icon: "notebook", color: "#db2777", sortOrder: 40 },+ { id: "nb_personal", parentId: null, name: "生活个人", slug: "personal-life", icon: "notebook", color: "#ea580c", sortOrder: 50 },+ { id: "nb_demo_features", parentId: "nb_projects", name: "功能演示", slug: "demo-features", icon: "notebook", color: "#0891b2", sortOrder: 21 },+ { id: "nb_demo_features_en", parentId: "nb_projects", name: "Feature Demos", slug: "feature-demos", icon: "notebook", color: "#0e7490", sortOrder: 22 },+];+export const DEMO_SEED_MEMOS_ZH = [+ {+ id: "memo_demo_overview",+ notebookId: "nb_demo_features",+ title: "🌟 欢迎使用 EdgeEver",+ tags: ["overview", "features", "demo"],+ isPinned: true,+ markdown:+ "## 🚀 开启您的 EdgeEver 笔记之旅\n\n> **EdgeEver** 是一款专为极客与创作者打造的现代开源 Serverless 个人知识库。它找回了经典的**印象笔记三栏式双视图布局**,以 Cloudflare 免费额度提供 **100% 免费**的自建云端,数据完全掌控,并原生集成 AI Agent (MCP) 接口。\n\n---\n\n### ⚡ 1. 核心产品特性对比\n\n*提示:在线模式下点击表格单元格可以直接修改文本;右键可快捷操作行列。*\n\n| 核心维度 | 传统云笔记 (如 Evernote) | 本地知识库 (如 Obsidian) | EdgeEver 极客笔记 |\n| :--- | :--- | :--- | :--- |\n| **云端托管成本** | 商业订阅高昂 ($10+/月) | 官方同步收费 ($5/月) | **100% 免费 (Cloudflare 免费额度)** |\n| **数据与隐私** | 封闭平台,导出受限 | 本地文件,同步需配置 | **完全掌控 (D1 SQLite 数据库 / R2 / WebDAV)** |\n| **编辑体验** | 富文本编辑 | 纯 Markdown | **双视图自由切换 (富文本 / Markdown 源码)** |\n| **多端支持** | 限制设备数量 | 移动端配置繁琐 | **Web / PWA / Android / macOS / iOS (审核中)** |\n| **创作者排版** | 无优化,格式易乱 | 需借助外部工具 | **微信公众号、Substack 一键富文本格式复制** |\n| **AI 原生集成** | 限制/仅特定付费版本 | 需繁琐的第三方插件 | **原生支持 MCP 协议与标准 OpenAPI** |\n\n---\n\n### 🎨 2. 沉浸式写作与排版美学\n\nEdgeEver 追求极致的创作体验,将设计美学融于字里行间:\n\n- **双视图编辑器**:点击右上角 `</>` 按钮,可在**所见即所得富文本**与 **Markdown 源码**间无缝切换,格式完全兼容。\n- **左侧可折叠大纲**:提供固定或折叠的大纲目录视图,支持点击标题平滑滚动定位,助您轻松掌控长文结构。\n- **8+ 款精致编辑器主题**:可在 **个人中心 / 设置** 中一键切换如 `WeChat Classic Green (微信经典绿)`、`Modern Mint (薄荷青)`、`minimal-emerald (极简祖母绿)` 等排版风格。\n- **自媒体一键排版复制**:专为创作者设计。点击右上角“复制到公众号”按钮,系统会自动将笔记转化为带行内样式的公众号美化格式,直接粘贴至微信公众号、Substack 或 WordPress 后台,排版与代码高亮完美保真。\n- **列表缩进与快捷操作**:支持快捷缩进列表,双击或选中文本可通过快捷键快速关联已有笔记。\n\n---\n\n### 📝 3. 模板中心与单篇导出\n\n- **可视化推荐模板库**:内置多种精美模板,点击即可弹窗预览。支持在当前笔记本中一键套用模板创建笔记,并支持一键返回列表。\n- **用户自定义模板**:您可以将常用笔记结构保存为自定义模板,实现效率翻倍。\n- **单篇便捷导出**:支持将当前笔记一键导出为标准的 `.md` Markdown 文件或排版优美的 `.pdf` 电子文档,便于独立归档与分发。\n\n---\n\n### 📊 4. 原生 Mermaid 动态图表渲染\n\n在代码块中使用 `mermaid` 标记,即可实时渲染高保真的动态逻辑图。支持多款**精致图表主题**选择,且微信复制时尺寸完美兼容:\n\n#### 1️⃣ 架构流程图 (Flowchart)\n```mermaid\nflowchart TD\n subgraph Client[\"📱 客户端生态\"]\n A[\"Web / PWA 浏览器\"]\n B[\"macOS / Android / iOS 客户端\"]\n end\n\n subgraph Backend[\"⚡ Cloudflare Serverless\"]\n C[\"Cloudflare Workers API\"]\n D[(\"D1 SQLite 数据库\")]\n E[(\"R2 资源存储\")]\n end\n\n A & B --> C\n C <--> D & E\n```\n\n#### 2️⃣ 交互时序图 (Sequence Diagram)\n```mermaid\nsequenceDiagram\n autonumber\n actor User as 用户\n participant App as 客户端 App\n participant Worker as Cloudflare Worker API\n participant D1 as D1 数据库\n\n User->>App: 编辑并保存笔记\n App->>Worker: POST /api/v1/memos (提交更改)\n Worker->>D1: 写入笔记 & 更新修订版本\n D1-->>Worker: 返回成功 (revision + 1)\n Worker-->>App: 200 OK (同步最新游标)\n App-->>User: 界面显示「已保存」\n```\n\n---\n\n### 📁 5. 多端覆盖、自动同步与剪藏\n\n- **全平台多端覆盖**:已发布 Web、Android 原生 App 以及 macOS 桌面端(支持 Apple Silicon 和 Intel Mac),iOS 客户端正在 App Store 审核中。\n- **网页裁剪器 (Web Clipper)**:已上架 Chrome, Edge 和 Firefox 插件商店,支持一键剪藏网页。\n- **微信文章一键剪藏**:在手机上直接将微信公众号文章分享至 EdgeEver App,系统将智能提取正文并保存为可编辑笔记。\n- **离线草稿与同步队列**:无网环境下自动保存本地,恢复连线后自动入队同步;支持在设置中灵活配置自动同步间隔。\n\n---\n\n### 🖼️ 6. 多媒体集成与图片前端压缩\n\n支持直接拖拽或粘贴插入图片与文件附件。本地浏览器会在上传前自动对图片进行 WebP 高保真压缩,缩减 **50% - 90%** 的体积,大幅加快加载速度并节省您的云端存储空间。\n\n\n\n---\n\n### 🤖 7. 面向 AI Agent 的原生生态\n\nEdgeEver 走在 AI 时代前沿,为 AI 协作者提供了原生支持:\n\n1. **REST API**:提供标准的 OpenAPI 接口,接口定义见 `/api/openapi.json`。\n2. **MCP (Model Context Protocol) 接口**:内置 MCP 服务端点 `/mcp`。像 Antigravity, Claude Code, Cursor 等 AI Agent 可以直接连接并安全地读写您的笔记库,实现笔记自动整理、标签归纳与双向联动。\n\n---\n\n### 🔒 8. 个人空间隔离与安全分享\n\n- **多账号与管理员中心**:支持多账号独立登录,数据物理隔离。系统提供防暴力破解的安全防护。\n- **多活跃设备管理**:个人设置中可直观查看当前账户在哪些设备登录,并可随时强制下线其他设备。\n- **可撤销的公开分享**:支持生成单独笔记的公开分享链接(列表及正文顶部可直观感知分享状态),他人无需登录即可查阅最新内容,您也可以随时关闭分享。\n\n---\n\n> 🎯 **快速探索建议**:\n> - 试试点击右上角的**微信图标**,将排版精美的富文本直接粘贴至公众号或 WordPress 后台;\n> - 试试在 **个人中心 / 设置 / 编辑器主题** 中切换您喜爱的写作风格;\n> - 按下 `Cmd/Ctrl + Shift + F` 开启 Zen 专注模式,享受无干扰的写作空间;\n> - 鼠标拖拽左侧的笔记本,体验无限层级目录的顺滑管理;\n> - 在个人中心或侧边栏点击“恢复 Demo 数据”,即可随时一键将整个演示环境恢复如初。"+ },+];+export const DEMO_SEED_REVISIONS = [+ {+ id: "rev_demo_revision_1",+ memoId: "memo_demo_overview",+ revision: 1,+ title: "🌟 欢迎使用 EdgeEver",+ markdown:+ "## 🌟 欢迎使用 EdgeEver(草稿)\n\n- 印象笔记经典三栏与自建 Serverless\n- 可视化表格与 Markdown 源码双向切换",+ },+ {+ id: "rev_demo_revision_1_en",+ memoId: "memo_demo_overview_en",+ revision: 1,+ title: "🌟 Welcome to EdgeEver",+ markdown:+ "## 🌟 Welcome to EdgeEver (Draft)\n\n- Classic Evernote 3-pane layout & Serverless self-hosted\n- Visual table editing & Markdown source toggle",+ },+];+export const DEMO_MEMO_ENGLISH = {+ memo_demo_overview: {+ title: "🌟 Welcome to EdgeEver",+ markdown:+ "## 🚀 Get Started with EdgeEver: The Geek's Knowledge Base\n\n> **EdgeEver** is a modern, open-source, serverless personal knowledge base built for geeks and creators. It restores the classic **Evernote-style three-pane layout**, while offering **100% free hosting** using Cloudflare's free tier, full data ownership, dual-view editing, and native AI Agent (MCP) integration.\n\n---\n\n### ⚡ 1. Feature Comparison\n\n*Tip: Click any cell in the table below to edit directly; right-click in editor mode to insert/delete rows or columns.*\n\n| Metric | Traditional Cloud Notes (e.g. Evernote) | Local Offline Notes (e.g. Obsidian) | EdgeEver Notes |\n| :--- | :--- | :--- | :--- |\n| **Hosting Cost** | High monthly fee ($10+/mo) | Official sync fee ($5/mo) | **100% Free (Cloudflare Free Tier)** |\n| **Data & Privacy** | Closed platform, locked export | Local files, sync needs setup | **Full Ownership (D1 SQLite, R2, WebDAV)** |\n| **Editing Mode** | Rich Text | Pure Markdown | **Seamless Dual-View Toggle (Rich Text / MD)** |\n| **Device Sync** | Limits active devices | Complicated mobile setup | **Web / PWA / Android / macOS / iOS (In Review)** |\n| **For Creators** | No formatting optimizations | Requires 3rd-party tools | **One-Click Rich Copy for WeChat & Substack** |\n| **AI Integration**| Paid/Limited versions only | Requires heavy plugin config | **Native MCP Protocol & Standard OpenAPI** |\n\n---\n\n### 🎨 2. Immersive Writing & Typography Aesthetics\n\nEdgeEver is crafted to provide a distraction-free and beautiful writing experience:\n\n- **Seamless Dual-View Editor**: Click the `</>` button in the top right to switch effortlessly between **WYSIWYG Rich Text** and **Markdown Source Code** with 100% compatibility.\n- **Collapsible Outline View**: Enjoy a fixed or collapsible sidebar outline of your document headings. Click any heading to navigate smoothly.\n- **8+ Exquisite Editor Themes**: Change your writing vibe instantly in **User Settings / Profile** with preset themes such as `WeChat Classic Green`, `Modern Mint`, `minimal-emerald`, and more.\n- **One-Click Publishing Export**: Built for publishers. Click \"Copy for WeChat / Publishing\" to automatically format your note with inline CSS. Paste it directly into WeChat, Substack, Medium, or WordPress editor while preserving layout and syntax highlighting.\n- **List Indentation & Quick Link**: Use quick keys for list indents, and double-click or select text to quickly link to existing notes with shortcut hints.\n\n---\n\n### 📝 3. Template Center & Single-Note Export\n\n- **Visual Template Library**: Access a curated collection of note templates with live modal preview cards. Instantly create notes using a template and jump back with one click.\n- **Custom Templates**: Save your frequent note structures as custom templates to double your productivity.\n- **Flexible File Export**: Export the current note as a standard `.md` Markdown file or a beautifully styled `.pdf` document for offline archival and sharing.\n\n---\n\n### 📊 4. Native Mermaid Diagram Rendering\n\nUse standard `mermaid` fenced code blocks to render beautiful diagrams in real time, with support for **selectable diagram themes** and dimension-preserved copying:\n\n#### 1️⃣ System Flowchart\n```mermaid\nflowchart TD\n subgraph Client[\"📱 Clients Ecosystem\"]\n A[\"Web / PWA\"]\n B[\"macOS / Android / iOS Apps\"]\n end\n\n subgraph Backend[\"⚡ Cloudflare Serverless\"]\n C[\"Cloudflare Workers API\"]\n D[(\"D1 SQLite DB\")]\n E[(\"R2 Object Storage\")]\n end\n\n A & B --> C\n C <--> D & E\n```\n\n#### 2️⃣ Interactive Sequence Diagram\n```mermaid\nsequenceDiagram\n autonumber\n actor User as User\n participant App as EdgeEver Client\n participant Worker as Cloudflare Worker API\n participant D1 as D1 Database\n\n User->>App: Edit and save note\n App->>Worker: POST /api/v1/memos (Save changes)\n Worker->>D1: Write note content & update revision\n D1-->>Worker: Return success (revision + 1)\n Worker-->>App: 200 OK (Latest sync cursor)\n App-->>User: Status updated to \"Saved\"\n```\n\n---\n\n### 📁 5. Multi-Device Sync, Offline Queue & Clipping\n\n- **Everywhere You Need It**: Native clients are available for Web, Android, and macOS (Intel & Apple Silicon), with the iOS client under App Store review.\n- **Web Clipper**: Available on Chrome, Edge, and Firefox Add-ons stores to save webpage contents with one click.\n- **Mobile WeChat Clipper**: Share any WeChat article to EdgeEver on your phone, and it automatically extracts the article content as an editable note.\n- **Offline Sync & Queue**: Keep writing even without network. Your edits are queued locally and synchronized automatically when connection resumes. Customize sync intervals in settings.\n\n---\n\n### 🖼️ 6. Rich Media & Smart Image Compression\n\nDrag-and-drop or paste images directly into your editor. EdgeEver compresses images locally to WebP before upload, reducing file sizes by **50% - 90%** to save bandwidth and Cloudflare storage.\n\n\n\n---\n\n### 🤖 7. Native AI Agent Ecosystem (Agent-Ready)\n\nEdgeEver is architected natively for the AI era:\n\n1. **REST API**: Provides complete OpenAPI definitions at `/api/openapi.json`.\n2. **MCP (Model Context Protocol) Endpoint**: Accessible at `/mcp`, allowing AI agents (like Antigravity, Claude Code, and Cursor) to securely connect, read, and write notes in your workspace for automated tags, summaries, and edits.\n\n---\n\n### 🔒 8. Account Isolation & Secure Sharing\n\n- **Multi-Tenant Isolation**: Supports multiple user accounts with independent workspace databases and brute-force login protection.\n- **Active Devices Session Control**: Check active login locations and user agents, and revoke other sessions with one tap in settings.\n- **Revocable Note Sharing**: Share a note publicly with a secure link and toggle it off anytime. Active sharing status is visible on the note list and editor header.\n\n---\n\n> 🎯 **Quick Try**:\n> - Click the **WeChat Icon** in the top bar and paste the styled rich text directly into WeChat, Substack, or WordPress;\n> - Swap **Editor Themes** in **Settings** to find your favorite color scheme;\n> - Press `Cmd/Ctrl + Shift + F` to enter Focus Mode for distraction-free writing;\n> - Drag and drop notebooks in the left list to experiment with infinite nesting;\n> - Click \"Reset Demo Data\" in the sidebar or settings to reset the workspace state at any time!"+ },+} as const;+export const DEMO_SEED_MEMOS_EN = DEMO_SEED_MEMOS_ZH.map((memo) => {+ const english = DEMO_MEMO_ENGLISH[memo.id as keyof typeof DEMO_MEMO_ENGLISH];+ if (!english) {+ return null;+ }++ return {+ ...memo,+ id: `${memo.id}_en`,+ notebookId: "nb_demo_features_en",+ title: english.title,+ markdown: `${english.markdown}${DEMO_ATTACHMENT_MARKDOWN_EN}`,+ };+}).filter((memo): memo is NonNullable<typeof memo> => memo !== null);+export const DEMO_SEED_MEMOS_ZH_WITH_ATTACHMENTS = DEMO_SEED_MEMOS_ZH.map((memo) => ({+ ...memo,+ markdown: `${memo.markdown}${DEMO_ATTACHMENT_MARKDOWN_ZH}`,+}));+export const DEMO_SEED_MEMOS = [...DEMO_SEED_MEMOS_ZH_WITH_ATTACHMENTS, ...DEMO_SEED_MEMOS_EN];+export const DEMO_SEED_RESOURCES = [+ {+ id: "res_demo_cat_image",+ memoId: "memo_demo_overview",+ filename: "cute-cat-demo.svg",+ mimeType: "image/svg+xml",+ width: 960,+ height: 540,+ svg:+ '<svg xmlns="http://www.w3.org/2000/svg" width="960" height="540" viewBox="0 0 960 540" fill="none"><rect width="960" height="540" rx="32" fill="#f0fdfa"/><g transform="translate(480, 270) scale(2.2)"><path d="M-60,-20 C-60,-60 -30,-80 0,-80 C30,-80 60,-60 60,-20 C60,20 40,40 0,40 C-40,40 -60,20 -60,-20 Z" stroke="#0f766e" stroke-width="6" stroke-linecap="round" stroke-linejoin="round" fill="none"/><path d="M-45,-68 L-55,-100 L-20,-78" stroke="#0f766e" stroke-width="6" stroke-linecap="round" stroke-linejoin="round" fill="none"/><path d="M45,-68 L55,-100 L20,-78" stroke="#0f766e" stroke-width="6" stroke-linecap="round" stroke-linejoin="round" fill="none"/><path d="M-30,-25 Q-20,-15 -10,-25" stroke="#0f766e" stroke-width="5" stroke-linecap="round" fill="none"/><path d="M10,-25 Q20,-15 30,-25" stroke="#0f766e" stroke-width="5" stroke-linecap="round" fill="none"/><path d="M-5,-10 L5,-10 L0,-5 Z" fill="#0f766e"/><path d="M0,-5 Q-5,5 -10,2 M0,-5 Q5,5 10,2" stroke="#0f766e" stroke-width="4" stroke-linecap="round" fill="none"/><path d="M-40,-5 L-65,-8" stroke="#0f766e" stroke-width="4" stroke-linecap="round"/><path d="M-42,5 L-68,7" stroke="#0f766e" stroke-width="4" stroke-linecap="round"/><path d="M40,-5 L65,-8" stroke="#0f766e" stroke-width="4" stroke-linecap="round"/><path d="M42,5 L68,7" stroke="#0f766e" stroke-width="4" stroke-linecap="round"/><path d="M-30,35 C-30,70 -10,90 0,90 C10,90 30,70 30,35" stroke="#0f766e" stroke-width="6" stroke-linecap="round" fill="none"/><path d="M25,75 C45,75 55,60 55,45 C55,30 45,25 40,30 C35,35 40,45 45,45" stroke="#0f766e" stroke-width="6" stroke-linecap="round" fill="none"/></g></svg>'},+] as const;+export const DEMO_SEED_ATTACHMENT_RESOURCES = [...DEMO_SEED_RESOURCES, ...DEMO_ATTACHMENT_RESOURCES];+export const DEMO_SEED_NOTEBOOK_IDS = DEMO_SEED_NOTEBOOKS.map((notebook) => notebook.id);+export const DEMO_SEED_MEMO_IDS = DEMO_SEED_MEMOS.map((memo) => memo.id);diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex 21d6e713..f56e79fe 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -18,9 +18,6 @@ import {JsonBackupResourceMetadataSchema,MemoCreateSchema,MemoUpdateSchema,- TemplateCreateSchema,- TemplateUpdateSchema,- TemplateUseSchema,MergeMemosSchema,MoveMemosSchema,normalizeTags,@@ -38,8 +35,6 @@ import {type MemoRevision,type MemoSummary,type MemoUpdateInput,- type MemoTemplate,- type TemplateUpdateInput,type JsonBackupMemo,type JsonBackupNotebook,type JsonBackupResource,@@ -84,10 +79,13 @@ import {} from "./auth-login-limiter";import {decodeDemoAttachment,- DEMO_ATTACHMENT_MARKDOWN_EN,- DEMO_ATTACHMENT_MARKDOWN_ZH,- DEMO_ATTACHMENT_RESOURCES,-} from "./demo-attachments";+ DEMO_SEED_ATTACHMENT_RESOURCES,+ DEMO_SEED_MEMO_IDS,+ DEMO_SEED_MEMOS,+ DEMO_SEED_NOTEBOOK_IDS,+ DEMO_SEED_NOTEBOOKS,+ DEMO_SEED_REVISIONS,+} from "./demo-seed-data";import { createCloudflareStorageAdapter } from "./cloudflare-storage-adapter";import type {DatabaseAdapter,@@ -156,6 +154,7 @@ import {type TokenScope,} from "./request-auth";import { registerTagRoutes } from "./tag-routes";+import { registerTemplateRoutes } from "./template-routes";import { registerNotebookRoutes } from "./notebook-routes";import { registerMemoShareRoutes, registerPublicShareRoutes } from "./share-routes";import { decryptSecret, encryptSecret } from "./secret-encryption";@@ -224,18 +223,6 @@ type MemoDetailRow = MemoSummaryRow & {content_hash: string;};-type MemoTemplateRow = {- id: string;- name: string;- description: string | null;- title: string | null;- content_json: string;- content_markdown: string;- tags_json: string;- created_at: string;- updated_at: string;-};-type MemoRevisionRow = {id: string;memo_id: string;@@ -347,88 +334,9 @@ const SESSION_COOKIE = "edgeever_session";const DEFAULT_WORKSPACE_ID = "ws_default";const DEFAULT_MEMO_LIST_LIMIT = 100;const MAX_MEMO_LIST_LIMIT = 200;-const UNTITLED_MEMO_TITLE = "无标题笔记";const DEFAULT_SESSION_TTL_DAYS = 400;const MAX_SESSION_TTL_DAYS = 400;const DEFAULT_R2_BUCKET_NAME = "edgeever-resources";-const DEMO_SEED_NOTEBOOKS = [- { id: "nb_inbox", parentId: null, name: "等待分类", slug: "inbox", icon: "notebook", color: "#0f766e", sortOrder: 10 },- { id: "nb_projects", parentId: null, name: "工作项目", slug: "work-projects", icon: "notebook", color: "#2563eb", sortOrder: 20 },- { id: "nb_learning", parentId: null, name: "学习资料", slug: "learning-resources", icon: "notebook", color: "#7c3aed", sortOrder: 30 },- { id: "nb_creative", parentId: null, name: "灵感创作", slug: "creative-ideas", icon: "notebook", color: "#db2777", sortOrder: 40 },- { id: "nb_personal", parentId: null, name: "生活个人", slug: "personal-life", icon: "notebook", color: "#ea580c", sortOrder: 50 },- { id: "nb_demo_features", parentId: "nb_projects", name: "功能演示", slug: "demo-features", icon: "notebook", color: "#0891b2", sortOrder: 21 },- { id: "nb_demo_features_en", parentId: "nb_projects", name: "Feature Demos", slug: "feature-demos", icon: "notebook", color: "#0e7490", sortOrder: 22 },-];-const DEMO_SEED_MEMOS_ZH = [- {- id: "memo_demo_overview",- notebookId: "nb_demo_features",- title: "🌟 欢迎使用 EdgeEver",- tags: ["overview", "features", "demo"],- isPinned: true,- markdown:- "## 🚀 开启您的 EdgeEver 笔记之旅\n\n> **EdgeEver** 是一款专为极客与创作者打造的现代开源 Serverless 个人知识库。它找回了经典的**印象笔记三栏式双视图布局**,以 Cloudflare 免费额度提供 **100% 免费**的自建云端,数据完全掌控,并原生集成 AI Agent (MCP) 接口。\n\n---\n\n### ⚡ 1. 核心产品特性对比\n\n*提示:在线模式下点击表格单元格可以直接修改文本;右键可快捷操作行列。*\n\n| 核心维度 | 传统云笔记 (如 Evernote) | 本地知识库 (如 Obsidian) | EdgeEver 极客笔记 |\n| :--- | :--- | :--- | :--- |\n| **云端托管成本** | 商业订阅高昂 ($10+/月) | 官方同步收费 ($5/月) | **100% 免费 (Cloudflare 免费额度)** |\n| **数据与隐私** | 封闭平台,导出受限 | 本地文件,同步需配置 | **完全掌控 (D1 SQLite 数据库 / R2 / WebDAV)** |\n| **编辑体验** | 富文本编辑 | 纯 Markdown | **双视图自由切换 (富文本 / Markdown 源码)** |\n| **多端支持** | 限制设备数量 | 移动端配置繁琐 | **Web / PWA / Android / macOS / iOS (审核中)** |\n| **创作者排版** | 无优化,格式易乱 | 需借助外部工具 | **微信公众号、Substack 一键富文本格式复制** |\n| **AI 原生集成** | 限制/仅特定付费版本 | 需繁琐的第三方插件 | **原生支持 MCP 协议与标准 OpenAPI** |\n\n---\n\n### 🎨 2. 沉浸式写作与排版美学\n\nEdgeEver 追求极致的创作体验,将设计美学融于字里行间:\n\n- **双视图编辑器**:点击右上角 `</>` 按钮,可在**所见即所得富文本**与 **Markdown 源码**间无缝切换,格式完全兼容。\n- **左侧可折叠大纲**:提供固定或折叠的大纲目录视图,支持点击标题平滑滚动定位,助您轻松掌控长文结构。\n- **8+ 款精致编辑器主题**:可在 **个人中心 / 设置** 中一键切换如 `WeChat Classic Green (微信经典绿)`、`Modern Mint (薄荷青)`、`minimal-emerald (极简祖母绿)` 等排版风格。\n- **自媒体一键排版复制**:专为创作者设计。点击右上角“复制到公众号”按钮,系统会自动将笔记转化为带行内样式的公众号美化格式,直接粘贴至微信公众号、Substack 或 WordPress 后台,排版与代码高亮完美保真。\n- **列表缩进与快捷操作**:支持快捷缩进列表,双击或选中文本可通过快捷键快速关联已有笔记。\n\n---\n\n### 📝 3. 模板中心与单篇导出\n\n- **可视化推荐模板库**:内置多种精美模板,点击即可弹窗预览。支持在当前笔记本中一键套用模板创建笔记,并支持一键返回列表。\n- **用户自定义模板**:您可以将常用笔记结构保存为自定义模板,实现效率翻倍。\n- **单篇便捷导出**:支持将当前笔记一键导出为标准的 `.md` Markdown 文件或排版优美的 `.pdf` 电子文档,便于独立归档与分发。\n\n---\n\n### 📊 4. 原生 Mermaid 动态图表渲染\n\n在代码块中使用 `mermaid` 标记,即可实时渲染高保真的动态逻辑图。支持多款**精致图表主题**选择,且微信复制时尺寸完美兼容:\n\n#### 1️⃣ 架构流程图 (Flowchart)\n```mermaid\nflowchart TD\n subgraph Client[\"📱 客户端生态\"]\n A[\"Web / PWA 浏览器\"]\n B[\"macOS / Android / iOS 客户端\"]\n end\n\n subgraph Backend[\"⚡ Cloudflare Serverless\"]\n C[\"Cloudflare Workers API\"]\n D[(\"D1 SQLite 数据库\")]\n E[(\"R2 资源存储\")]\n end\n\n A & B --> C\n C <--> D & E\n```\n\n#### 2️⃣ 交互时序图 (Sequence Diagram)\n```mermaid\nsequenceDiagram\n autonumber\n actor User as 用户\n participant App as 客户端 App\n participant Worker as Cloudflare Worker API\n participant D1 as D1 数据库\n\n User->>App: 编辑并保存笔记\n App->>Worker: POST /api/v1/memos (提交更改)\n Worker->>D1: 写入笔记 & 更新修订版本\n D1-->>Worker: 返回成功 (revision + 1)\n Worker-->>App: 200 OK (同步最新游标)\n App-->>User: 界面显示「已保存」\n```\n\n---\n\n### 📁 5. 多端覆盖、自动同步与剪藏\n\n- **全平台多端覆盖**:已发布 Web、Android 原生 App 以及 macOS 桌面端(支持 Apple Silicon 和 Intel Mac),iOS 客户端正在 App Store 审核中。\n- **网页裁剪器 (Web Clipper)**:已上架 Chrome, Edge 和 Firefox 插件商店,支持一键剪藏网页。\n- **微信文章一键剪藏**:在手机上直接将微信公众号文章分享至 EdgeEver App,系统将智能提取正文并保存为可编辑笔记。\n- **离线草稿与同步队列**:无网环境下自动保存本地,恢复连线后自动入队同步;支持在设置中灵活配置自动同步间隔。\n\n---\n\n### 🖼️ 6. 多媒体集成与图片前端压缩\n\n支持直接拖拽或粘贴插入图片与文件附件。本地浏览器会在上传前自动对图片进行 WebP 高保真压缩,缩减 **50% - 90%** 的体积,大幅加快加载速度并节省您的云端存储空间。\n\n\n\n---\n\n### 🤖 7. 面向 AI Agent 的原生生态\n\nEdgeEver 走在 AI 时代前沿,为 AI 协作者提供了原生支持:\n\n1. **REST API**:提供标准的 OpenAPI 接口,接口定义见 `/api/openapi.json`。\n2. **MCP (Model Context Protocol) 接口**:内置 MCP 服务端点 `/mcp`。像 Antigravity, Claude Code, Cursor 等 AI Agent 可以直接连接并安全地读写您的笔记库,实现笔记自动整理、标签归纳与双向联动。\n\n---\n\n### 🔒 8. 个人空间隔离与安全分享\n\n- **多账号与管理员中心**:支持多账号独立登录,数据物理隔离。系统提供防暴力破解的安全防护。\n- **多活跃设备管理**:个人设置中可直观查看当前账户在哪些设备登录,并可随时强制下线其他设备。\n- **可撤销的公开分享**:支持生成单独笔记的公开分享链接(列表及正文顶部可直观感知分享状态),他人无需登录即可查阅最新内容,您也可以随时关闭分享。\n\n---\n\n> 🎯 **快速探索建议**:\n> - 试试点击右上角的**微信图标**,将排版精美的富文本直接粘贴至公众号或 WordPress 后台;\n> - 试试在 **个人中心 / 设置 / 编辑器主题** 中切换您喜爱的写作风格;\n> - 按下 `Cmd/Ctrl + Shift + F` 开启 Zen 专注模式,享受无干扰的写作空间;\n> - 鼠标拖拽左侧的笔记本,体验无限层级目录的顺滑管理;\n> - 在个人中心或侧边栏点击“恢复 Demo 数据”,即可随时一键将整个演示环境恢复如初。"- },-];-const DEMO_SEED_REVISIONS = [- {- id: "rev_demo_revision_1",- memoId: "memo_demo_overview",- revision: 1,- title: "🌟 欢迎使用 EdgeEver",- markdown:- "## 🌟 欢迎使用 EdgeEver(草稿)\n\n- 印象笔记经典三栏与自建 Serverless\n- 可视化表格与 Markdown 源码双向切换",- },- {- id: "rev_demo_revision_1_en",- memoId: "memo_demo_overview_en",- revision: 1,- title: "🌟 Welcome to EdgeEver",- markdown:- "## 🌟 Welcome to EdgeEver (Draft)\n\n- Classic Evernote 3-pane layout & Serverless self-hosted\n- Visual table editing & Markdown source toggle",- },-];-const DEMO_MEMO_ENGLISH = {- memo_demo_overview: {- title: "🌟 Welcome to EdgeEver",- markdown:- "## 🚀 Get Started with EdgeEver: The Geek's Knowledge Base\n\n> **EdgeEver** is a modern, open-source, serverless personal knowledge base built for geeks and creators. It restores the classic **Evernote-style three-pane layout**, while offering **100% free hosting** using Cloudflare's free tier, full data ownership, dual-view editing, and native AI Agent (MCP) integration.\n\n---\n\n### ⚡ 1. Feature Comparison\n\n*Tip: Click any cell in the table below to edit directly; right-click in editor mode to insert/delete rows or columns.*\n\n| Metric | Traditional Cloud Notes (e.g. Evernote) | Local Offline Notes (e.g. Obsidian) | EdgeEver Notes |\n| :--- | :--- | :--- | :--- |\n| **Hosting Cost** | High monthly fee ($10+/mo) | Official sync fee ($5/mo) | **100% Free (Cloudflare Free Tier)** |\n| **Data & Privacy** | Closed platform, locked export | Local files, sync needs setup | **Full Ownership (D1 SQLite, R2, WebDAV)** |\n| **Editing Mode** | Rich Text | Pure Markdown | **Seamless Dual-View Toggle (Rich Text / MD)** |\n| **Device Sync** | Limits active devices | Complicated mobile setup | **Web / PWA / Android / macOS / iOS (In Review)** |\n| **For Creators** | No formatting optimizations | Requires 3rd-party tools | **One-Click Rich Copy for WeChat & Substack** |\n| **AI Integration**| Paid/Limited versions only | Requires heavy plugin config | **Native MCP Protocol & Standard OpenAPI** |\n\n---\n\n### 🎨 2. Immersive Writing & Typography Aesthetics\n\nEdgeEver is crafted to provide a distraction-free and beautiful writing experience:\n\n- **Seamless Dual-View Editor**: Click the `</>` button in the top right to switch effortlessly between **WYSIWYG Rich Text** and **Markdown Source Code** with 100% compatibility.\n- **Collapsible Outline View**: Enjoy a fixed or collapsible sidebar outline of your document headings. Click any heading to navigate smoothly.\n- **8+ Exquisite Editor Themes**: Change your writing vibe instantly in **User Settings / Profile** with preset themes such as `WeChat Classic Green`, `Modern Mint`, `minimal-emerald`, and more.\n- **One-Click Publishing Export**: Built for publishers. Click \"Copy for WeChat / Publishing\" to automatically format your note with inline CSS. Paste it directly into WeChat, Substack, Medium, or WordPress editor while preserving layout and syntax highlighting.\n- **List Indentation & Quick Link**: Use quick keys for list indents, and double-click or select text to quickly link to existing notes with shortcut hints.\n\n---\n\n### 📝 3. Template Center & Single-Note Export\n\n- **Visual Template Library**: Access a curated collection of note templates with live modal preview cards. Instantly create notes using a template and jump back with one click.\n- **Custom Templates**: Save your frequent note structures as custom templates to double your productivity.\n- **Flexible File Export**: Export the current note as a standard `.md` Markdown file or a beautifully styled `.pdf` document for offline archival and sharing.\n\n---\n\n### 📊 4. Native Mermaid Diagram Rendering\n\nUse standard `mermaid` fenced code blocks to render beautiful diagrams in real time, with support for **selectable diagram themes** and dimension-preserved copying:\n\n#### 1️⃣ System Flowchart\n```mermaid\nflowchart TD\n subgraph Client[\"📱 Clients Ecosystem\"]\n A[\"Web / PWA\"]\n B[\"macOS / Android / iOS Apps\"]\n end\n\n subgraph Backend[\"⚡ Cloudflare Serverless\"]\n C[\"Cloudflare Workers API\"]\n D[(\"D1 SQLite DB\")]\n E[(\"R2 Object Storage\")]\n end\n\n A & B --> C\n C <--> D & E\n```\n\n#### 2️⃣ Interactive Sequence Diagram\n```mermaid\nsequenceDiagram\n autonumber\n actor User as User\n participant App as EdgeEver Client\n participant Worker as Cloudflare Worker API\n participant D1 as D1 Database\n\n User->>App: Edit and save note\n App->>Worker: POST /api/v1/memos (Save changes)\n Worker->>D1: Write note content & update revision\n D1-->>Worker: Return success (revision + 1)\n Worker-->>App: 200 OK (Latest sync cursor)\n App-->>User: Status updated to \"Saved\"\n```\n\n---\n\n### 📁 5. Multi-Device Sync, Offline Queue & Clipping\n\n- **Everywhere You Need It**: Native clients are available for Web, Android, and macOS (Intel & Apple Silicon), with the iOS client under App Store review.\n- **Web Clipper**: Available on Chrome, Edge, and Firefox Add-ons stores to save webpage contents with one click.\n- **Mobile WeChat Clipper**: Share any WeChat article to EdgeEver on your phone, and it automatically extracts the article content as an editable note.\n- **Offline Sync & Queue**: Keep writing even without network. Your edits are queued locally and synchronized automatically when connection resumes. Customize sync intervals in settings.\n\n---\n\n### 🖼️ 6. Rich Media & Smart Image Compression\n\nDrag-and-drop or paste images directly into your editor. EdgeEver compresses images locally to WebP before upload, reducing file sizes by **50% - 90%** to save bandwidth and Cloudflare storage.\n\n\n\n---\n\n### 🤖 7. Native AI Agent Ecosystem (Agent-Ready)\n\nEdgeEver is architected natively for the AI era:\n\n1. **REST API**: Provides complete OpenAPI definitions at `/api/openapi.json`.\n2. **MCP (Model Context Protocol) Endpoint**: Accessible at `/mcp`, allowing AI agents (like Antigravity, Claude Code, and Cursor) to securely connect, read, and write notes in your workspace for automated tags, summaries, and edits.\n\n---\n\n### 🔒 8. Account Isolation & Secure Sharing\n\n- **Multi-Tenant Isolation**: Supports multiple user accounts with independent workspace databases and brute-force login protection.\n- **Active Devices Session Control**: Check active login locations and user agents, and revoke other sessions with one tap in settings.\n- **Revocable Note Sharing**: Share a note publicly with a secure link and toggle it off anytime. Active sharing status is visible on the note list and editor header.\n\n---\n\n> 🎯 **Quick Try**:\n> - Click the **WeChat Icon** in the top bar and paste the styled rich text directly into WeChat, Substack, or WordPress;\n> - Swap **Editor Themes** in **Settings** to find your favorite color scheme;\n> - Press `Cmd/Ctrl + Shift + F` to enter Focus Mode for distraction-free writing;\n> - Drag and drop notebooks in the left list to experiment with infinite nesting;\n> - Click \"Reset Demo Data\" in the sidebar or settings to reset the workspace state at any time!"- },-} as const;-const DEMO_SEED_MEMOS_EN = DEMO_SEED_MEMOS_ZH.map((memo) => {- const english = DEMO_MEMO_ENGLISH[memo.id as keyof typeof DEMO_MEMO_ENGLISH];- if (!english) {- return null;- }-- return {- ...memo,- id: `${memo.id}_en`,- notebookId: "nb_demo_features_en",- title: english.title,- markdown: `${english.markdown}${DEMO_ATTACHMENT_MARKDOWN_EN}`,- };-}).filter((memo): memo is NonNullable<typeof memo> => memo !== null);-const DEMO_SEED_MEMOS_ZH_WITH_ATTACHMENTS = DEMO_SEED_MEMOS_ZH.map((memo) => ({- ...memo,- markdown: `${memo.markdown}${DEMO_ATTACHMENT_MARKDOWN_ZH}`,-}));-const DEMO_SEED_MEMOS = [...DEMO_SEED_MEMOS_ZH_WITH_ATTACHMENTS, ...DEMO_SEED_MEMOS_EN];-const DEMO_SEED_RESOURCES = [- {- id: "res_demo_cat_image",- memoId: "memo_demo_overview",- filename: "cute-cat-demo.svg",- mimeType: "image/svg+xml",- width: 960,- height: 540,- svg:- '<svg xmlns="http://www.w3.org/2000/svg" width="960" height="540" viewBox="0 0 960 540" fill="none"><rect width="960" height="540" rx="32" fill="#f0fdfa"/><g transform="translate(480, 270) scale(2.2)"><path d="M-60,-20 C-60,-60 -30,-80 0,-80 C30,-80 60,-60 60,-20 C60,20 40,40 0,40 C-40,40 -60,20 -60,-20 Z" stroke="#0f766e" stroke-width="6" stroke-linecap="round" stroke-linejoin="round" fill="none"/><path d="M-45,-68 L-55,-100 L-20,-78" stroke="#0f766e" stroke-width="6" stroke-linecap="round" stroke-linejoin="round" fill="none"/><path d="M45,-68 L55,-100 L20,-78" stroke="#0f766e" stroke-width="6" stroke-linecap="round" stroke-linejoin="round" fill="none"/><path d="M-30,-25 Q-20,-15 -10,-25" stroke="#0f766e" stroke-width="5" stroke-linecap="round" fill="none"/><path d="M10,-25 Q20,-15 30,-25" stroke="#0f766e" stroke-width="5" stroke-linecap="round" fill="none"/><path d="M-5,-10 L5,-10 L0,-5 Z" fill="#0f766e"/><path d="M0,-5 Q-5,5 -10,2 M0,-5 Q5,5 10,2" stroke="#0f766e" stroke-width="4" stroke-linecap="round" fill="none"/><path d="M-40,-5 L-65,-8" stroke="#0f766e" stroke-width="4" stroke-linecap="round"/><path d="M-42,5 L-68,7" stroke="#0f766e" stroke-width="4" stroke-linecap="round"/><path d="M40,-5 L65,-8" stroke="#0f766e" stroke-width="4" stroke-linecap="round"/><path d="M42,5 L68,7" stroke="#0f766e" stroke-width="4" stroke-linecap="round"/><path d="M-30,35 C-30,70 -10,90 0,90 C10,90 30,70 30,35" stroke="#0f766e" stroke-width="6" stroke-linecap="round" fill="none"/><path d="M25,75 C45,75 55,60 55,45 C55,30 45,25 40,30 C35,35 40,45 45,45" stroke="#0f766e" stroke-width="6" stroke-linecap="round" fill="none"/></g></svg>'},-] as const;-const DEMO_SEED_ATTACHMENT_RESOURCES = [...DEMO_SEED_RESOURCES, ...DEMO_ATTACHMENT_RESOURCES];-const DEMO_SEED_NOTEBOOK_IDS = DEMO_SEED_NOTEBOOKS.map((notebook) => notebook.id);-const DEMO_SEED_MEMO_IDS = DEMO_SEED_MEMOS.map((memo) => memo.id);const MAX_IMAGE_UPLOAD_BYTES = 100 * 1024 * 1024;const MAX_ATTACHMENT_UPLOAD_BYTES = 100 * 1024 * 1024;const REVISION_SNAPSHOT_INTERVAL_MS = 5 * 60 * 1000;@@ -1243,125 +1151,11 @@ app.get("/api/v1/sync/changes", async (c) => {registerTagRoutes(app);registerMemoShareRoutes(app);--app.get("/api/v1/templates", async (c) => {- const rows = await c.env.storage.db.prepare(- `SELECT id, name, description, title, content_json, content_markdown, tags_json, created_at, updated_at- FROM memo_templates- WHERE workspace_id = ?- ORDER BY updated_at DESC, name ASC`- ).bind(getWorkspaceId(c)).all<MemoTemplateRow>();-- return c.json({ templates: rows.results.map(mapMemoTemplate) });-});--app.post("/api/v1/templates", zValidator("json", TemplateCreateSchema), async (c) => {- const input = c.req.valid("json");- const workspaceId = getWorkspaceId(c);- const memo = input.memoId ? await getMemoDetail(c.env.storage.db, workspaceId, input.memoId) : null;- if (input.memoId && !memo) {- return notFound(c, "Memo not found");- }-- const id = createId("template");- const now = new Date().toISOString();- const title = memo?.title ?? (input.title?.trim() || null);- const contentMarkdown = memo?.contentMarkdown ?? input.contentMarkdown ?? "";- const tags = memo?.tags ?? input.tags ?? [];- const contentJson = memo?.contentJson ?? markdownToDoc(contentMarkdown);- await c.env.storage.db.prepare(- `INSERT INTO memo_templates (- id, workspace_id, name, description, title, content_json, content_markdown, tags_json, created_at, updated_at- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`- ).bind(- id,- workspaceId,- input.name.trim(),- input.description?.trim() || null,- title,- JSON.stringify(contentJson),- contentMarkdown,- JSON.stringify(tags),- now,- now,- ).run();-- const template = await getMemoTemplate(c.env.storage.db, workspaceId, id);- const actor = getAuditActor(c);- await audit(c.env.storage.db, actor.actorType, actor.actorId, "template.create", "template", id, { memoId: input.memoId ?? null });- return c.json({ template }, 201);+registerTemplateRoutes(app, {+ createMemoRecord: (...args) => createMemoRecord(...args),+ getMemoDetail: (...args) => getMemoDetail(...args),});-app.patch("/api/v1/templates/:id", zValidator("json", TemplateUpdateSchema), async (c) => {- const id = c.req.param("id");- const input = c.req.valid("json");- const workspaceId = getWorkspaceId(c);- const current = await getMemoTemplateRow(c.env.storage.db, workspaceId, id);- if (!current) {- return notFound(c, "Template not found");- }-- const contentMarkdown = input.contentMarkdown ?? current.content_markdown;- const contentJson = input.contentMarkdown !== undefined- ? markdownToDoc(contentMarkdown)- : JSON.parse(current.content_json);- const tags = input.tags ?? parseJsonArray(current.tags_json);- const now = new Date().toISOString();- await c.env.storage.db.prepare(- `UPDATE memo_templates- SET name = ?, description = ?, title = ?, content_json = ?, content_markdown = ?, tags_json = ?, updated_at = ?- WHERE id = ? AND workspace_id = ?`- ).bind(- input.name ?? current.name,- input.description !== undefined ? input.description?.trim() || null : current.description,- input.title !== undefined ? input.title?.trim() || null : current.title,- JSON.stringify(contentJson),- contentMarkdown,- JSON.stringify(tags),- now,- id,- workspaceId,- ).run();-- const template = await getMemoTemplate(c.env.storage.db, workspaceId, id);- const actor = getAuditActor(c);- await audit(c.env.storage.db, actor.actorType, actor.actorId, "template.update", "template", id, {});- return c.json({ template });-});--app.post("/api/v1/templates/:id/use", zValidator("json", TemplateUseSchema), async (c) => {- const id = c.req.param("id");- const input = c.req.valid("json");- const workspaceId = getWorkspaceId(c);- const template = await getMemoTemplate(c.env.storage.db, workspaceId, id);- if (!template) {- return notFound(c, "Template not found");- }-- const memo = await createMemoRecord(c.env.storage.db, workspaceId, {- notebookId: input.notebookId,- title: template.title ?? undefined,- contentMarkdown: template.contentMarkdown,- tags: template.tags,- }, getAuditActor(c), getActorLabel(c));- const actor = getAuditActor(c);- await audit(c.env.storage.db, actor.actorType, actor.actorId, "template.use", "template", id, { memoId: memo.id });- return c.json({ memo });-});--app.delete("/api/v1/templates/:id", async (c) => {- const id = c.req.param("id");- const workspaceId = getWorkspaceId(c);- const current = await getMemoTemplateRow(c.env.storage.db, workspaceId, id);- if (!current) {- return notFound(c, "Template not found");- }-- await c.env.storage.db.prepare(`DELETE FROM memo_templates WHERE id = ? AND workspace_id = ?`).bind(id, workspaceId).run();- const actor = getAuditActor(c);- await audit(c.env.storage.db, actor.actorType, actor.actorId, "template.delete", "template", id, {});- return c.json({ ok: true });-});app.get("/api/v1/memos", async (c) => {const denied = requireScopes(c, "read:memos");@@ -1379,7 +1173,7 @@ app.get("/api/v1/memos", async (c) => {const limit = clampNumber(Number(c.req.query("limit") ?? DEFAULT_MEMO_LIST_LIMIT), 1, MAX_MEMO_LIST_LIMIT);const cursor = decodeMemoListCursor(c.req.query("cursor"), sort);const deletedClause = includeTrash ? "m.is_deleted = 1" : "m.is_deleted = 0";- const titleSortExpression = `LOWER(COALESCE(NULLIF(m.title, ''), '${UNTITLED_MEMO_TITLE}'))`;+ const titleSortExpression = `LOWER(COALESCE(NULLIF(m.title, ''), '${DEFAULT_MEMO_TITLE}'))`;const baseConditions = ["m.workspace_id = ?", deletedClause];const baseBinds: unknown[] = [getWorkspaceId(c)];@@ -3911,18 +3705,6 @@ const mapMemoDetail = (row: MemoDetailRow): MemoDetail => ({mergedIntoMemoId: row.merged_into_memo_id,});-const mapMemoTemplate = (row: MemoTemplateRow): MemoTemplate => ({- id: row.id,- name: row.name,- description: row.description,- title: row.title,- contentJson: parseDoc(row.content_json),- contentMarkdown: row.content_markdown,- tags: parseJsonArray(row.tags_json),- createdAt: row.created_at,- updatedAt: row.updated_at,-});-const mapMemoRevision = (row: MemoRevisionRow): MemoRevision => ({id: row.id,memoId: row.memo_id,@@ -4444,18 +4226,6 @@ const getMemoDetail = async (db: D1Database, workspaceId: string, id: string, inreturn row ? mapMemoDetail(row) : null;};-const getMemoTemplateRow = async (db: D1Database, workspaceId: string, id: string): Promise<MemoTemplateRow | null> =>- db.prepare(- `SELECT id, name, description, title, content_json, content_markdown, tags_json, created_at, updated_at- FROM memo_templates- WHERE id = ? AND workspace_id = ?`- ).bind(id, workspaceId).first<MemoTemplateRow>();--const getMemoTemplate = async (db: D1Database, workspaceId: string, id: string): Promise<MemoTemplate | null> => {- const row = await getMemoTemplateRow(db, workspaceId, id);- return row ? mapMemoTemplate(row) : null;-};-const deleteMemosRecord = async (env: Bindings,workspaceId: string,diff --git a/apps/api/src/template-routes.test.mjs b/apps/api/src/template-routes.test.mjsnew file mode 100644index 00000000..b0da01ff--- /dev/null+++ b/apps/api/src/template-routes.test.mjs@@ -0,0 +1,37 @@+import { describe, expect, test } from "bun:test";+import { mapMemoTemplateRow } from "./template-routes.ts";++const row = {+ id: "template_1",+ name: "Weekly review",+ description: "Review template",+ title: "Week 1",+ content_json: '{"type":"doc","content":[{"type":"paragraph"}]}',+ content_markdown: "# Week 1",+ tags_json: '["review","weekly"]',+ created_at: "2026-08-08T00:00:00.000Z",+ updated_at: "2026-08-08T01:00:00.000Z",+};++describe("template route mapping", () => {+ test("maps storage rows into the public template contract", () => {+ expect(mapMemoTemplateRow(row)).toEqual({+ id: "template_1",+ name: "Weekly review",+ description: "Review template",+ title: "Week 1",+ contentJson: { type: "doc", content: [{ type: "paragraph" }] },+ contentMarkdown: "# Week 1",+ tags: ["review", "weekly"],+ createdAt: "2026-08-08T00:00:00.000Z",+ updatedAt: "2026-08-08T01:00:00.000Z",+ });+ });++ test("fails closed to an empty document for damaged stored JSON", () => {+ expect(mapMemoTemplateRow({ ...row, content_json: "damaged" }).contentJson).toEqual({+ type: "doc",+ content: [{ type: "paragraph" }],+ });+ });+});diff --git a/apps/api/src/template-routes.ts b/apps/api/src/template-routes.tsnew file mode 100644index 00000000..ab3af658--- /dev/null+++ b/apps/api/src/template-routes.ts@@ -0,0 +1,221 @@+import {+ emptyDoc,+ markdownToDoc,+ TemplateCreateSchema,+ TemplateUpdateSchema,+ TemplateUseSchema,+ type MemoDetail,+ type MemoTemplate,+ type TiptapDoc,+} from "@edgeever/shared";+import { zValidator } from "@hono/zod-validator";+import type { Hono } from "hono";+import { audit } from "./audit";+import type { AppEnv, AuditActor } from "./api-context";+import { createId, parseJsonArray } from "./entity-utils";+import { notFound } from "./http-errors";+import { getActorLabel, getAuditActor, getWorkspaceId } from "./request-auth";+import type { DatabaseAdapter } from "./storage-contract";++export type MemoTemplateRow = {+ id: string;+ name: string;+ description: string | null;+ title: string | null;+ content_json: string;+ content_markdown: string;+ tags_json: string;+ created_at: string;+ updated_at: string;+};++type MemoCreateInput = {+ notebookId: string;+ title?: string;+ contentMarkdown?: string;+ tags?: string[];+ createdAt?: string;+ updatedAt?: string;+};++type TemplateRouteDependencies = {+ createMemoRecord: (+ db: DatabaseAdapter,+ workspaceId: string,+ input: MemoCreateInput,+ actor: AuditActor,+ actorLabel: string+ ) => Promise<MemoDetail>;+ getMemoDetail: (+ db: DatabaseAdapter,+ workspaceId: string,+ id: string,+ includeDeleted?: boolean+ ) => Promise<MemoDetail | null>;+};++const parseTemplateDoc = (json: string): TiptapDoc => {+ try {+ const value = JSON.parse(json);+ return value && typeof value === "object" ? (value as TiptapDoc) : emptyDoc();+ } catch {+ return emptyDoc();+ }+};++export const mapMemoTemplateRow = (row: MemoTemplateRow): MemoTemplate => ({+ id: row.id,+ name: row.name,+ description: row.description,+ title: row.title,+ contentJson: parseTemplateDoc(row.content_json),+ contentMarkdown: row.content_markdown,+ tags: parseJsonArray(row.tags_json),+ createdAt: row.created_at,+ updatedAt: row.updated_at,+});++const getMemoTemplateRow = async (+ db: DatabaseAdapter,+ workspaceId: string,+ id: string+): Promise<MemoTemplateRow | null> =>+ db.prepare(+ `SELECT id, name, description, title, content_json, content_markdown, tags_json, created_at, updated_at+ FROM memo_templates+ WHERE id = ? AND workspace_id = ?`+ ).bind(id, workspaceId).first<MemoTemplateRow>();++const getMemoTemplate = async (+ db: DatabaseAdapter,+ workspaceId: string,+ id: string+): Promise<MemoTemplate | null> => {+ const row = await getMemoTemplateRow(db, workspaceId, id);+ return row ? mapMemoTemplateRow(row) : null;+};++export const registerTemplateRoutes = (+ app: Hono<AppEnv>,+ dependencies: TemplateRouteDependencies+) => {+ const { createMemoRecord, getMemoDetail } = dependencies;+ app.get("/api/v1/templates", async (c) => {+ const rows = await c.env.storage.db.prepare(+ `SELECT id, name, description, title, content_json, content_markdown, tags_json, created_at, updated_at+ FROM memo_templates+ WHERE workspace_id = ?+ ORDER BY updated_at DESC, name ASC`+ ).bind(getWorkspaceId(c)).all<MemoTemplateRow>();++ return c.json({ templates: rows.results.map(mapMemoTemplateRow) });+ });++ app.post("/api/v1/templates", zValidator("json", TemplateCreateSchema), async (c) => {+ const input = c.req.valid("json");+ const workspaceId = getWorkspaceId(c);+ const memo = input.memoId ? await getMemoDetail(c.env.storage.db, workspaceId, input.memoId) : null;+ if (input.memoId && !memo) {+ return notFound(c, "Memo not found");+ }++ const id = createId("template");+ const now = new Date().toISOString();+ const title = memo?.title ?? (input.title?.trim() || null);+ const contentMarkdown = memo?.contentMarkdown ?? input.contentMarkdown ?? "";+ const tags = memo?.tags ?? input.tags ?? [];+ const contentJson = memo?.contentJson ?? markdownToDoc(contentMarkdown);+ await c.env.storage.db.prepare(+ `INSERT INTO memo_templates (+ id, workspace_id, name, description, title, content_json, content_markdown, tags_json, created_at, updated_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`+ ).bind(+ id,+ workspaceId,+ input.name.trim(),+ input.description?.trim() || null,+ title,+ JSON.stringify(contentJson),+ contentMarkdown,+ JSON.stringify(tags),+ now,+ now,+ ).run();++ const template = await getMemoTemplate(c.env.storage.db, workspaceId, id);+ const actor = getAuditActor(c);+ await audit(c.env.storage.db, actor.actorType, actor.actorId, "template.create", "template", id, { memoId: input.memoId ?? null });+ return c.json({ template }, 201);+ });++ app.patch("/api/v1/templates/:id", zValidator("json", TemplateUpdateSchema), async (c) => {+ const id = c.req.param("id");+ const input = c.req.valid("json");+ const workspaceId = getWorkspaceId(c);+ const current = await getMemoTemplateRow(c.env.storage.db, workspaceId, id);+ if (!current) {+ return notFound(c, "Template not found");+ }++ const contentMarkdown = input.contentMarkdown ?? current.content_markdown;+ const contentJson = input.contentMarkdown !== undefined+ ? markdownToDoc(contentMarkdown)+ : JSON.parse(current.content_json);+ const tags = input.tags ?? parseJsonArray(current.tags_json);+ const now = new Date().toISOString();+ await c.env.storage.db.prepare(+ `UPDATE memo_templates+ SET name = ?, description = ?, title = ?, content_json = ?, content_markdown = ?, tags_json = ?, updated_at = ?+ WHERE id = ? AND workspace_id = ?`+ ).bind(+ input.name ?? current.name,+ input.description !== undefined ? input.description?.trim() || null : current.description,+ input.title !== undefined ? input.title?.trim() || null : current.title,+ JSON.stringify(contentJson),+ contentMarkdown,+ JSON.stringify(tags),+ now,+ id,+ workspaceId,+ ).run();++ const template = await getMemoTemplate(c.env.storage.db, workspaceId, id);+ const actor = getAuditActor(c);+ await audit(c.env.storage.db, actor.actorType, actor.actorId, "template.update", "template", id, {});+ return c.json({ template });+ });++ app.post("/api/v1/templates/:id/use", zValidator("json", TemplateUseSchema), async (c) => {+ const id = c.req.param("id");+ const input = c.req.valid("json");+ const workspaceId = getWorkspaceId(c);+ const template = await getMemoTemplate(c.env.storage.db, workspaceId, id);+ if (!template) {+ return notFound(c, "Template not found");+ }++ const memo = await createMemoRecord(c.env.storage.db, workspaceId, {+ notebookId: input.notebookId,+ title: template.title ?? undefined,+ contentMarkdown: template.contentMarkdown,+ tags: template.tags,+ }, getAuditActor(c), getActorLabel(c));+ const actor = getAuditActor(c);+ await audit(c.env.storage.db, actor.actorType, actor.actorId, "template.use", "template", id, { memoId: memo.id });+ return c.json({ memo });+ });++ app.delete("/api/v1/templates/:id", async (c) => {+ const id = c.req.param("id");+ const workspaceId = getWorkspaceId(c);+ const current = await getMemoTemplateRow(c.env.storage.db, workspaceId, id);+ if (!current) {+ return notFound(c, "Template not found");+ }++ await c.env.storage.db.prepare(`DELETE FROM memo_templates WHERE id = ? AND workspace_id = ?`).bind(id, workspaceId).run();+ const actor = getAuditActor(c);+ await audit(c.env.storage.db, actor.actorType, actor.actorId, "template.delete", "template", id, {});+ return c.json({ ok: true });+ });+};diff --git a/apps/ios/EdgeEver.xcodeproj/project.pbxproj b/apps/ios/EdgeEver.xcodeproj/project.pbxprojindex edee39f4..bac6254c 100644--- a/apps/ios/EdgeEver.xcodeproj/project.pbxproj+++ b/apps/ios/EdgeEver.xcodeproj/project.pbxproj@@ -38,11 +38,13 @@50800DF91A760DE7FB68DFB4 /* Motion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58C065FED3C78404D4D8DD19 /* Motion.swift */; };511A8DCB204AFCB2880AE51E /* MemoCreateCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 82E057D0906932A00DF62EBB /* MemoCreateCommitTests.swift */; };541297DC463B8FC593ECB5F6 /* ResourceBlobStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA9305413739F81EA39395F7 /* ResourceBlobStore.swift */; };+ 5724B9A66EC1AE14D4C48F8B /* EditorContentCodec.swift in Sources */ = {isa = PBXBuildFile; fileRef = F01CF1D403DB46FB8784062E /* EditorContentCodec.swift */; };588019CB46131EDF8DCB2F53 /* MemoTemplatesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8D1DC59EC9FA65240DCBC19 /* MemoTemplatesTests.swift */; };5EEFDEEDC372725C7C7F22ED /* EdgeEverApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9CEA2902CDE0D7C4137D173 /* EdgeEverApp.swift */; };5F5EC9565A02FAFDD5D7B54C /* SyncProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 12236E3A2F318CDEB17B80CB /* SyncProtocol.swift */; };63D4B562B4EF6ED7291155F6 /* TemplatePickerSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9BA3D6859C4C6D9F65435671 /* TemplatePickerSheet.swift */; };6A671BB702DA77A0548E6E29 /* URL+Normalize.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A8662720DE42695E29F5741 /* URL+Normalize.swift */; };+ 6B2D55E0EA4D28EB7171A565 /* SystemImagePicker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17A2092411EFC3765B97DF88 /* SystemImagePicker.swift */; };7BDAD91E69B7B62D7D390CB5 /* MemoEditView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3674473015F8EB6863B69B0F /* MemoEditView.swift */; };8430B1EDE6CA87A0C922E484 /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1D94BB61519CA2A345D99C1 /* SettingsView.swift */; };8785D0133655387F399C3C58 /* LocalMirrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2035E878FD92B74D889D6047 /* LocalMirrorTests.swift */; };@@ -111,6 +113,7 @@12236E3A2F318CDEB17B80CB /* SyncProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SyncProtocol.swift; sourceTree = "<group>"; };12DCA98C14CC6F28C22C41A1 /* TipTapWebView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TipTapWebView.swift; sourceTree = "<group>"; };1606EF8ADEA4921421EB0690 /* MobileUIParityTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MobileUIParityTests.swift; sourceTree = "<group>"; };+ 17A2092411EFC3765B97DF88 /* SystemImagePicker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SystemImagePicker.swift; sourceTree = "<group>"; };1CD75D20D94A27E982103AB3 /* EdgeEver.app */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.application; path = EdgeEver.app; sourceTree = BUILT_PRODUCTS_DIR; };2035E878FD92B74D889D6047 /* LocalMirrorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocalMirrorTests.swift; sourceTree = "<group>"; };213837D2B2F025307A5EBB69 /* ChromeParityTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChromeParityTests.swift; sourceTree = "<group>"; };@@ -170,6 +173,7 @@E6159DBF27CC86920005E25D /* SyncProtocolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SyncProtocolTests.swift; sourceTree = "<group>"; };EA9305413739F81EA39395F7 /* ResourceBlobStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ResourceBlobStore.swift; sourceTree = "<group>"; };EFF10CDC8FB8C97DA0103AA0 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; path = PrivacyInfo.xcprivacy; sourceTree = "<group>"; };+ F01CF1D403DB46FB8784062E /* EditorContentCodec.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EditorContentCodec.swift; sourceTree = "<group>"; };F080AD98FDF3AADDD90B9931 /* ShareViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShareViewController.swift; sourceTree = "<group>"; };F1F36ACF8073C8A61AE397CD /* MemoTemplates.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MemoTemplates.swift; sourceTree = "<group>"; };F50D91D8505FE6446ABD647C /* WorkspaceView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkspaceView.swift; sourceTree = "<group>"; };@@ -422,8 +426,10 @@BEFB911E3106AB68356141B7 /* Editor */ = {isa = PBXGroup;children = (+ F01CF1D403DB46FB8784062E /* EditorContentCodec.swift */,F9182F742B06FB1713E27C2A /* ResourceActions.swift */,EA9305413739F81EA39395F7 /* ResourceBlobStore.swift */,+ 17A2092411EFC3765B97DF88 /* SystemImagePicker.swift */,AE1D4EB4B51C66E9CD72FF7F /* TipTapContentSource.swift */,36831A94478123A1EE9BB538 /* TipTapWarmPool.swift */,12DCA98C14CC6F28C22C41A1 /* TipTapWebView.swift */,@@ -621,6 +627,7 @@9CBE3E1196B24C4DDFC7CD0A /* DraftRepository.swift in Sources */,5EEFDEEDC372725C7C7F22ED /* EdgeEverApp.swift in Sources */,8C761DABADB93F2F15E21E80 /* EditFabButton.swift in Sources */,+ 5724B9A66EC1AE14D4C48F8B /* EditorContentCodec.swift in Sources */,B13CF9D8320DF366EA58601F /* ImageCompressor.swift in Sources */,132BA05FF9673B95D3E3959A /* JSONCoding.swift in Sources */,BBFC2539859878814E2F7197 /* KeychainStore.swift in Sources */,@@ -648,6 +655,7 @@35AAF7A2B1B4D5EE38F8518C /* SyncEngine.swift in Sources */,2E185C3C27DA3A729F2734B4 /* SyncOutboxRepository.swift in Sources */,5F5EC9565A02FAFDD5D7B54C /* SyncProtocol.swift in Sources */,+ 6B2D55E0EA4D28EB7171A565 /* SystemImagePicker.swift in Sources */,63D4B562B4EF6ED7291155F6 /* TemplatePickerSheet.swift in Sources */,4A2DD0673B81D32FA9E5F9DB /* Theme.swift in Sources */,265DB48114144779A7C807F7 /* TipTapContentSource.swift in Sources */,diff --git a/apps/ios/EdgeEver/Editor/EditorContentCodec.swift b/apps/ios/EdgeEver/Editor/EditorContentCodec.swiftnew file mode 100644index 00000000..e340be83--- /dev/null+++ b/apps/ios/EdgeEver/Editor/EditorContentCodec.swift@@ -0,0 +1,224 @@+import Foundation++// MARK: - TipTap content helpers (native Markdown serializer is recovery-only)++enum EditorContentCodec {+ /// TipTap's Markdown extension is authoritative because it understands the complete+ /// registered schema (tables, nested/ordered lists, code languages, links and images).+ /// The native serializer remains only as a recovery path for an absent bridge payload.+ static func preferredMarkdown(+ editorMarkdown: String?,+ documentJSON: String,+ fallback: String+ ) -> String {+ // A present-but-empty payload means the user intentionally cleared the note.+ if let editorMarkdown {+ return editorMarkdown+ }+ if !fallback.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+ return fallback+ }+ return markdownFromTipTapJSON(documentJSON) ?? ""+ }++ static func protectedResourceRefs(in text: String) -> [String] {+ guard let regex = try? NSRegularExpression(+ pattern: #"/api/v1/resources/[A-Za-z0-9_-]+(?:/blob)?"#,+ options: []+ ) else { return [] }+ let ns = text as NSString+ let matches = regex.matches(in: text, options: [], range: NSRange(location: 0, length: ns.length))+ var seen = Set<String>()+ var refs: [String] = []+ for match in matches {+ let ref = ns.substring(with: match.range)+ if seen.insert(ref).inserted { refs.append(ref) }+ }+ return refs+ }++ static func looksLikeTipTapDoc(_ json: String) -> Bool {+ guard let data = json.data(using: .utf8),+ let doc = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let type = doc["type"] as? String+ else { return false }+ return type == "doc"+ }++ static func containsImageNode(_ json: String) -> Bool {+ json.contains("\"type\":\"image\"") || json.contains("\"type\": \"image\"")+ }++ /// Match resource by id so `/blob` vs bare path doesn't look like a missing image.+ static func jsonContainsResource(_ json: String, src: String) -> Bool {+ if json.contains(src) { return true }+ if let id = ResourceCache.resourceId(from: src), json.contains(id) {+ return true+ }+ return false+ }++ static func plainText(markdown: String, json: String) -> String {+ let a = plainTextFromMarkdown(markdown)+ let b = plainTextFromJSON(json)+ return a.count >= b.count ? a : b+ }++ static func plainTextFromMarkdown(_ markdown: String) -> String {+ var s = markdown+ // Strip image / link targets; keep link labels lightly.+ s = s.replacingOccurrences(of: #"!\[[^\]]*\]\([^)]*\)"#, with: " ", options: .regularExpression)+ s = s.replacingOccurrences(of: #"\[[^\]]*\]\([^)]*\)"#, with: " ", options: .regularExpression)+ s = s.replacingOccurrences(of: #"[#>*`_~\-]+"#, with: " ", options: .regularExpression)+ return s+ .components(separatedBy: .whitespacesAndNewlines)+ .filter { !$0.isEmpty }+ .joined(separator: " ")+ }++ static func plainTextFromJSON(_ json: String) -> String {+ guard let data = json.data(using: .utf8),+ let obj = try? JSONSerialization.jsonObject(with: data)+ else { return "" }+ var parts: [String] = []+ collectText(obj, into: &parts)+ return parts.joined(separator: " ")+ }++ private static func collectText(_ any: Any, into parts: inout [String]) {+ if let dict = any as? [String: Any] {+ if let type = dict["type"] as? String, type == "text", let text = dict["text"] as? String, !text.isEmpty {+ parts.append(text)+ }+ if let content = dict["content"] as? [Any] {+ for child in content { collectText(child, into: &parts) }+ }+ return+ }+ if let arr = any as? [Any] {+ for child in arr { collectText(child, into: &parts) }+ }+ }++ /// Best-effort TipTap JSON → markdown so sync wire format keeps body text + images.+ static func markdownFromTipTapJSON(_ json: String) -> String? {+ guard let data = json.data(using: .utf8),+ let doc = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let content = doc["content"] as? [Any]+ else { return nil }+ var lines: [String] = []+ for node in content {+ guard let dict = node as? [String: Any], let type = dict["type"] as? String else { continue }+ switch type {+ case "paragraph":+ lines.append(inlineMarkdown(dict["content"] as? [Any] ?? []))+ case "heading":+ let level = (dict["attrs"] as? [String: Any])?["level"] as? Int ?? 2+ let prefix = String(repeating: "#", count: min(max(level, 1), 6))+ lines.append("\(prefix) \(inlineMarkdown(dict["content"] as? [Any] ?? []))")+ case "image":+ let attrs = dict["attrs"] as? [String: Any] ?? [:]+ let src = attrs["src"] as? String ?? ""+ let alt = attrs["alt"] as? String ?? ""+ if !src.isEmpty { lines.append(")") }+ case "bulletList", "orderedList":+ if let items = dict["content"] as? [Any] {+ for item in items {+ guard let itemDict = item as? [String: Any] else { continue }+ let text = blockText(itemDict)+ if !text.isEmpty { lines.append("- \(text)") }+ }+ }+ case "blockquote":+ let text = blockText(dict)+ if !text.isEmpty { lines.append("> \(text)") }+ case "codeBlock":+ let text = blockText(dict)+ lines.append("```\n\(text)\n```")+ case "horizontalRule":+ lines.append("---")+ default:+ let text = blockText(dict)+ if !text.isEmpty { lines.append(text) }+ }+ }+ let joined = lines.joined(separator: "\n\n").trimmingCharacters(in: .whitespacesAndNewlines)+ return joined.isEmpty ? nil : joined + "\n"+ }++ private static func blockText(_ node: [String: Any]) -> String {+ if let type = node["type"] as? String, type == "text" {+ return node["text"] as? String ?? ""+ }+ guard let content = node["content"] as? [Any] else { return "" }+ return content.compactMap { child -> String? in+ guard let dict = child as? [String: Any] else { return nil }+ if dict["type"] as? String == "image" {+ let attrs = dict["attrs"] as? [String: Any] ?? [:]+ let src = attrs["src"] as? String ?? ""+ let alt = attrs["alt"] as? String ?? ""+ return src.isEmpty ? nil : ")"+ }+ let t = blockText(dict)+ return t.isEmpty ? nil : t+ }.joined()+ }++ private static func inlineMarkdown(_ content: [Any]) -> String {+ content.compactMap { child -> String? in+ guard let dict = child as? [String: Any] else { return nil }+ if dict["type"] as? String == "hardBreak" { return "\n" }+ if dict["type"] as? String == "text" {+ var t = dict["text"] as? String ?? ""+ let marks = dict["marks"] as? [[String: Any]] ?? []+ // Apply outer marks last so **`code`** style nesting is reasonable.+ for mark in marks.reversed() {+ switch mark["type"] as? String {+ case "code":+ t = "`\(t)`"+ case "bold", "strong":+ t = "**\(t)**"+ case "italic", "em":+ t = "*\(t)*"+ case "strike":+ t = "~~\(t)~~"+ case "link":+ let href = (mark["attrs"] as? [String: Any])?["href"] as? String ?? ""+ t = "[\(t)](\(href))"+ default:+ break+ }+ }+ return t+ }+ return blockText(dict)+ }.joined()+ }++ /// Append image node without wiping existing document content.+ static func appendingImage(toJSON json: String, src: String, alt: String) -> String {+ if json.contains(src) { return json }+ guard let data = json.data(using: .utf8),+ var doc = try? JSONSerialization.jsonObject(with: data) as? [String: Any]+ else {+ // Only invent a stub when we truly have no document yet.+ let safeAlt = alt.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"")+ return """+ {"type":"doc","content":[{"type":"paragraph"},{"type":"image","attrs":{"src":"\(src)","alt":"\(safeAlt)"}},{"type":"paragraph"}]}+ """+ }+ var content = doc["content"] as? [[String: Any]] ?? []+ // Avoid blanking a doc that already has text — only append.+ content.append([+ "type": "image",+ "attrs": ["src": src, "alt": alt] as [String: Any],+ ])+ content.append(["type": "paragraph"] as [String: Any])+ doc["type"] = doc["type"] ?? "doc"+ doc["content"] = content+ guard let out = try? JSONSerialization.data(withJSONObject: doc),+ let s = String(data: out, encoding: .utf8)+ else { return json }+ return s+ }+}diff --git a/apps/ios/EdgeEver/Editor/SystemImagePicker.swift b/apps/ios/EdgeEver/Editor/SystemImagePicker.swiftnew file mode 100644index 00000000..658c3386--- /dev/null+++ b/apps/ios/EdgeEver/Editor/SystemImagePicker.swift@@ -0,0 +1,141 @@+import PhotosUI+import SwiftUI+import UIKit+import UniformTypeIdentifiers++// MARK: - System PHPicker++enum ImagePickerResult {+ case cancelled+ case failed(String)+ case picked(Data, filename: String)+}++/// UIKit PHPicker wrapper — loads UIImage/data via NSItemProvider (not Transferable).+struct SystemImagePicker: UIViewControllerRepresentable {+ var onFinish: (ImagePickerResult) -> Void++ func makeUIViewController(context: Context) -> PHPickerViewController {+ var config = PHPickerConfiguration(photoLibrary: .shared())+ config.filter = .images+ config.selectionLimit = 1+ config.preferredAssetRepresentationMode = .current+ let picker = PHPickerViewController(configuration: config)+ picker.delegate = context.coordinator+ return picker+ }++ func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) {}++ func makeCoordinator() -> Coordinator {+ Coordinator(onFinish: onFinish)+ }++ final class Coordinator: NSObject, PHPickerViewControllerDelegate {+ let onFinish: (ImagePickerResult) -> Void+ private var settled = false++ init(onFinish: @escaping (ImagePickerResult) -> Void) {+ self.onFinish = onFinish+ }++ func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {+ guard !settled else { return }+ guard let provider = results.first?.itemProvider else {+ settled = true+ DispatchQueue.main.async { self.onFinish(.cancelled) }+ return+ }+ Task {+ do {+ let (data, name) = try await Self.loadImage(from: provider)+ await MainActor.run {+ guard !self.settled else { return }+ self.settled = true+ self.onFinish(.picked(data, filename: name))+ }+ } catch {+ await MainActor.run {+ guard !self.settled else { return }+ self.settled = true+ self.onFinish(.failed(error.localizedDescription))+ }+ }+ }+ }++ private static func loadImage(from provider: NSItemProvider) async throws -> (Data, String) {+ // 1) UIImage path — most reliable for Photos library assets.+ if provider.canLoadObject(ofClass: UIImage.self) {+ let image = try await withCheckedThrowingContinuation { (cont: CheckedContinuation<UIImage, Error>) in+ provider.loadObject(ofClass: UIImage.self) { object, error in+ if let image = object as? UIImage {+ cont.resume(returning: image)+ } else {+ cont.resume(+ throwing: error+ ?? APIError(status: 0, code: nil, message: "无法解码图片")+ )+ }+ }+ }+ if let data = image.jpegData(compressionQuality: 0.92), !data.isEmpty {+ return (data, "image.jpg")+ }+ }++ // 2) Typed data representations.+ let typeIds = [+ UTType.jpeg.identifier,+ UTType.png.identifier,+ UTType.heic.identifier,+ UTType.image.identifier,+ ]+ for typeId in typeIds where provider.hasItemConformingToTypeIdentifier(typeId) {+ if let data = try? await loadData(provider, typeIdentifier: typeId), !data.isEmpty {+ let normalized = ImagePickerData.normalize(data)+ let mime = TipTapResourceLoader.sniffImageMime(normalized)+ let ext = mime == "image/png" ? "png" : "jpg"+ return (normalized, "image.\(ext)")+ }+ }++ throw APIError(status: 0, code: nil, message: "无法读取所选图片,请换一张重试。")+ }++ private static func loadData(_ provider: NSItemProvider, typeIdentifier: String) async throws -> Data {+ try await withCheckedThrowingContinuation { cont in+ provider.loadDataRepresentation(forTypeIdentifier: typeIdentifier) { data, error in+ if let data {+ cont.resume(returning: data)+ } else {+ cont.resume(+ throwing: error+ ?? APIError(status: 0, code: nil, message: "读取图片数据失败")+ )+ }+ }+ }+ }+ }+}++enum ImagePickerData {+ /// HEIC / unknown → JPEG so upload mime is valid and ImageCompressor can decode.+ static func normalize(_ data: Data) -> Data {+ if data.starts(with: [0xFF, 0xD8, 0xFF]) { return data } // JPEG+ if data.starts(with: [0x89, 0x50, 0x4E, 0x47]) { return data } // PNG+ if data.starts(with: [0x47, 0x49, 0x46, 0x38]) { return data } // GIF+ if data.count >= 12 {+ let riff = data.prefix(4)+ let webp = data.dropFirst(8).prefix(4)+ if riff.elementsEqual([0x52, 0x49, 0x46, 0x46]), webp.elementsEqual([0x57, 0x45, 0x42, 0x50]) {+ return data+ }+ }+ if let image = UIImage(data: data), let jpeg = image.jpegData(compressionQuality: 0.92) {+ return jpeg+ }+ return data+ }+}diff --git a/apps/ios/EdgeEver/Features/Workspace/MemoEditView.swift b/apps/ios/EdgeEver/Features/Workspace/MemoEditView.swiftindex 1a092bed..e1fbe8dd 100644--- a/apps/ios/EdgeEver/Features/Workspace/MemoEditView.swift+++ b/apps/ios/EdgeEver/Features/Workspace/MemoEditView.swift@@ -1,7 +1,4 @@-import PhotosUIimport SwiftUI-import UIKit-import UniformTypeIdentifiersenum MemoEditMode: Equatable {/// `seed` pre-fills title/body/tags (template / clip-style create). When nil, restores local new-note draft.@@ -1098,365 +1095,6 @@ struct MemoEditView: View {}}-// MARK: - TipTap content helpers (native Markdown serializer is recovery-only)--enum EditorContentCodec {- /// TipTap's Markdown extension is authoritative because it understands the complete- /// registered schema (tables, nested/ordered lists, code languages, links and images).- /// The native serializer remains only as a recovery path for an absent bridge payload.- static func preferredMarkdown(- editorMarkdown: String?,- documentJSON: String,- fallback: String- ) -> String {- // A present-but-empty payload means the user intentionally cleared the note.- if let editorMarkdown {- return editorMarkdown- }- if !fallback.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {- return fallback- }- return markdownFromTipTapJSON(documentJSON) ?? ""- }-- static func protectedResourceRefs(in text: String) -> [String] {- guard let regex = try? NSRegularExpression(- pattern: #"/api/v1/resources/[A-Za-z0-9_-]+(?:/blob)?"#,- options: []- ) else { return [] }- let ns = text as NSString- let matches = regex.matches(in: text, options: [], range: NSRange(location: 0, length: ns.length))- var seen = Set<String>()- var refs: [String] = []- for match in matches {- let ref = ns.substring(with: match.range)- if seen.insert(ref).inserted { refs.append(ref) }- }- return refs- }-- static func looksLikeTipTapDoc(_ json: String) -> Bool {- guard let data = json.data(using: .utf8),- let doc = try? JSONSerialization.jsonObject(with: data) as? [String: Any],- let type = doc["type"] as? String- else { return false }- return type == "doc"- }-- static func containsImageNode(_ json: String) -> Bool {- json.contains("\"type\":\"image\"") || json.contains("\"type\": \"image\"")- }-- /// Match resource by id so `/blob` vs bare path doesn't look like a missing image.- static func jsonContainsResource(_ json: String, src: String) -> Bool {- if json.contains(src) { return true }- if let id = ResourceCache.resourceId(from: src), json.contains(id) {- return true- }- return false- }-- static func plainText(markdown: String, json: String) -> String {- let a = plainTextFromMarkdown(markdown)- let b = plainTextFromJSON(json)- return a.count >= b.count ? a : b- }-- static func plainTextFromMarkdown(_ markdown: String) -> String {- var s = markdown- // Strip image / link targets; keep link labels lightly.- s = s.replacingOccurrences(of: #"!\[[^\]]*\]\([^)]*\)"#, with: " ", options: .regularExpression)- s = s.replacingOccurrences(of: #"\[[^\]]*\]\([^)]*\)"#, with: " ", options: .regularExpression)- s = s.replacingOccurrences(of: #"[#>*`_~\-]+"#, with: " ", options: .regularExpression)- return s- .components(separatedBy: .whitespacesAndNewlines)- .filter { !$0.isEmpty }- .joined(separator: " ")- }-- static func plainTextFromJSON(_ json: String) -> String {- guard let data = json.data(using: .utf8),- let obj = try? JSONSerialization.jsonObject(with: data)- else { return "" }- var parts: [String] = []- collectText(obj, into: &parts)- return parts.joined(separator: " ")- }-- private static func collectText(_ any: Any, into parts: inout [String]) {- if let dict = any as? [String: Any] {- if let type = dict["type"] as? String, type == "text", let text = dict["text"] as? String, !text.isEmpty {- parts.append(text)- }- if let content = dict["content"] as? [Any] {- for child in content { collectText(child, into: &parts) }- }- return- }- if let arr = any as? [Any] {- for child in arr { collectText(child, into: &parts) }- }- }-- /// Best-effort TipTap JSON → markdown so sync wire format keeps body text + images.- static func markdownFromTipTapJSON(_ json: String) -> String? {- guard let data = json.data(using: .utf8),- let doc = try? JSONSerialization.jsonObject(with: data) as? [String: Any],- let content = doc["content"] as? [Any]- else { return nil }- var lines: [String] = []- for node in content {- guard let dict = node as? [String: Any], let type = dict["type"] as? String else { continue }- switch type {- case "paragraph":- lines.append(inlineMarkdown(dict["content"] as? [Any] ?? []))- case "heading":- let level = (dict["attrs"] as? [String: Any])?["level"] as? Int ?? 2- let prefix = String(repeating: "#", count: min(max(level, 1), 6))- lines.append("\(prefix) \(inlineMarkdown(dict["content"] as? [Any] ?? []))")- case "image":- let attrs = dict["attrs"] as? [String: Any] ?? [:]- let src = attrs["src"] as? String ?? ""- let alt = attrs["alt"] as? String ?? ""- if !src.isEmpty { lines.append(")") }- case "bulletList", "orderedList":- if let items = dict["content"] as? [Any] {- for item in items {- guard let itemDict = item as? [String: Any] else { continue }- let text = blockText(itemDict)- if !text.isEmpty { lines.append("- \(text)") }- }- }- case "blockquote":- let text = blockText(dict)- if !text.isEmpty { lines.append("> \(text)") }- case "codeBlock":- let text = blockText(dict)- lines.append("```\n\(text)\n```")- case "horizontalRule":- lines.append("---")- default:- let text = blockText(dict)- if !text.isEmpty { lines.append(text) }- }- }- let joined = lines.joined(separator: "\n\n").trimmingCharacters(in: .whitespacesAndNewlines)- return joined.isEmpty ? nil : joined + "\n"- }-- private static func blockText(_ node: [String: Any]) -> String {- if let type = node["type"] as? String, type == "text" {- return node["text"] as? String ?? ""- }- guard let content = node["content"] as? [Any] else { return "" }- return content.compactMap { child -> String? in- guard let dict = child as? [String: Any] else { return nil }- if dict["type"] as? String == "image" {- let attrs = dict["attrs"] as? [String: Any] ?? [:]- let src = attrs["src"] as? String ?? ""- let alt = attrs["alt"] as? String ?? ""- return src.isEmpty ? nil : ")"- }- let t = blockText(dict)- return t.isEmpty ? nil : t- }.joined()- }-- private static func inlineMarkdown(_ content: [Any]) -> String {- content.compactMap { child -> String? in- guard let dict = child as? [String: Any] else { return nil }- if dict["type"] as? String == "hardBreak" { return "\n" }- if dict["type"] as? String == "text" {- var t = dict["text"] as? String ?? ""- let marks = dict["marks"] as? [[String: Any]] ?? []- // Apply outer marks last so **`code`** style nesting is reasonable.- for mark in marks.reversed() {- switch mark["type"] as? String {- case "code":- t = "`\(t)`"- case "bold", "strong":- t = "**\(t)**"- case "italic", "em":- t = "*\(t)*"- case "strike":- t = "~~\(t)~~"- case "link":- let href = (mark["attrs"] as? [String: Any])?["href"] as? String ?? ""- t = "[\(t)](\(href))"- default:- break- }- }- return t- }- return blockText(dict)- }.joined()- }-- /// Append image node without wiping existing document content.- static func appendingImage(toJSON json: String, src: String, alt: String) -> String {- if json.contains(src) { return json }- guard let data = json.data(using: .utf8),- var doc = try? JSONSerialization.jsonObject(with: data) as? [String: Any]- else {- // Only invent a stub when we truly have no document yet.- let safeAlt = alt.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"")- return """- {"type":"doc","content":[{"type":"paragraph"},{"type":"image","attrs":{"src":"\(src)","alt":"\(safeAlt)"}},{"type":"paragraph"}]}- """- }- var content = doc["content"] as? [[String: Any]] ?? []- // Avoid blanking a doc that already has text — only append.- content.append([- "type": "image",- "attrs": ["src": src, "alt": alt] as [String: Any],- ])- content.append(["type": "paragraph"] as [String: Any])- doc["type"] = doc["type"] ?? "doc"- doc["content"] = content- guard let out = try? JSONSerialization.data(withJSONObject: doc),- let s = String(data: out, encoding: .utf8)- else { return json }- return s- }-}--// MARK: - System PHPicker (reliable; PhotosPicker+Transferable was a silent no-op)--private enum ImagePickerResult {- case cancelled- case failed(String)- case picked(Data, filename: String)-}--/// UIKit PHPicker wrapper — loads UIImage/data via NSItemProvider (not Transferable).-private struct SystemImagePicker: UIViewControllerRepresentable {- var onFinish: (ImagePickerResult) -> Void-- func makeUIViewController(context: Context) -> PHPickerViewController {- var config = PHPickerConfiguration(photoLibrary: .shared())- config.filter = .images- config.selectionLimit = 1- config.preferredAssetRepresentationMode = .current- let picker = PHPickerViewController(configuration: config)- picker.delegate = context.coordinator- return picker- }-- func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) {}-- func makeCoordinator() -> Coordinator {- Coordinator(onFinish: onFinish)- }-- final class Coordinator: NSObject, PHPickerViewControllerDelegate {- let onFinish: (ImagePickerResult) -> Void- private var settled = false-- init(onFinish: @escaping (ImagePickerResult) -> Void) {- self.onFinish = onFinish- }-- func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {- guard !settled else { return }- guard let provider = results.first?.itemProvider else {- settled = true- DispatchQueue.main.async { self.onFinish(.cancelled) }- return- }- Task {- do {- let (data, name) = try await Self.loadImage(from: provider)- await MainActor.run {- guard !self.settled else { return }- self.settled = true- self.onFinish(.picked(data, filename: name))- }- } catch {- await MainActor.run {- guard !self.settled else { return }- self.settled = true- self.onFinish(.failed(error.localizedDescription))- }- }- }- }-- private static func loadImage(from provider: NSItemProvider) async throws -> (Data, String) {- // 1) UIImage path — most reliable for Photos library assets.- if provider.canLoadObject(ofClass: UIImage.self) {- let image = try await withCheckedThrowingContinuation { (cont: CheckedContinuation<UIImage, Error>) in- provider.loadObject(ofClass: UIImage.self) { object, error in- if let image = object as? UIImage {- cont.resume(returning: image)- } else {- cont.resume(- throwing: error- ?? APIError(status: 0, code: nil, message: "无法解码图片")- )- }- }- }- if let data = image.jpegData(compressionQuality: 0.92), !data.isEmpty {- return (data, "image.jpg")- }- }-- // 2) Typed data representations.- let typeIds = [- UTType.jpeg.identifier,- UTType.png.identifier,- UTType.heic.identifier,- UTType.image.identifier,- ]- for typeId in typeIds where provider.hasItemConformingToTypeIdentifier(typeId) {- if let data = try? await loadData(provider, typeIdentifier: typeId), !data.isEmpty {- let normalized = ImagePickerData.normalize(data)- let mime = TipTapResourceLoader.sniffImageMime(normalized)- let ext = mime == "image/png" ? "png" : "jpg"- return (normalized, "image.\(ext)")- }- }-- throw APIError(status: 0, code: nil, message: "无法读取所选图片,请换一张重试。")- }-- private static func loadData(_ provider: NSItemProvider, typeIdentifier: String) async throws -> Data {- try await withCheckedThrowingContinuation { cont in- provider.loadDataRepresentation(forTypeIdentifier: typeIdentifier) { data, error in- if let data {- cont.resume(returning: data)- } else {- cont.resume(- throwing: error- ?? APIError(status: 0, code: nil, message: "读取图片数据失败")- )- }- }- }- }- }-}--enum ImagePickerData {- /// HEIC / unknown → JPEG so upload mime is valid and ImageCompressor can decode.- static func normalize(_ data: Data) -> Data {- if data.starts(with: [0xFF, 0xD8, 0xFF]) { return data } // JPEG- if data.starts(with: [0x89, 0x50, 0x4E, 0x47]) { return data } // PNG- if data.starts(with: [0x47, 0x49, 0x46, 0x38]) { return data } // GIF- if data.count >= 12 {- let riff = data.prefix(4)- let webp = data.dropFirst(8).prefix(4)- if riff.elementsEqual([0x52, 0x49, 0x46, 0x46]), webp.elementsEqual([0x57, 0x45, 0x42, 0x50]) {- return data- }- }- if let image = UIImage(data: data), let jpeg = image.jpegData(compressionQuality: 0.92) {- return jpeg- }- return data- }-}// MARK: - Compact notebook picker for create/editdiff --git a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx b/apps/mobile/src/screens/WorkspaceMemoDetail.tsxindex d6b46fd1..2dd5780b 100644--- a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx+++ b/apps/mobile/src/screens/WorkspaceMemoDetail.tsx@@ -1,5 +1,5 @@import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";-import { resolveMemoContentDoc, type MemoDetail, type TiptapDoc } from "@edgeever/shared";+import { DEFAULT_MEMO_TITLE, resolveMemoContentDoc, type MemoDetail, type TiptapDoc } from "@edgeever/shared";import { ActivityIndicator, Image as RNImage, Platform, StyleSheet, View, type ImageStyle, type StyleProp } from "react-native";import { Modal } from "react-native";import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context";@@ -31,7 +31,6 @@ import type { MobileSyncQueueItem } from "../lib/sync-queue";import { styles } from "./workspace-styles";const ANDROID_SYSTEM_NAVIGATION_FALLBACK = 48;-const DEFAULT_MEMO_TITLE = "无标题笔记";const RESOURCE_DATA_URL_CACHE_LIMIT = 32;type SessionLike = { baseUrl: string; token: string } | null;diff --git a/apps/mobile/src/screens/WorkspaceNotesView.tsx b/apps/mobile/src/screens/WorkspaceNotesView.tsxindex 62c961c1..715ba84a 100644--- a/apps/mobile/src/screens/WorkspaceNotesView.tsx+++ b/apps/mobile/src/screens/WorkspaceNotesView.tsx@@ -1,6 +1,6 @@import { memo, type ReactNode } from "react";import type { MemoFilterMode } from "@edgeever/client";-import type { MemoSummary, Notebook } from "@edgeever/shared";+import { DEFAULT_MEMO_TITLE, type MemoSummary, type Notebook } from "@edgeever/shared";import { MOBILE_UI_METRICS, toggleMobileMemoFilterMode } from "@edgeever/shared/mobile-ui";import { ActivityIndicator, FlatList, Platform, RefreshControl, View } from "react-native";import Animated, { useAnimatedStyle, useSharedValue, withTiming } from "react-native-reanimated";@@ -13,7 +13,6 @@ import type { MobileMemoListDensity } from "../lib/preferences";import { formatMemoPreviewDate } from "./workspace-utils";import { styles } from "./workspace-styles";-const DEFAULT_MEMO_TITLE = "无标题笔记";type MemoView = "notebook" | "trash";export const NotesView = ({diff --git a/apps/mobile/src/screens/WorkspaceScreen.tsx b/apps/mobile/src/screens/WorkspaceScreen.tsxindex e3f90bda..16d8eea1 100644--- a/apps/mobile/src/screens/WorkspaceScreen.tsx+++ b/apps/mobile/src/screens/WorkspaceScreen.tsx@@ -69,7 +69,7 @@ import { Alert, Pressable, Text, TextInput } from "../components/LocalizedText";import Markdown, { type ASTNode, type RenderRules } from "react-native-markdown-display";import { SvgXml } from "react-native-svg";import { ApiRequestError } from "@edgeever/client";-import { buildGitHubFeedbackUrl, createExcerpt, docToMarkdown, docToText, getNotebookDescendantIds, markdownToDoc, resolveMemoContentDoc, type AuthUser, type MemoDetail, type MemoRevision, type MemoSummary, type Notebook, type TiptapDoc } from "@edgeever/shared";+import { buildGitHubFeedbackUrl, createExcerpt, DEFAULT_MEMO_TITLE, docToMarkdown, docToText, getNotebookDescendantIds, markdownToDoc, resolveMemoContentDoc, type AuthUser, type MemoDetail, type MemoRevision, type MemoSummary, type Notebook, type TiptapDoc } from "@edgeever/shared";import { MOBILE_UI_METRICS, getMobileCenteredScrollOffset, getMobileNotebookSearchVisibleIds, toggleMobileMemoFilterMode, toggleMobileMemoSelection } from "@edgeever/shared/mobile-ui";import { clearMobileMemoDraft, clearMobileNewMemoDraft, readMobileMemoDraft, readMobileNewMemoDraft, writeMobileMemoDraft, writeMobileNewMemoDraft, type MobileMemoDraft } from "../lib/mobile-drafts";import {@@ -177,7 +177,6 @@ import {} from "../lib/mobile-protected-resources";const ALL_NOTES_ID = "all";-const DEFAULT_MEMO_TITLE = "无标题笔记";const ANDROID_SYSTEM_NAVIGATION_FALLBACK = 48;const DETAIL_CONTENT_HORIZONTAL_PADDING = 16;const DETAIL_TABLE_FIT_COLUMN_COUNT = 3;diff --git a/apps/mobile/src/screens/workspace-utils.ts b/apps/mobile/src/screens/workspace-utils.tsindex 38dc455c..e959f426 100644--- a/apps/mobile/src/screens/workspace-utils.ts+++ b/apps/mobile/src/screens/workspace-utils.ts@@ -1,4 +1,4 @@-import type { MemoSummary, Notebook } from "@edgeever/shared";+import { DEFAULT_MEMO_TITLE, type MemoSummary, type Notebook } from "@edgeever/shared";import type { MobileLocalePreference } from "../lib/preferences";export type NotebookOption = {@@ -147,7 +147,7 @@ export const formatMemoPreviewDate = (value: string, localePreference: MobileLocexport const sortMemoSummaries = (memos: MemoSummary[], sortMode: unknown) =>[...memos].sort((left, right) => {if (sortMode === "title-asc") {- return (left.title || "无标题笔记").localeCompare(right.title || "无标题笔记");+ return (left.title || DEFAULT_MEMO_TITLE).localeCompare(right.title || DEFAULT_MEMO_TITLE);}if (sortMode === "created-desc") {return right.createdAt.localeCompare(left.createdAt);