diff --git a/client/components/plainleaf_workspace.test.ts b/client/components/plainleaf_workspace.test.ts index 1708c2fb..17f250c4 100644 --- a/client/components/plainleaf_workspace.test.ts +++ b/client/components/plainleaf_workspace.test.ts @@ -4,7 +4,11 @@ import { buildPageTree, collectPlainleafTags, pagesInPlainleafFolder, + plainleafDuplicatePageName, + plainleafFolderPaths, + plainleafFrontmatterTags, plainleafFolderExists, + isPlainleafFavoritePage, plainleafPageLabel, plainleafTaskReference, plainleafTaskTitle, @@ -92,6 +96,50 @@ test("distinguishes a same-named page from an existing folder", () => { ).toBe(false); }); +test("creates a non-conflicting Markdown copy beside the source page", () => { + const pages = [ + page("项目/计划"), + page("项目/计划 副本"), + page("项目/计划 副本 2"), + ]; + expect(plainleafDuplicatePageName("项目/计划", pages)).toBe( + "项目/计划 副本 3", + ); + expect(plainleafDuplicatePageName("根目录笔记", pages)).toBe( + "根目录笔记 副本", + ); +}); + +test("derives all nested destination folders from Markdown page paths", () => { + expect( + plainleafFolderPaths([ + page("工作/项目/计划"), + page("工作/记录"), + page("个人/日记"), + page("草稿/隐藏", { _isAspiring: true }), + ]), + ).toEqual(["个人", "工作", "工作/项目"]); +}); + +test("recognizes both supported favorite tags", () => { + expect(isPlainleafFavoritePage(page("A", { tags: ["favorite"] }))).toBe(true); + expect(isPlainleafFavoritePage(page("B", { tags: ["收藏"] }))).toBe(true); + expect(isPlainleafFavoritePage(page("C", { tags: ["读书"] }))).toBe(false); +}); + +test("reads only YAML frontmatter tags when updating favorites", () => { + expect( + plainleafFrontmatterTags( + "---\ntitle: 示例\ntags:\n - 工作\n - favorite\n---\n# 正文\n\n#不会写回YAML\n", + ), + ).toEqual(["工作", "favorite"]); + expect(plainleafFrontmatterTags("# 正文\n\n#favorite\n")).toEqual([]); + expect(plainleafFrontmatterTags("---\ntags: 工作, 收藏\n---\n正文")).toEqual([ + "工作", + "收藏", + ]); +}); + test("omits aspiring and decorated hidden pages", () => { const tree = buildPageTree([ page("Visible"), diff --git a/client/components/plainleaf_workspace.tsx b/client/components/plainleaf_workspace.tsx index 8d01f0c7..801f537b 100644 --- a/client/components/plainleaf_workspace.tsx +++ b/client/components/plainleaf_workspace.tsx @@ -1,6 +1,7 @@ import type { PageMeta } from "@silverbulletmd/silverbullet/type/index"; import type { ComponentChildren } from "preact"; import { useEffect, useMemo, useRef, useState } from "preact/hooks"; +import YAML from "js-yaml"; import { BookOpen, Bell, @@ -20,6 +21,7 @@ import { Compass, CornerUpLeft, CornerUpRight, + Copy, Download, Edit3, Eye, @@ -139,6 +141,20 @@ export type PlainleafFolderMutation = | { type: "rename"; folder: PageTreeFolder; path: string } | { type: "delete"; folder: PageTreeFolder }; +export type PlainleafPageAction = + | { type: "rename"; page: PageTreeFile } + | { type: "move"; page: PageTreeFile } + | { type: "duplicate"; page: PageTreeFile } + | { type: "delete"; page: PageTreeFile } + | { type: "favorite"; page: PageTreeFile; favorite: boolean }; + +export type PlainleafPageMutation = + | { type: "rename"; page: PageTreeFile; name: string } + | { type: "move"; page: PageTreeFile; name: string } + | { type: "duplicate"; page: PageTreeFile; name: string } + | { type: "delete"; page: PageTreeFile } + | { type: "favorite"; page: PageTreeFile; favorite: boolean }; + export function plainleafTaskReference(task: PlainleafTask): string { const ref = task.ref.trim(); if (ref.includes("@") || ref.includes("#") || ref.includes("$")) return ref; @@ -156,6 +172,7 @@ export type { PlainleafEditorAction } from "./plainleaf_markdown_toolbar.ts"; type PlainleafView = | "notes" + | "favorites" | "search" | "tasks" | "tags" @@ -251,6 +268,63 @@ export function plainleafPageLabel(name: string, indexPage = "index"): string { return systemLabels[segment] ?? segment; } +export function isPlainleafFavoritePage(page: PageMeta): boolean { + return (page.tags ?? []).some((tag) => + ["favorite", "收藏"].includes(tag.toLocaleLowerCase()), + ); +} + +export function plainleafFrontmatterTags(text: string): string[] { + const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/); + if (!match) return []; + try { + const data = YAML.load(match[1]); + if (!data || typeof data !== "object" || !("tags" in data)) return []; + const value = (data as { tags?: unknown }).tags; + const tags = Array.isArray(value) + ? value + : typeof value === "string" + ? value.split(/,\s*|\s+/) + : []; + return tags + .map((tag) => String(tag).replace(/^#/, "").trim()) + .filter(Boolean); + } catch { + return []; + } +} + +export function plainleafDuplicatePageName( + pageName: string, + allPages: PageMeta[], +): string { + const parts = pageName.split("/"); + const title = parts.pop() || pageName; + const folder = parts.join("/"); + const existing = new Set( + allPages.filter((page) => !page._isAspiring).map((page) => page.name), + ); + let suffix = 1; + let candidate = ""; + do { + const copyTitle = + suffix === 1 ? `${title} 副本` : `${title} 副本 ${suffix}`; + candidate = folder ? `${folder}/${copyTitle}` : copyTitle; + suffix += 1; + } while (existing.has(candidate)); + return candidate; +} + +export function plainleafFolderPaths(allPages: PageMeta[]): string[] { + const paths = new Set(); + for (const page of allPages) { + if (page._isAspiring) continue; + const parts = page.name.split("/").slice(0, -1); + parts.forEach((_, index) => paths.add(parts.slice(0, index + 1).join("/"))); + } + return [...paths].sort((a, b) => a.localeCompare(b, "zh-CN")); +} + export function pagesInPlainleafFolder( allPages: PageMeta[], folderPath: string, @@ -400,6 +474,7 @@ function PageTree({ onToggleFolder, onOpenPage, onFolderAction, + onPageAction, canManageFolders, depth = 0, }: { @@ -409,6 +484,7 @@ function PageTree({ onToggleFolder: (path: string) => void; onOpenPage: (page: string) => void; onFolderAction: (action: PlainleafFolderAction) => void; + onPageAction: (action: PlainleafPageAction) => void; canManageFolders: boolean; depth?: number; }) { @@ -416,19 +492,103 @@ function PageTree({
{nodes.map((node) => { if (node.kind === "page") { + const canManagePage = + canManageFolders && + node.meta.perm !== "ro" && + !isPlainleafSystemPage(node.meta); + const favorite = isPlainleafFavoritePage(node.meta); return ( - +
+ + {canManagePage && ( +
+ + + +
+ + + + + +
+
+ )} +
); } @@ -516,6 +676,7 @@ function PageTree({ onToggleFolder={onToggleFolder} onOpenPage={onOpenPage} onFolderAction={onFolderAction} + onPageAction={onPageAction} canManageFolders={canManageFolders} depth={depth + 1} /> @@ -1213,6 +1374,7 @@ export function PlainleafWorkspace({ darkMode, onOpenPage, onCreatePage, + onMutatePage, onMutateFolder, onLoadPreview, onOpenDaily, @@ -1244,6 +1406,7 @@ export function PlainleafWorkspace({ darkMode: boolean; onOpenPage: (page: string) => void; onCreatePage: (page: string) => Promise; + onMutatePage: (mutation: PlainleafPageMutation) => Promise; onMutateFolder: (mutation: PlainleafFolderMutation) => Promise; onLoadPreview: () => Promise; onOpenDaily: () => void; @@ -1368,6 +1531,10 @@ export function PlainleafWorkspace({ const [folderAction, setFolderAction] = useState(); const [folderName, setFolderName] = useState(""); const [folderBusy, setFolderBusy] = useState(false); + const [pageAction, setPageAction] = useState(); + const [pageTitle, setPageTitle] = useState(""); + const [pageFolder, setPageFolder] = useState(""); + const [pageBusy, setPageBusy] = useState(false); const [editorMode, setEditorMode] = useState("edit"); const [previewHtml, setPreviewHtml] = useState(""); const [previewLoading, setPreviewLoading] = useState(false); @@ -1855,6 +2022,87 @@ export function PlainleafWorkspace({ } }; + const runPageMutation = async ( + mutation: PlainleafPageMutation, + successMessage: string, + ) => { + setPageBusy(true); + try { + await onMutatePage(mutation); + setTaskNotice(successMessage); + setPageAction(undefined); + setMobileOpen(false); + } catch (error) { + setTaskError(error instanceof Error ? error.message : "笔记操作失败"); + } finally { + setPageBusy(false); + } + }; + + const openPageAction = (action: PlainleafPageAction) => { + if (action.type === "delete") { + if ( + !confirm( + `确定删除“${action.page.label}”吗?只会删除这篇 Markdown 笔记,此操作无法撤销。`, + ) + ) { + return; + } + void runPageMutation(action, `已删除“${action.page.label}”`); + return; + } + if (action.type === "favorite") { + void runPageMutation( + action, + action.favorite + ? `已收藏“${action.page.label}”` + : `已取消收藏“${action.page.label}”`, + ); + return; + } + if (action.type === "duplicate") { + const name = plainleafDuplicatePageName(action.page.name, allPages); + void runPageMutation( + { type: "duplicate", page: action.page, name }, + `已创建“${plainleafPageLabel(name, indexPage)}”`, + ); + return; + } + const parts = action.page.name.split("/"); + setPageTitle(parts.pop() || action.page.label); + setPageFolder(parts.join("/")); + setPageAction(action); + }; + + const submitPageAction = async () => { + if ( + !pageAction || + (pageAction.type !== "rename" && pageAction.type !== "move") + ) { + return; + } + const title = pageTitle.trim(); + if (!title || title.includes("/")) { + setTaskError("笔记标题不能为空,也不能包含斜杠"); + return; + } + const name = pageFolder ? `${pageFolder}/${title}` : title; + if (name === pageAction.page.name) { + setPageAction(undefined); + return; + } + if (allPages.some((page) => !page._isAspiring && page.name === name)) { + setTaskError("目标位置已经有同名笔记"); + return; + } + await runPageMutation( + { type: pageAction.type, page: pageAction.page, name }, + pageAction.type === "move" + ? `已移动“${pageAction.page.label}”` + : `已将笔记重命名为“${title}”`, + ); + }; + const openPage = (page: string) => { onOpenPage(page); setMobileOpen(false); @@ -1997,6 +2245,37 @@ export function PlainleafWorkspace({ ); const renderSidebarContent = () => { + if (view === "favorites") { + return ( + <> +
+ 收藏的笔记 + {favoritePages.length} 篇 +
+
+ {favoritePages.map((page) => ( + + ))} +
+ {favoritePages.length === 0 && ( +
+ + 还没有收藏 + 打开笔记右侧的菜单,即可收藏常用内容。 +
+ )} + + ); + } + if (view === "search") { return ( <> @@ -2243,7 +2522,7 @@ export function PlainleafWorkspace({ 最近编辑 {recentPages.length} -
)} + + {pageAction && ["rename", "move"].includes(pageAction.type) && ( +
{ + if (event.currentTarget === event.target && !pageBusy) { + setPageAction(undefined); + } + }} + > + +
+ )} ); } diff --git a/client/editor_ui.tsx b/client/editor_ui.tsx index c73aea58..7c0b76aa 100644 --- a/client/editor_ui.tsx +++ b/client/editor_ui.tsx @@ -7,6 +7,7 @@ import { PlainleafWorkspace, pagesInPlainleafFolder, plainleafFolderExists, + plainleafFrontmatterTags, plainleafPageLabel, plainleafTaskReference, visiblePlainleafPages, @@ -14,6 +15,7 @@ import { type PlainleafDeletedTaskBlock, type PlainleafFolderMutation, type PlainleafNewTask, + type PlainleafPageMutation, type PlainleafSearchResult, type PlainleafSearchScope, type PlainleafTask, @@ -577,6 +579,88 @@ export class MainUI { const ref = parseToRef(name); if (ref) await client.open(ref); }} + onMutatePage={async (mutation: PlainleafPageMutation) => { + const oldName = mutation.page.name; + if (mutation.type === "rename" || mutation.type === "move") { + if (!isValidName(mutation.name)) { + throw new Error("笔记标题或文件夹名称包含不能用于路径的字符"); + } + const existing = viewState.allPages.some( + (page) => + !page._isAspiring && + page.name === mutation.name && + page.name !== oldName, + ); + if (existing) throw new Error("目标位置已经有同名笔记"); + await client.save(true); + const renamed = await client.clientSystem.system.invokeFunction( + "index.renamePageCommand", + [{ oldPage: oldName, page: mutation.name }], + ); + if (renamed === false) throw new Error("笔记重命名失败"); + await client.mq.awaitEmptyQueue("indexQueue"); + await client.updatePageListCache(); + return; + } + + if (mutation.type === "duplicate") { + if (!isValidName(mutation.name)) { + throw new Error("副本名称包含不能用于路径的字符"); + } + await client.save(true); + const { text } = await client.space.readPage(oldName); + await client.space.writePage(mutation.name, text); + await client.mq.awaitEmptyQueue("indexQueue"); + await client.updatePageListCache(); + const ref = parseToRef(mutation.name); + if (ref) await client.open(ref); + return; + } + + if (mutation.type === "delete") { + await client.save(true); + if (client.currentName() === oldName) { + const ref = parseToRef(client.bootConfig.indexPage); + if (ref) await client.open(ref); + } + await client.space.deletePage(oldName); + await client.mq.awaitEmptyQueue("indexQueue"); + await client.updatePageListCache(); + return; + } + + await client.save(true); + const { text } = await client.space.readPage(oldName); + const withoutFavoriteTags = mutation.favorite + ? text + : ( + await client.clientSystem.system.invokeFunction( + "index.extractFrontmatter", + [text, { removeTags: ["favorite", "收藏"] }], + ) + ).text; + const tags = plainleafFrontmatterTags(withoutFavoriteTags).filter( + (tag) => !["favorite", "收藏"].includes(tag.toLocaleLowerCase()), + ); + if (mutation.favorite) tags.push("favorite"); + const patched = await client.clientSystem.system.invokeFunction( + "index.patchFrontmatter", + [ + withoutFavoriteTags, + [ + tags.length + ? { op: "set-key", path: "tags", value: tags } + : { op: "delete-key", path: "tags" }, + ], + ], + ); + await client.space.writePage(oldName, patched); + await client.mq.awaitEmptyQueue("indexQueue"); + await client.updatePageListCache(); + if (client.currentName() === oldName) { + await client.contentManager.reloadPageContent("favorite-change"); + } + }} onMutateFolder={async (mutation: PlainleafFolderMutation) => { if (mutation.type === "create") { const indexName = `${mutation.path}/首页`; diff --git a/client/styles/plainleaf_workspace.scss b/client/styles/plainleaf_workspace.scss index 3f4d279f..9534d0b8 100644 --- a/client/styles/plainleaf_workspace.scss +++ b/client/styles/plainleaf_workspace.scss @@ -452,13 +452,21 @@ html[data-skin="cloudleaf"] .pl-note-shortcuts button.is-active { background: var(--pl-green-soft); } -.pl-tree-folder-row { +.pl-tree-folder-row, +.pl-tree-page-row { display: grid; position: relative; grid-template-columns: minmax(0, 1fr) 28px; align-items: center; } +.pl-tree-page-row .pl-tree-favorite { + flex: 0 0 12px; + margin: 0 2px 0 6px; + color: var(--pl-gold, #b68225); + fill: currentColor; +} + html[data-skin="cloudleaf"] .pl-tree-folder > .pl-tree-folder-row::before { content: ""; position: absolute; @@ -508,6 +516,10 @@ html[data-skin="cloudleaf"] .pl-tree-folder > .pl-tree-folder-row::before { box-shadow: 0 12px 34px rgb(28 38 31 / 16%); } +.pl-page-actions > div { + width: 176px; +} + .pl-folder-actions > div > button { display: flex; align-items: center; diff --git a/client/styles/plainleaf_workspace.test.ts b/client/styles/plainleaf_workspace.test.ts index e08e69c9..b269d891 100644 --- a/client/styles/plainleaf_workspace.test.ts +++ b/client/styles/plainleaf_workspace.test.ts @@ -63,6 +63,12 @@ test("styles folder actions and the Markdown preview as stable workspace control expect(workspaceStyles).toMatch( /\.pl-folder-actions > summary\s*\{[^}]*width: 28px;[^}]*height: 28px;/s, ); + expect(workspaceStyles).toMatch( + /\.pl-tree-folder-row,\s*\.pl-tree-page-row\s*\{[^}]*grid-template-columns: minmax\(0, 1fr\) 28px;/s, + ); + expect(workspaceStyles).toMatch( + /\.pl-page-actions > div\s*\{[^}]*width: 176px;/s, + ); expect(workspaceStyles).toMatch( /\.pl-editor-mode-switch\s*\{[^}]*display: flex;/s, );