Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Support pinning documents in a dedicated section of the document panel https://github.com/siyuan-note/siyuan/issues/19401

Daniel1b24506de12a
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index c438d6b73b..7849fc8377 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,7 @@
{
+ "pinnedDocs": "المستندات المثبتة",
+ "pinDoc": "تثبيت في اللوحة",
+ "unpinDoc": "إلغاء التثبيت من اللوحة",
"editSnapshotMemo": "تعديل ملاحظة اللقطة",
"snapshotMemoLocalTip": "يغيّر ملاحظة اللقطة المحلية فقط",
"mobileBarsAutoHide": "إخفاء الشريطين العلوي والسفلي تلقائيًا أثناء التمرير",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 6416d7d3d3..f11a934299 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,7 @@
{
+ "pinnedDocs": "Angeheftete Dokumente",
+ "pinDoc": "Im Panel anheften",
+ "unpinDoc": "Vom Panel lösen",
"editSnapshotMemo": "Snapshot-Notiz bearbeiten",
"snapshotMemoLocalTip": "Ändert nur die Notiz des lokalen Snapshots",
"mobileBarsAutoHide": "Obere und untere Leiste beim Scrollen automatisch ausblenden",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index ee69299fe5..a44c0ee895 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,7 @@
{
+ "pinnedDocs": "Pinned documents",
+ "pinDoc": "Pin to panel",
+ "unpinDoc": "Unpin from panel",
"editSnapshotMemo": "Edit snapshot memo",
"snapshotMemoLocalTip": "Changes only the local snapshot memo",
"mobileBarsAutoHide": "Auto-hide top and bottom bars while scrolling",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 37e74e042b..912cc98f64 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,7 @@
{
+ "pinnedDocs": "Documentos fijados",
+ "pinDoc": "Fijar en el panel",
+ "unpinDoc": "Desfijar del panel",
"editSnapshotMemo": "Editar nota de la instantánea",
"snapshotMemoLocalTip": "Solo cambia la nota de la instantánea local",
"mobileBarsAutoHide": "Ocultar automáticamente las barras superior e inferior al desplazarse",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 7d271f5318..74948c8ea1 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,7 @@
{
+ "pinnedDocs": "Documents épinglés",
+ "pinDoc": "Épingler au panneau",
+ "unpinDoc": "Détacher du panneau",
"editSnapshotMemo": "Modifier la note de l’instantané",
"snapshotMemoLocalTip": "Modifie uniquement la note de l’instantané local",
"mobileBarsAutoHide": "Masquer automatiquement les barres supérieure et inférieure pendant le défilement",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index f9543424bb..e1d852aa2d 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,7 @@
{
+ "pinnedDocs": "מסמכים מוצמדים",
+ "pinDoc": "הצמדה ללוח",
+ "unpinDoc": "ביטול הצמדה ללוח",
"editSnapshotMemo": "עריכת הערת תמונת המצב",
"snapshotMemoLocalTip": "משנה רק את ההערה של תמונת המצב המקומית",
"mobileBarsAutoHide": "הסתרה אוטומטית של הסרגל העליון והתחתון בעת גלילה",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 72705b5f1e..27ed9108de 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,7 @@
{
+ "pinnedDocs": "पिन किए गए दस्तावेज़",
+ "pinDoc": "पैनल में पिन करें",
+ "unpinDoc": "पैनल से अनपिन करें",
"editSnapshotMemo": "स्नैपशॉट टिप्पणी संपादित करें",
"snapshotMemoLocalTip": "केवल स्थानीय स्नैपशॉट की टिप्पणी बदलता है",
"mobileBarsAutoHide": "स्क्रॉल करते समय ऊपरी और निचला बार अपने आप छिपाएँ",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 1d66330135..01cdafb9aa 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,7 @@
{
+ "pinnedDocs": "Dokumen disematkan",
+ "pinDoc": "Sematkan ke panel",
+ "unpinDoc": "Lepaskan dari panel",
"editSnapshotMemo": "Edit catatan snapshot",
"snapshotMemoLocalTip": "Hanya mengubah catatan snapshot lokal",
"mobileBarsAutoHide": "Sembunyikan bilah atas dan bawah otomatis saat menggulir",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 1c6521505a..bdeb993e85 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,7 @@
{
+ "pinnedDocs": "Documenti fissati",
+ "pinDoc": "Fissa nel pannello",
+ "unpinDoc": "Rimuovi dal pannello",
"editSnapshotMemo": "Modifica nota dell’istantanea",
"snapshotMemoLocalTip": "Modifica solo la nota dell’istantanea locale",
"mobileBarsAutoHide": "Nascondi automaticamente le barre superiore e inferiore durante lo scorrimento",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 46d096525f..ea45f7a84c 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,7 @@
{
+ "pinnedDocs": "ピン留めしたドキュメント",
+ "pinDoc": "パネルにピン留め",
+ "unpinDoc": "パネルのピン留めを解除",
"editSnapshotMemo": "スナップショットのメモを編集",
"snapshotMemoLocalTip": "ローカルのスナップショットのメモのみを変更します",
"mobileBarsAutoHide": "スクロール時に上部と下部のバーを自動的に隠す",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 2a212560eb..3ec7b30d93 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,7 @@
{
+ "pinnedDocs": "고정된 문서",
+ "pinDoc": "패널에 고정",
+ "unpinDoc": "패널에서 고정 해제",
"editSnapshotMemo": "스냅샷 메모 편집",
"snapshotMemoLocalTip": "로컬 스냅샷 메모만 변경합니다",
"mobileBarsAutoHide": "스크롤 시 상단 및 하단 표시줄 자동 숨기기",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 61d855dfab..4eafd42c68 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,7 @@
{
+ "pinnedDocs": "Vastgemaakte documenten",
+ "pinDoc": "Vastmaken aan paneel",
+ "unpinDoc": "Losmaken van paneel",
"editSnapshotMemo": "Snapshotnotitie bewerken",
"snapshotMemoLocalTip": "Wijzigt alleen de notitie van de lokale snapshot",
"mobileBarsAutoHide": "Bovenste en onderste balk automatisch verbergen bij scrollen",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 7c21746646..497aac2284 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,7 @@
{
+ "pinnedDocs": "Przypięte dokumenty",
+ "pinDoc": "Przypnij do panelu",
+ "unpinDoc": "Odepnij od panelu",
"editSnapshotMemo": "Edytuj notatkę migawki",
"snapshotMemoLocalTip": "Zmienia tylko notatkę lokalnej migawki",
"mobileBarsAutoHide": "Automatycznie ukrywaj górny i dolny pasek podczas przewijania",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index a78d450c55..214d8781ec 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,7 @@
{
+ "pinnedDocs": "Documentos fixados",
+ "pinDoc": "Fixar no painel",
+ "unpinDoc": "Desafixar do painel",
"editSnapshotMemo": "Editar nota do snapshot",
"snapshotMemoLocalTip": "Altera apenas a nota do snapshot local",
"mobileBarsAutoHide": "Ocultar as barras superior e inferior automaticamente ao rolar",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 04671d2796..6188a2e218 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,7 @@
{
+ "pinnedDocs": "Закреплённые документы",
+ "pinDoc": "Закрепить на панели",
+ "unpinDoc": "Открепить от панели",
"editSnapshotMemo": "Изменить заметку снимка",
"snapshotMemoLocalTip": "Изменяет только заметку локального снимка",
"mobileBarsAutoHide": "Автоматически скрывать верхнюю и нижнюю панели при прокрутке",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index e9b72fec89..4b840bf7f4 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,7 @@
{
+ "pinnedDocs": "Pripnuté dokumenty",
+ "pinDoc": "Pripnúť na panel",
+ "unpinDoc": "Odopnúť z panela",
"editSnapshotMemo": "Upraviť poznámku snímky",
"snapshotMemoLocalTip": "Zmení iba poznámku lokálnej snímky",
"mobileBarsAutoHide": "Automaticky skrývať hornú a dolnú lištu pri posúvaní",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index e1319e8c95..fe57fe7842 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,7 @@
{
+ "pinnedDocs": "เอกสารที่ปักหมุด",
+ "pinDoc": "ปักหมุดบนแผง",
+ "unpinDoc": "เลิกปักหมุดจากแผง",
"editSnapshotMemo": "แก้ไขบันทึกสแนปช็อต",
"snapshotMemoLocalTip": "เปลี่ยนเฉพาะบันทึกของสแนปช็อตในเครื่อง",
"mobileBarsAutoHide": "ซ่อนแถบด้านบนและด้านล่างอัตโนมัติขณะเลื่อน",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index b2467874c7..a99da09224 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,7 @@
{
+ "pinnedDocs": "Sabitlenmiş belgeler",
+ "pinDoc": "Panele sabitle",
+ "unpinDoc": "Panelden sabitlemeyi kaldır",
"editSnapshotMemo": "Anlık görüntü notunu düzenle",
"snapshotMemoLocalTip": "Yalnızca yerel anlık görüntü notunu değiştirir",
"mobileBarsAutoHide": "Kaydırırken üst ve alt çubukları otomatik gizle",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 495c29707f..2f2963f017 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,7 @@
{
+ "pinnedDocs": "Закріплені документи",
+ "pinDoc": "Закріпити на панелі",
+ "unpinDoc": "Відкріпити від панелі",
"editSnapshotMemo": "Змінити примітку знімка",
"snapshotMemoLocalTip": "Змінює лише примітку локального знімка",
"mobileBarsAutoHide": "Автоматично приховувати верхню й нижню панелі під час прокручування",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index a498440a30..56e1d3597b 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,7 @@
{
+ "pinnedDocs": "置顶文档",
+ "pinDoc": "置顶到面板",
+ "unpinDoc": "取消面板置顶",
"editSnapshotMemo": "修改快照备注",
"snapshotMemoLocalTip": "仅修改本地快照的备注",
"mobileBarsAutoHide": "滚动时自动隐藏顶部和底部栏",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 554a309472..39285c013f 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,7 @@
{
+ "pinnedDocs": "置頂文件",
+ "pinDoc": "置頂至面板",
+ "unpinDoc": "取消面板置頂",
"editSnapshotMemo": "修改快照備註",
"snapshotMemoLocalTip": "僅修改本機快照的備註",
"mobileBarsAutoHide": "捲動時自動隱藏頂部和底部列",
diff --git a/app/src/config/entryVisibility/catalog.test.ts b/app/src/config/entryVisibility/catalog.test.ts
index fbc2729a46..7dc3260445 100644
--- a/app/src/config/entryVisibility/catalog.test.ts
+++ b/app/src/config/entryVisibility/catalog.test.ts
@@ -980,6 +980,15 @@ test("configuration labels distinguish block scopes and size controls", () => {
}
});
+test("document tree pin entries follow attributes and precede sorting", () => {
+ const keys = getEntryCatalogChildren("docTree.document").map(item => item.key);
+ assert.deepEqual(keys.slice(keys.indexOf("attr"), keys.indexOf("sort") + 1), ["attr", "pinDoc", "unpinDoc", "sort"]);
+ for (const key of ["pinDoc", "unpinDoc"]) {
+ assert.equal(getEntryCatalogNode(`docTree.document.${key}`)?.simple, true);
+ assert.equal(getEntryCatalogNode(`docTree.document.${key}`)?.type, "entry");
+ }
+});
+
test("document tree creation entries match menu order and remain available in the Simple profile", () => {
const entries = getEntryCatalogChildren("docTree.document");
const creationKeys = ["newDocAbove", "newDocBelow", "newSiblingDoc"];
@@ -1004,8 +1013,10 @@ test("document tree creation entries match menu order and remain available in th
test("document tree sort menus follow their scope inheritance options", () => {
const documentEntries = getEntryCatalogChildren("docTree.document");
const attrIndex = documentEntries.findIndex((item) => item.key === "attr");
- assert.deepEqual(documentEntries.slice(attrIndex, attrIndex + 3).map((item) => item.key), [
+ assert.deepEqual(documentEntries.slice(attrIndex, attrIndex + 5).map((item) => item.key), [
"attr",
+ "pinDoc",
+ "unpinDoc",
"sort",
"riffCard",
]);
diff --git a/app/src/config/entryVisibility/catalog.ts b/app/src/config/entryVisibility/catalog.ts
index 2ed8516a40..1f1f1264ec 100644
--- a/app/src/config/entryVisibility/catalog.ts
+++ b/app/src/config/entryVisibility/catalog.ts
@@ -173,6 +173,8 @@ const docTreeDocument = () => {
separator("separator_2"),
node("rename", lang("rename")),
node("attr", lang("attr")),
+ node("pinDoc", lang("pinDoc")),
+ node("unpinDoc", lang("unpinDoc")),
node("sort", lang("sort"), true, sortChildren("sortByParent")),
riffCard,
node("search", lang("search")),
diff --git a/app/src/config/entryVisibility/order.test.ts b/app/src/config/entryVisibility/order.test.ts
index ae069abc2e..710f6c9246 100644
--- a/app/src/config/entryVisibility/order.test.ts
+++ b/app/src/config/entryVisibility/order.test.ts
@@ -28,6 +28,18 @@ test("entry order inserts document sorting after attributes in existing profiles
), ["search", "rename", "attr", "sort", "riffCard"]);
});
+test("pin entries merge into document menus without moving existing plugin slots", () => {
+ const entries = getEntryCatalogChildren("docTree.document");
+ const defaults = entries.map(item => item.key);
+ const saved = defaults.filter(key => !["pinDoc", "unpinDoc"].includes(key));
+ saved.splice(1, 0, "plugin:example:item");
+ const merged = mergeEntryOrderPreservingUnknown(defaults, saved);
+ assert.deepEqual(merged.filter(key => !["pinDoc", "unpinDoc"].includes(key)), saved);
+ assert.deepEqual(merged.slice(merged.indexOf("attr"), merged.indexOf("sort") + 1), ["attr", "pinDoc", "unpinDoc", "sort"]);
+ const separators = new Set(entries.filter(item => item.type === "separator").map(item => item.key));
+ assert.deepEqual(resolveEntryOrder([...defaults, "plugin:example:item"], merged, separators), merged);
+});
+
test("entry order ignores unknown and duplicate keys", () => {
assert.deepEqual(mergeEntryOrder(["a", "b", "c"], ["missing", "c", "c", "a"]), ["c", "a", "b"]);
});
diff --git a/app/src/layout/dock/Files.ts b/app/src/layout/dock/Files.ts
index 40c48fac06..d330c19b19 100644
--- a/app/src/layout/dock/Files.ts
+++ b/app/src/layout/dock/Files.ts
@@ -75,6 +75,7 @@ import {
import {clearDocumentTabMovePreview} from "../tabDrag";
import {reorderSortedFileTree} from "../../util/fileTreeReorder";
import {getHostCapabilities} from "../../util/hostCapabilities";
+import {PinnedDocs} from "./PinnedDocs";
export class Files extends Model {
public element: HTMLElement;
@@ -82,6 +83,7 @@ export class Files extends Model {
public closeElement: HTMLElement;
public lastSelectedElement: Element = null;
private actionsElement: HTMLElement;
+ private pinnedDocs: PinnedDocs;
private reloadNotebookInfoTimeout: number;
private docSortModeRefreshTimeout: number;
private docSortModeChanges = new Map<string, IDocSortModeChanged>();
@@ -123,6 +125,9 @@ export class Files extends Model {
this.actionsElement = options.tab.panelElement.firstElementChild as HTMLElement;
this.element = this.actionsElement.nextElementSibling as HTMLElement;
this.closeElement = options.tab.panelElement.lastElementChild as HTMLElement;
+ this.pinnedDocs = new PinnedDocs(options.app, this.element, (id) => {
+ openFileById({app: options.app, id, action: [Constants.CB_GET_FOCUS, Constants.CB_GET_SCROLL]});
+ });
this.closeElement.addEventListener("click", (event) => {
setPanelFocus(this.element.parentElement);
let target = event.target as HTMLElement;
@@ -1165,6 +1170,7 @@ export class Files extends Model {
}
private handleMsgCallback(data: IWebSocketData) {
+ if (data) { this.pinnedDocs?.scheduleRefresh(); }
if (data) {
switch (data.cmd) {
case "reloadDocInfo":
@@ -1464,6 +1470,7 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"
}
public init(init = true) {
+ this.pinnedDocs?.scheduleRefresh();
let html = "";
let closeHtml = "";
let closeCounter = 0;
@@ -1675,6 +1682,7 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"
}
public onDocSortModeChanged(data: IDocSortModeChanged) {
+ this.pinnedDocs?.scheduleRefresh();
updateFileTreeSortMode(data, this.element);
this.docSortModeChanges.set(`${data.scope}:${data.box}:${data.id}:${data.path}`, data);
window.clearTimeout(this.docSortModeRefreshTimeout);
@@ -2137,6 +2145,10 @@ aria-label="${ariaLabel}">${getDocDisplayName(item.name, item.titleEmpty, true)}
</li>`;
}
+ public destroy() {
+ this.pinnedDocs.destroy();
+ }
+
private initMoreMenu() {
window.siyuan.menus.menu.remove();
window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_DOC_TREE_PANEL_MORE);
diff --git a/app/src/layout/dock/PinnedDocs.test.ts b/app/src/layout/dock/PinnedDocs.test.ts
new file mode 100644
index 0000000000..0cf534b4b3
--- /dev/null
+++ b/app/src/layout/dock/PinnedDocs.test.ts
@@ -0,0 +1,83 @@
+import * as assert from "node:assert/strict";
+import test from "node:test";
+import {readFileSync} from "node:fs";
+import {join} from "node:path";
+import {runInNewContext} from "node:vm";
+import * as ts from "typescript";
+
+interface IPanelHarness {
+ drop(ids: string[], x: number, y: number): Promise<void>;
+ click(event: unknown): void;
+ previewDrop(): void;
+ clearDrop(): void;
+ scheduleRefresh(): void;
+ dropTarget?: {id: string, position: string};
+ suppressClick?: boolean;
+}
+
+const loadPanel = () => {
+ const calls: {kind: string, args: unknown[]}[] = [];
+ const record = (kind: string) => async (...args: unknown[]) => {
+ calls.push({kind, args});
+ return {code: 0};
+ };
+ const exports: {PinnedDocs?: {prototype: object}} = {};
+ const source = ts.transpileModule(readFileSync(join(__dirname, "PinnedDocs.ts"), "utf8"), {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},
+ }).outputText;
+ runInNewContext(source, {
+ exports,
+ require: (name: string) => {
+ if (name.endsWith("/pinnedDocs")) { return {updatePinnedDocs: record("pin")}; }
+ if (name.endsWith("/fetch")) { return {fetchSyncPost: record("http")}; }
+ if (name.endsWith("/fileTreeReorder")) { return {reorderSortedFileTree: record("reorder")}; }
+ return {};
+ },
+ });
+ const panel = Object.create(exports.PinnedDocs.prototype) as IPanelHarness;
+ panel.clearDrop = () => { panel.dropTarget = undefined; };
+ panel.scheduleRefresh = () => {};
+ return {panel, calls};
+};
+
+test("root drops create an entry without invoking source movement", async () => {
+ const {panel, calls} = loadPanel();
+ panel.previewDrop = () => { panel.dropTarget = {id: "parent", position: "pin-before"}; };
+ await panel.drop(["child"], 0, 0);
+ assert.deepEqual(calls, [{kind: "pin", args: [["child"], "pin", "parent", false]}]);
+});
+
+test("child ordering uses the existing conflict confirmation and inside drops move the source", async () => {
+ const {panel, calls} = loadPanel();
+ panel.previewDrop = () => { panel.dropTarget = {id: "sibling", position: "after"}; };
+ await panel.drop(["child"], 0, 0);
+ assert.deepEqual(calls, [{kind: "reorder", args: [["child"], "sibling", true]}]);
+ calls.length = 0;
+ panel.previewDrop = () => { panel.dropTarget = {id: "parent", position: "inside"}; };
+ await panel.drop(["child"], 0, 0);
+ assert.equal(calls[0].kind, "http");
+ assert.equal(calls[0].args[0], "/api/filetree/moveDocsByID");
+ assert.equal(JSON.stringify(calls[0].args[1]), JSON.stringify({fromIDs: ["child"], toID: "parent"}));
+});
+
+test("invalid drop targets and self moves do not mutate source documents", async () => {
+ const {panel, calls} = loadPanel();
+ panel.previewDrop = () => { panel.dropTarget = undefined; };
+ await panel.drop(["child"], 0, 0);
+ panel.previewDrop = () => { panel.dropTarget = {id: "child", position: "inside"}; };
+ await panel.drop(["child"], 0, 0);
+ await panel.drop([], 0, 0);
+ assert.equal(calls.length, 0);
+});
+
+test("panel clicks never bubble into the mobile source tree handler", () => {
+ const {panel} = loadPanel();
+ let stopped = 0;
+ let prevented = 0;
+ panel.suppressClick = true;
+ panel.click({stopPropagation: () => stopped++, preventDefault: () => prevented++});
+ panel.suppressClick = false;
+ panel.click({stopPropagation: () => stopped++, target: {closest: (): Element | null => null}});
+ assert.equal(stopped, 2);
+ assert.equal(prevented, 1);
+});
diff --git a/app/src/layout/dock/PinnedDocs.ts b/app/src/layout/dock/PinnedDocs.ts
new file mode 100644
index 0000000000..d0892a798a
--- /dev/null
+++ b/app/src/layout/dock/PinnedDocs.ts
@@ -0,0 +1,414 @@
+import type {App} from "../../index";
+import {Constants} from "../../constants";
+import {fetchSyncPost} from "../../util/fetch";
+import {pinnedDocIDs, updatePinnedDocs} from "../../util/pinnedDocs";
+import {getPinnedDropPosition} from "../../util/pinnedDocsDrop";
+import {getFileTreeIconHTML} from "../../emoji/fileTreeIcon";
+import {escapeHtml} from "../../util/escape";
+import {initFileMenu} from "../../menus/navigation";
+import {parseDocumentTabDragData, parseDocumentTreeDragData} from "../../util/fileTreeMove";
+import {reorderSortedFileTree} from "../../util/fileTreeReorder";
+import {dragOverScroll, stopScrollAnimation} from "../../boot/globalEvent/dragover";
+import {MenuItem} from "../../menus/Menu";
+import {newFileInTree} from "../../util/newFile";
+import {FILE_TREE_CHILDREN_SORT_MODE, FILE_TREE_EFFECTIVE_SORT_MODE} from "../../util/fileTreeSort";
+
+interface IPinnedDoc {
+ id: string;
+ notebook: string;
+ name: string;
+ path: string;
+ icon: string;
+ subFileCount: number;
+ unavailable?: boolean;
+ childrenSortMode?: number | null;
+}
+
+// 根入口与子树使用独立容器,避免重复文档干扰源文档树的选择和移动定位。
+export class PinnedDocs {
+ public element: HTMLElement;
+ private list: HTMLElement;
+ private expanded = new Set<string>();
+ private generation = 0;
+ private refreshTimer: number;
+ private disposed = false;
+ private dropTarget: {id: string, position: ReturnType<typeof getPinnedDropPosition>} | undefined;
+ private touch: {id: string, x: number, y: number, timer: number, dragging: boolean, ghost?: HTMLElement};
+ private suppressClick = false;
+ private dragging = false;
+ private sourceEvents = new AbortController();
+ private names = new Map<string, string>();
+
+ constructor(private app: App, private sourceTree: HTMLElement, private open: (id: string, notebook: string) => void,
+ private mobile = false) {
+ this.element = document.createElement("div");
+ this.element.className = "file-tree__pins fn__flex-column";
+ this.element.style.cssText = "flex-shrink:0;max-height:40%;min-height:30px;overflow:hidden;border-bottom:1px solid var(--b3-border-color)";
+ this.element.innerHTML = `<button class="b3-list-item" type="button" data-pin-heading="true"><span class="b3-list-item__toggle"><svg class="b3-list-item__arrow"><use xlink:href="#iconRight"></use></svg></span><span class="b3-list-item__text">${window.siyuan.languages.pinnedDocs}</span></button><div class="fn__flex-1" style="overflow:auto;min-height:0"><ul class="b3-list"></ul></div>`;
+ this.list = this.element.lastElementChild.firstElementChild as HTMLElement;
+ sourceTree.before(this.element);
+ try {
+ this.expanded = new Set(JSON.parse(localStorage.getItem("siyuan-pinned-docs-expanded") || "[]"));
+ } catch (e) {
+ console.warn("Failed to read pinned document expansion state", e);
+ }
+ this.setCollapsed(localStorage.getItem("siyuan-pinned-docs-collapsed") === "true");
+ this.element.addEventListener("click", event => this.click(event));
+ this.element.addEventListener("contextmenu", event => {
+ event.stopPropagation();
+ const row = (event.target as Element).closest<HTMLElement>("[data-pin-row]");
+ if (row) {
+ event.preventDefault();
+ this.menu(row, event.clientX, event.clientY);
+ }
+ });
+ this.element.addEventListener("dragstart", event => {
+ const row = (event.target as Element).closest<HTMLElement>("[data-pin-row]");
+ if (!row || row.dataset.unavailable === "true" || window.siyuan.config.readonly) {
+ event.preventDefault();
+ return;
+ }
+ event.stopPropagation();
+ this.dragging = true;
+ this.generation++;
+ event.dataTransfer.setData("application/siyuan-pinned-document", row.dataset.nodeId);
+ event.dataTransfer.setData(Constants.SIYUAN_DROP_DOCUMENTS, JSON.stringify({ids: [row.dataset.nodeId]}));
+ event.dataTransfer.setData(Constants.SIYUAN_DROP_FILE, row.dataset.nodeId);
+ event.dataTransfer.effectAllowed = "copyMove";
+ });
+ this.element.addEventListener("dragover", event => {
+ if (window.siyuan.config.readonly || ![Constants.SIYUAN_DROP_DOCUMENTS, Constants.SIYUAN_DROP_FILE,
+ Constants.SIYUAN_DROP_DOCUMENT_TAB].some(type => event.dataTransfer.types.includes(type))) {
+ return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ this.previewDrop(event.clientX, event.clientY);
+ event.dataTransfer.dropEffect = this.dropTarget?.position.startsWith("pin") ? "copy" : "move";
+ });
+ this.element.addEventListener("drop", async event => {
+ event.preventDefault();
+ event.stopPropagation();
+ const rawDocs = event.dataTransfer.getData(Constants.SIYUAN_DROP_DOCUMENTS);
+ const docs = rawDocs ? parseDocumentTreeDragData(rawDocs) : undefined;
+ const tab = event.dataTransfer.getData(Constants.SIYUAN_DROP_DOCUMENT_TAB);
+ const ids = docs?.ids || (tab ? [parseDocumentTabDragData(tab)?.rootId].filter(Boolean) :
+ event.dataTransfer.getData(Constants.SIYUAN_DROP_FILE).split(",").filter(id => /^\d{14}-[a-z0-9]{7}$/.test(id)));
+ await this.drop(ids, event.clientX, event.clientY);
+ });
+ this.element.addEventListener("dragleave", event => {
+ if (!this.element.contains(event.relatedTarget as Node)) {
+ this.clearDrop();
+ }
+ });
+ this.element.addEventListener("dragend", () => {
+ this.clearDrop();
+ this.dragging = false;
+ this.scheduleRefresh();
+ });
+ sourceTree.addEventListener("dragover", event => {
+ if (!event.dataTransfer.types.includes("application/siyuan-pinned-document")) { return; }
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ this.previewDrop(event.clientX, event.clientY, true);
+ }, {capture: true, signal: this.sourceEvents.signal});
+ sourceTree.addEventListener("drop", event => {
+ const id = event.dataTransfer.getData("application/siyuan-pinned-document");
+ if (!/^\d{14}-[a-z0-9]{7}$/.test(id)) { return; }
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ this.drop([id], event.clientX, event.clientY, true);
+ }, {capture: true, signal: this.sourceEvents.signal});
+ sourceTree.addEventListener("dragleave", event => {
+ if (this.dragging && !sourceTree.contains(event.relatedTarget as Node)) { this.clearDrop(); }
+ }, {capture: true, signal: this.sourceEvents.signal});
+ this.bindTouch();
+ this.refresh();
+ }
+
+ public destroy() {
+ this.disposed = true;
+ this.generation++;
+ window.clearTimeout(this.refreshTimer);
+ this.cancelTouch();
+ this.sourceEvents.abort();
+ }
+
+ public scheduleRefresh() {
+ window.clearTimeout(this.refreshTimer);
+ this.refreshTimer = window.setTimeout(() => this.refresh(), 150);
+ }
+
+ private setCollapsed(collapsed: boolean) {
+ this.element.lastElementChild.classList.toggle("fn__none", collapsed);
+ this.element.firstElementChild.setAttribute("aria-expanded", String(!collapsed));
+ this.element.querySelector("svg").classList.toggle("b3-list-item__arrow--open", !collapsed);
+ }
+
+ public async refresh() {
+ if (this.disposed || window.siyuan.isPublish || this.dragging || this.touch?.dragging) {
+ return;
+ }
+ const generation = ++this.generation;
+ const response = await fetchSyncPost("/api/filetree/getPinnedDocs", {});
+ if (response.code !== 0 || generation !== this.generation || this.disposed) {
+ return;
+ }
+ const scroll = this.list.parentElement.scrollTop;
+ const focused = this.list.contains(document.activeElement) ? (document.activeElement as HTMLElement).dataset.pinRow : undefined;
+ const selected = new Set(Array.from(this.list.querySelectorAll<HTMLElement>(".b3-list-item--focus"), row => row.dataset.pinRow));
+ pinnedDocIDs.clear();
+ response.data.forEach(doc => pinnedDocIDs.add(doc.id));
+ const list = document.createElement("ul");
+ for (const doc of response.data) {
+ if (doc.unavailable) {
+ doc.name = this.names.get(doc.id) || doc.name;
+ } else {
+ this.names.set(doc.id, doc.name);
+ }
+ const wrapper = document.createElement("ul");
+ wrapper.dataset.url = doc.notebook;
+ list.append(wrapper);
+ await this.appendDoc(wrapper, doc, doc.id, 0, generation);
+ }
+ if (generation === this.generation && !this.disposed) {
+ this.list.replaceChildren(...Array.from(list.children));
+ this.list.querySelectorAll<HTMLElement>("[data-pin-row]").forEach(row => {
+ row.classList.toggle("b3-list-item--focus", selected.has(row.dataset.pinRow));
+ if (row.dataset.pinRow === focused) { row.focus({preventScroll: true}); }
+ });
+ this.list.parentElement.scrollTop = scroll;
+ }
+ }
+
+ private async appendDoc(parent: HTMLElement, doc: IPinnedDoc, key: string, depth: number, generation: number) {
+ const row = document.createElement("li");
+ row.className = "b3-list-item b3-list-item--hide-action";
+ row.dataset.pinRow = key;
+ row.dataset.pinRoot = String(depth === 0);
+ row.dataset.nodeId = doc.id;
+ row.dataset.notebook = doc.notebook;
+ row.dataset.path = doc.path;
+ row.dataset.name = doc.name;
+ row.dataset.count = String(doc.subFileCount);
+ row.dataset.type = "navigation-file";
+ row.setAttribute(FILE_TREE_CHILDREN_SORT_MODE, doc.childrenSortMode?.toString() || "");
+ row.dataset.unavailable = String(Boolean(doc.unavailable));
+ row.draggable = !doc.unavailable && !window.siyuan.config.readonly;
+ row.tabIndex = 0;
+ row.style.paddingLeft = `${depth * (this.mobile ? 20 : 18)}px`;
+ row.setAttribute("aria-disabled", String(Boolean(doc.unavailable)));
+ if (doc.subFileCount) { row.setAttribute("aria-expanded", "false"); }
+ row.innerHTML = `<span data-pin-toggle="true" class="b3-list-item__toggle${doc.subFileCount ? "" : " fn__hidden"}"><svg class="b3-list-item__arrow"><use xlink:href="#iconRight"></use></svg></span><span class="b3-list-item__icon">${getFileTreeIconHTML(doc.icon, doc.subFileCount ? "folder" : "file")}</span><span class="b3-list-item__text">${escapeHtml(doc.name)}${doc.unavailable ? ` (${window.siyuan.languages.closeNotebook})` : ""}</span><span data-pin-more="true" class="b3-list-item__action"><svg><use xlink:href="#iconMore"></use></svg></span>`;
+ if (!doc.unavailable && !window.siyuan.config.readonly) {
+ const add = document.createElement("span");
+ add.className = "b3-list-item__action";
+ add.dataset.pinNew = "true";
+ add.setAttribute("aria-label", window.siyuan.languages.newSubDoc);
+ add.innerHTML = '<svg><use xlink:href="#iconAdd"></use></svg>';
+ row.append(add);
+ }
+ row.addEventListener("keydown", event => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ event.stopPropagation();
+ if (!doc.unavailable) { this.open(doc.id, doc.notebook); }
+ } else if (event.key === "ArrowRight" || event.key === "ArrowLeft") {
+ event.preventDefault();
+ event.stopPropagation();
+ this.toggle(row, event.key === "ArrowRight");
+ }
+ });
+ parent.append(row);
+ const children = document.createElement("ul");
+ children.className = "fn__none";
+ parent.append(children);
+ if (this.expanded.has(key) && doc.subFileCount && !doc.unavailable) {
+ await this.loadChildren(row, children, generation);
+ }
+ }
+
+ private async loadChildren(row: HTMLElement, children: HTMLElement, generation: number) {
+ const response = await fetchSyncPost("/api/filetree/listDocsByPath", {
+ notebook: row.dataset.notebook, path: row.dataset.path,
+ maxListCount: 0,
+ });
+ if (response.code !== 0 || generation !== this.generation || !this.expanded.has(row.dataset.pinRow)) {
+ return;
+ }
+ children.replaceChildren();
+ children.setAttribute(FILE_TREE_EFFECTIVE_SORT_MODE, String(response.data.effectiveSortMode));
+ for (const doc of response.data.files) {
+ await this.appendDoc(children, {...doc, notebook: row.dataset.notebook},
+ `${row.dataset.pinRow}/${doc.id}`, row.dataset.pinRow.split("/").length, generation);
+ }
+ children.classList.remove("fn__none");
+ row.querySelector(".b3-list-item__arrow").classList.add("b3-list-item__arrow--open");
+ row.setAttribute("aria-expanded", "true");
+ }
+
+ private async toggle(row: HTMLElement, expand = !this.expanded.has(row.dataset.pinRow)) {
+ if (row.dataset.unavailable === "true" || row.dataset.count === "0") { return; }
+ const key = row.dataset.pinRow;
+ if (expand) {
+ this.expanded.add(key);
+ await this.loadChildren(row, row.nextElementSibling as HTMLElement, this.generation);
+ } else {
+ this.expanded.delete(key);
+ row.nextElementSibling.classList.add("fn__none");
+ row.querySelector("svg").classList.remove("b3-list-item__arrow--open");
+ row.setAttribute("aria-expanded", "false");
+ }
+ localStorage.setItem("siyuan-pinned-docs-expanded", JSON.stringify([...this.expanded]));
+ }
+
+ private click(event: MouseEvent) {
+ event.stopPropagation();
+ if (this.suppressClick) { event.preventDefault(); return; }
+ const target = event.target as Element;
+ if (target.closest("[data-pin-heading]")) {
+ const collapsed = this.element.firstElementChild.getAttribute("aria-expanded") === "true";
+ this.setCollapsed(collapsed);
+ localStorage.setItem("siyuan-pinned-docs-collapsed", String(collapsed));
+ return;
+ }
+ const row = target.closest<HTMLElement>("[data-pin-row]");
+ if (!row) { return; }
+ if (target.closest("[data-pin-more]")) {
+ this.menu(row, event.clientX, event.clientY);
+ } else if (target.closest("[data-pin-new]")) {
+ newFileInTree(this.app, row.dataset.notebook, row.dataset.path);
+ } else if (target.closest("[data-pin-toggle]")) {
+ this.toggle(row);
+ } else if (row.dataset.unavailable !== "true") {
+ this.list.querySelectorAll(".b3-list-item--focus").forEach(item => item.classList.remove("b3-list-item--focus"));
+ row.classList.add("b3-list-item--focus");
+ this.open(row.dataset.nodeId, row.dataset.notebook);
+ }
+ }
+
+ private menu(row: HTMLElement, x: number, y: number) {
+ if (row.dataset.unavailable === "true") {
+ const menu = window.siyuan.menus.menu;
+ menu.remove();
+ menu.element.setAttribute("data-name", Constants.MENU_DOC_TREE_MORE);
+ menu.element.setAttribute("data-from", Constants.MENU_FROM_DOC_TREE_MORE_DOC);
+ if (!window.siyuan.config.readonly) {
+ menu.append(new MenuItem({
+ id: "unpinDoc",
+ label: window.siyuan.languages.unpinDoc,
+ icon: "iconUnpin",
+ click: () => { updatePinnedDocs([row.dataset.nodeId], "unpin"); },
+ }).element);
+ if (this.mobile) { menu.fullscreen("bottom"); } else { menu.popup({x, y}); }
+ }
+ return;
+ }
+ const menu = initFileMenu(this.app, row.dataset.notebook, row.dataset.path, row);
+ if (this.mobile) { menu.fullscreen("bottom"); } else { menu.popup({x, y}); }
+ }
+
+ public previewDrop(x: number, y: number, allowSource = false) {
+ this.clearDrop();
+ const target = document.elementFromPoint(x, y);
+ if (!target || window.siyuan.config.readonly) { return false; }
+ const source = allowSource && this.sourceTree.contains(target);
+ if (!this.element.contains(target) && !source) { return false; }
+ const row = target.closest<HTMLElement>(source ? "li[data-type]" : "[data-pin-row]");
+ if (source && (!row || row.closest("[data-encrypted=true]"))) { return false; }
+ if (!row) {
+ this.dropTarget = {id: "", position: "pin-before"};
+ this.element.firstElementChild.classList.add("dragover__top");
+ } else {
+ if (row.dataset.unavailable === "true") { return false; }
+ const rect = row.getBoundingClientRect();
+ const position = source && row.dataset.type === "navigation-root" ? "inside" :
+ getPinnedDropPosition(row.dataset.pinRoot === "true", (y - rect.top) / rect.height);
+ this.dropTarget = {id: row.dataset.nodeId || row.dataset.url, position};
+ row.classList.add(position === "inside" ? "dragover" : position.endsWith("before") ? "dragover__top" : "dragover__bottom");
+ }
+ const scrollElement = source ? this.sourceTree : this.list.parentElement;
+ dragOverScroll({clientY: y} as MouseEvent, scrollElement.getBoundingClientRect(), scrollElement);
+ return true;
+ }
+
+ public clearDrop() {
+ this.dropTarget = undefined;
+ this.element.querySelectorAll(".dragover, .dragover__top, .dragover__bottom").forEach(row =>
+ row.classList.remove("dragover", "dragover__top", "dragover__bottom"));
+ if (this.dragging || this.touch?.dragging) {
+ this.sourceTree.querySelectorAll(".dragover, .dragover__top, .dragover__bottom").forEach(row =>
+ row.classList.remove("dragover", "dragover__top", "dragover__bottom"));
+ }
+ stopScrollAnimation();
+ }
+
+ public async drop(ids: string[], x: number, y: number, allowSource = false) {
+ this.previewDrop(x, y, allowSource);
+ const target = this.dropTarget;
+ this.clearDrop();
+ if (!target || !ids.length) { return; }
+ if (target.position.startsWith("pin")) {
+ await updatePinnedDocs(ids, "pin", target.id, target.position === "pin-after");
+ } else if (!ids.includes(target.id)) {
+ if (target.position === "inside") {
+ await fetchSyncPost("/api/filetree/moveDocsByID", {fromIDs: ids, toID: target.id});
+ } else {
+ await reorderSortedFileTree(ids, target.id, target.position === "after");
+ }
+ }
+ this.scheduleRefresh();
+ }
+
+ private cancelTouch() {
+ this.clearDrop();
+ if (this.touch) {
+ window.clearTimeout(this.touch.timer);
+ this.touch.ghost?.remove();
+ this.touch = undefined;
+ }
+ }
+
+ private bindTouch() {
+ this.element.addEventListener("touchstart", event => {
+ event.stopPropagation();
+ const row = (event.target as Element).closest<HTMLElement>("[data-pin-row]");
+ if (!row || row.dataset.unavailable === "true" || window.siyuan.config.readonly || event.touches.length !== 1) { return; }
+ this.cancelTouch();
+ const touch = event.touches[0];
+ const state = {id: row.dataset.nodeId, x: touch.clientX, y: touch.clientY, timer: 0, dragging: false, ghost: undefined as HTMLElement};
+ this.touch = state;
+ state.timer = window.setTimeout(() => {
+ state.dragging = true;
+ state.ghost = row.cloneNode(true) as HTMLElement;
+ state.ghost.style.cssText = `position:fixed;pointer-events:none;z-index:9999;opacity:.7;left:${state.x}px;top:${state.y}px`;
+ document.body.append(state.ghost);
+ this.suppressClick = true;
+ }, Constants.TIMEOUT_LONGPRESS);
+ }, {passive: true});
+ this.element.addEventListener("touchmove", event => {
+ event.stopPropagation();
+ if (!this.touch) { return; }
+ const touch = event.touches[0];
+ if (!this.touch.dragging) {
+ if (Math.abs(touch.clientX - this.touch.x) + Math.abs(touch.clientY - this.touch.y) > 8) { this.cancelTouch(); }
+ return;
+ }
+ event.preventDefault();
+ this.touch.ghost.style.left = `${touch.clientX}px`;
+ this.touch.ghost.style.top = `${touch.clientY}px`;
+ this.previewDrop(touch.clientX, touch.clientY, true);
+ }, {passive: false});
+ this.element.addEventListener("touchend", event => {
+ event.stopPropagation();
+ if (this.touch?.dragging) {
+ event.preventDefault();
+ const touch = event.changedTouches[0];
+ this.drop([this.touch.id], touch.clientX, touch.clientY, true);
+ }
+ this.cancelTouch();
+ window.setTimeout(() => { this.suppressClick = false; }, 300);
+ });
+ this.element.addEventListener("touchcancel", () => this.cancelTouch());
+ }
+}
diff --git a/app/src/menus/navigation.ts b/app/src/menus/navigation.ts
index 09815c2b90..9c29fe4e1a 100644
--- a/app/src/menus/navigation.ts
+++ b/app/src/menus/navigation.ts
@@ -5,6 +5,7 @@ import * as path from "path";
/// #endif
import {MenuItem} from "./Menu";
import {getDisplayName, getNotebookName, getTopPaths, isEncryptedBox, pathPosix, useShell} from "../util/pathName";
+import {pinnedDocIDs, updatePinnedDocs} from "../util/pinnedDocs";
import {showMessage} from "../dialog/message";
import {confirmDialog} from "../dialog/confirmDialog";
import {fetchPost, fetchSyncPost} from "../util/fetch";
@@ -813,6 +814,23 @@ export const initFileMenu = (app: App, notebookId: string, pathString: string, l
});
}
}).element);
+ if (!isEncryptedBox(notebookId)) {
+ const pinned = pinnedDocIDs.has(id);
+ window.siyuan.menus.menu.append(new MenuItem({
+ id: "pinDoc",
+ icon: "iconPin",
+ label: window.siyuan.languages.pinDoc,
+ click: () => { updatePinnedDocs([id], "pin"); },
+ }).element);
+ if (pinned) {
+ window.siyuan.menus.menu.append(new MenuItem({
+ id: "unpinDoc",
+ icon: "iconUnpin",
+ label: window.siyuan.languages.unpinDoc,
+ click: () => { updatePinnedDocs([id], "unpin"); },
+ }).element);
+ }
+ }
const configuredSortMode = getConfiguredChildrenSortMode(liElement);
const sortSubMenu = sortMenu("document", configuredSortMode, (sortMode) => {
fetchPost("/api/filetree/setDocSortMode", {
diff --git a/app/src/mobile/dock/MobileFiles.ts b/app/src/mobile/dock/MobileFiles.ts
index c13c2a4bd8..c2d3ed0fc6 100644
--- a/app/src/mobile/dock/MobileFiles.ts
+++ b/app/src/mobile/dock/MobileFiles.ts
@@ -58,10 +58,12 @@ import {
updateFileTreeSortMode
} from "../../util/fileTreeSort";
import {MobileOpenedFileSelection} from "./mobileOpenedFileSelection";
+import {PinnedDocs} from "../../layout/dock/PinnedDocs";
export class MobileFiles extends Model {
public element: HTMLElement;
private actionsElement: HTMLElement;
+ private pinnedDocs: PinnedDocs;
private closeElement: HTMLElement;
private reloadNotebookInfoTimeout: number;
private docSortModeRefreshTimeout: number;
@@ -108,6 +110,9 @@ export class MobileFiles extends Model {
</ul>`;
this.actionsElement = filesElement.firstElementChild as HTMLElement;
this.element = this.actionsElement.nextElementSibling as HTMLElement;
+ this.pinnedDocs = new PinnedDocs(app, this.element, (id, notebook) => {
+ openMobileFileById(app, id, [Constants.CB_GET_SCROLL], undefined, notebook);
+ }, true);
this.closeElement = this.element.nextElementSibling as HTMLElement;
filesElement.addEventListener("click", (event: MouseEvent & { target: HTMLElement }) => {
let target = event.target as HTMLElement;
@@ -347,6 +352,14 @@ export class MobileFiles extends Model {
dragOverScroll({clientY: touch.clientY} as MouseEvent, this.element.getBoundingClientRect(), this.element);
const target = document.elementFromPoint(touch.clientX, touch.clientY);
+ if (target && this.pinnedDocs.element.contains(target)) {
+ this.clearDragIndicators();
+ if (state.selectedElement.dataset.type === "navigation-file") {
+ this.pinnedDocs.previewDrop(touch.clientX, touch.clientY);
+ }
+ return;
+ }
+ this.pinnedDocs.clearDrop();
const liElement = target?.closest(".b3-list-item") as HTMLElement;
if (!liElement) return;
@@ -385,13 +398,20 @@ export class MobileFiles extends Model {
}
}, {passive: false});
- filesElement.addEventListener("touchend", async () => {
+ filesElement.addEventListener("touchend", async (event: TouchEvent) => {
const state = this.touchDragState;
if (!state) return;
stopScrollAnimation();
state.selectedElement.style.opacity = "";
if (state.isDragging) {
state.ghostElement?.remove();
+ const touch = event.changedTouches[0];
+ const target = document.elementFromPoint(touch.clientX, touch.clientY);
+ if (target && this.pinnedDocs.element.contains(target) && state.selectedElement.dataset.type === "navigation-file") {
+ this.touchDragState = null;
+ await this.pinnedDocs.drop([state.selectedElement.dataset.nodeId], touch.clientX, touch.clientY);
+ return;
+ }
const newElement = this.element.querySelector(".dragover, .dragover__bottom, .dragover__top");
if (!newElement) {
this.touchDragState = null;
@@ -587,6 +607,7 @@ export class MobileFiles extends Model {
}
private handleMsgCallback(data: IWebSocketData) {
+ if (data) { this.pinnedDocs?.scheduleRefresh(); }
if (data) {
switch (data.cmd) {
case "moveDocs":
@@ -737,6 +758,10 @@ export class MobileFiles extends Model {
});
};
+ public destroy() {
+ this.pinnedDocs.destroy();
+ }
+
private genSort() {
window.siyuan.menus.menu.remove();
const subMenu = sortMenu("notebooks", window.siyuan.config.fileTree.sort, (sort) => {
@@ -907,6 +932,7 @@ export class MobileFiles extends Model {
}
public init(init = true) {
+ this.pinnedDocs?.scheduleRefresh();
let html = "";
let closeHtml = "";
let closeCounter = 0;
@@ -1190,6 +1216,7 @@ export class MobileFiles extends Model {
}
public onDocSortModeChanged(data: IDocSortModeChanged) {
+ this.pinnedDocs?.scheduleRefresh();
updateFileTreeSortMode(data, this.element);
this.docSortModeChanges.set(`${data.scope}:${data.box}:${data.id}:${data.path}`, data);
window.clearTimeout(this.docSortModeRefreshTimeout);
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index 723223568b..37c34e55c3 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -66,6 +66,8 @@ export type NetworkServeTLSRequestInput = { "networkServeTLS": boolean; };
export type Notebook = { "closed": boolean; "dueFlashcardCount": number; "encrypted": boolean; "flashcardCount": number; "icon": string; "id": string; "name": string; "newFlashcardCount": number; "sort": number; "sortMode": number; "state"?: "Locked" | "Unlocking" | "Unlocked" | "Locking" | "Error"; "subFileCount": number; "unlocked": boolean; };
+export type PinnedDoc = { "childrenSortMode": number | null; "icon": string; "id": string; "name": string; "notebook": string; "path": string; "subFileCount": number; "unavailable": boolean; };
+
export type PublishedBlockInfo = { "publishAccessRequired": true; "rootID": string; "rootIcon": string; "rootTitle": string; "rootTitleEmpty": boolean; };
export type RemoveBookmarkRequestInput = { "bookmark": string; };
@@ -94,6 +96,8 @@ export type UnfoldedParentData = { "parentID": string; };
export type UpdateChannelRequestInput = { "updateChannel": string; };
+export type UpdatePinnedDocsRequestInput = { "action": string; "after"?: boolean; "ids": Array<string>; "targetID"?: string; };
+
export type VirtualBlockRefRequestInput = { "keywords": Array<string>; };
export type WorkspaceInfoData = { "siyuanVer": string; "workspaceDir": string; };
@@ -792,6 +796,16 @@ export interface APIPOSTRoutes {
response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "json";
};
+ "/api/filetree/getPinnedDocs": {
+ request: EmptyRequestInput;
+ response: { "code": 0; "data": Array<PinnedDoc>; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "none";
+ };
+ "/api/filetree/updatePinnedDocs": {
+ request: UpdatePinnedDocsRequestInput;
+ response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
"/api/history/clearWorkspaceHistory": {
request: EmptyRequestInput;
response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
diff --git a/app/src/util/pinnedDocs.ts b/app/src/util/pinnedDocs.ts
new file mode 100644
index 0000000000..3bcd3493ec
--- /dev/null
+++ b/app/src/util/pinnedDocs.ts
@@ -0,0 +1,6 @@
+import {fetchSyncPost} from "./fetch";
+
+export const pinnedDocIDs = new Set<string>();
+
+export const updatePinnedDocs = (ids: string[], action: "pin" | "unpin", targetID = "", after = false) =>
+ fetchSyncPost("/api/filetree/updatePinnedDocs", {ids, action, targetID, after});
diff --git a/app/src/util/pinnedDocsDrop.test.ts b/app/src/util/pinnedDocsDrop.test.ts
new file mode 100644
index 0000000000..e70126e72a
--- /dev/null
+++ b/app/src/util/pinnedDocsDrop.test.ts
@@ -0,0 +1,15 @@
+import * as assert from "node:assert/strict";
+import test from "node:test";
+import {getPinnedDropPosition} from "./pinnedDocsDrop";
+
+test("root insertion creates pins while child insertion changes source order", () => {
+ assert.equal(getPinnedDropPosition(true, .1), "pin-before");
+ assert.equal(getPinnedDropPosition(true, .9), "pin-after");
+ assert.equal(getPinnedDropPosition(false, .1), "before");
+ assert.equal(getPinnedDropPosition(false, .9), "after");
+ for (const root of [false, true]) {
+ assert.equal(getPinnedDropPosition(root, .5), "inside");
+ assert.equal(getPinnedDropPosition(root, .25), "inside");
+ assert.equal(getPinnedDropPosition(root, .75), "inside");
+ }
+});
diff --git a/app/src/util/pinnedDocsDrop.ts b/app/src/util/pinnedDocsDrop.ts
new file mode 100644
index 0000000000..179fac2fb3
--- /dev/null
+++ b/app/src/util/pinnedDocsDrop.ts
@@ -0,0 +1,9 @@
+export const getPinnedDropPosition = (root: boolean, ratio: number) => {
+ if (ratio < .25) {
+ return root ? "pin-before" : "before";
+ }
+ if (ratio > .75) {
+ return root ? "pin-after" : "after";
+ }
+ return "inside";
+};
diff --git a/docs/PINNED-DOCUMENTS.md b/docs/PINNED-DOCUMENTS.md
new file mode 100644
index 0000000000..e54bf8a3ac
--- /dev/null
+++ b/docs/PINNED-DOCUMENTS.md
@@ -0,0 +1,44 @@
+# 文档树面板置顶区
+
+对应议题:https://github.com/siyuan-note/siyuan/issues/19401
+
+## 设计评审
+
+置顶区位于文档树面板顶部,以置顶文档为根展示真实子文档。根入口的顺序独立于文档层级和源文档排序;展开后的子文档直接使用源文档数据。桌面端和移动端共享置顶区实现,区域可折叠并限制最大高度,内部独立滚动。
+
+| 操作 | 行为 |
+|---|---|
+| 菜单置顶 | 新入口放在最顶部;已有入口移到最顶部,不重复创建 |
+| 根层插入线拖放 | 创建或调整置顶入口,源文档位置不变 |
+| 子文档之间插入线拖放 | 调整真实文档顺序,沿用现有排序冲突确认 |
+| 拖放到文档行中部 | 移入真实文档,沿用现有移动校验 |
+| 取消父文档置顶 | 只移除该根入口,单独置顶的子文档保留 |
+| 重命名或移动 | 所有入口重新读取源文档,跨笔记本移动维护笔记本标识 |
+| 关闭普通笔记本 | 保留不可用入口,允许取消置顶;当前会话保留已读取的标题,无法读取标题时显示文档 ID |
+| 删除文档或笔记本 | 清理相关入口;读取列表时也过滤不存在的源文档 |
+| 加密笔记本 | 不显示置顶操作,服务端拒绝新增,也不返回已有异常入口 |
+
+根层的拖放提示使用插入线,行中部使用文档高亮,明确区分创建入口和移动源文档。移动到自身或后代的校验交由已有文档移动接口执行。子文档列表按照源文档的有效排序加载;置顶操作不写入 `sort.json`,不改变排序继承。
+
+## 持久化与同步
+
+`data/storage/pinned-docs.json` 使用版本 1 格式:`{"version":1,"docs":[{"id":"文档 ID","notebook":"笔记本 ID"}]}`。数组顺序即根层顺序,仅保存标识,不缓存文档内容。文件进入现有数据同步和快照流程,服从工作区同步忽略规则;仅此文件发生同步变更时也刷新文档树面板。跨设备同时编辑沿用现有同步文件冲突处理机制。
+
+同一内核内的更新由互斥锁串行处理,接口接受相对位置操作,避免客户端提交整份旧列表覆盖其他窗口新增的入口。未知版本、错误结构或损坏文件返回错误并保留原文件。现有文档、加密、历史和备份格式均无变更。
+
+区域折叠和子树展开状态保存在本设备的浏览器存储中,不写入同步文件。不同置顶根下的同一子文档具有独立展开状态。
+
+## HTTP 接口
+
+两个接口均使用 POST,要求认证和管理员角色;写接口还检查只读状态。接口成功时 `code` 为 `0`,业务或参数错误为 `-1`。类型契约位于 `kernel/apicontract/`,生成声明同步到插件声明仓库。
+
+| 接口 | 请求 | 成功数据 |
+|---|---|---|
+| `/api/filetree/getPinnedDocs` | 无需请求体 | 数组,每项包含 `id`、`notebook`、`name`、`path`、`icon`、`subFileCount`、`unavailable`、`childrenSortMode` |
+| `/api/filetree/updatePinnedDocs` | `ids: string[]`、`action: "pin"或"unpin"`,可选 `targetID: string`、`after: boolean` | `null` |
+
+未指定目标时,置顶操作放到最顶部;指定目标时插入其前面,`after: true` 则插入其后面。取消置顶忽略位置参数。批量请求先校验所有源文档,失败时不写入部分结果。置顶区子树继续通过现有文档列表、移动和排序接口操作,不新增文档副本。
+
+## 验证范围
+
+回归覆盖入口去重和顺序、源排序不变、无效批量请求不产生部分更新、未知版本和损坏数据保留、关闭笔记本入口保留、加密笔记本拒绝和过滤、引用维护、同步路径纳入、根层与子树拖放分类、菜单目录及旧配置顺序迁移。接口测试使用真实处理函数检查响应契约,并执行已有接口兼容和路由覆盖测试。
diff --git a/kernel/api/pinned_docs.go b/kernel/api/pinned_docs.go
new file mode 100644
index 0000000000..dc68b1d0f8
--- /dev/null
+++ b/kernel/api/pinned_docs.go
@@ -0,0 +1,27 @@
+package api
+
+import (
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+ "github.com/siyuan-note/siyuan/kernel/model"
+)
+
+var getPinnedDocs = contractHandler(apicontract.GetPinnedDocs, func(c *gin.Context, _ apicontract.EmptyRequest) apicontract.Response[[]apicontract.PinnedDoc] {
+ docs, err := model.GetPinnedDocs()
+ if err != nil {
+ return apicontract.Failure[[]apicontract.PinnedDoc](-1, err.Error())
+ }
+ ret := []apicontract.PinnedDoc{}
+ for _, doc := range docs {
+ ret = append(ret, apicontract.PinnedDoc{ID: doc.ID, Notebook: doc.Notebook, Name: doc.Name, Path: doc.Path,
+ Icon: doc.Icon, SubFileCount: doc.SubFileCount, Unavailable: doc.Unavailable, ChildrenSortMode: doc.ChildrenSortMode})
+ }
+ return apicontract.Success(ret)
+})
+
+var updatePinnedDocs = contractHandler(apicontract.UpdatePinnedDocs, func(c *gin.Context, request apicontract.UpdatePinnedDocsRequest) apicontract.Response[apicontract.Null] {
+ if err := model.UpdatePinnedDocs(request.IDs, request.Action, request.TargetID, request.After); err != nil {
+ return apicontract.Failure[apicontract.Null](-1, err.Error())
+ }
+ return apicontract.Success(apicontract.Null{})
+})
diff --git a/kernel/api/pinned_docs_test.go b/kernel/api/pinned_docs_test.go
new file mode 100644
index 0000000000..232dc18783
--- /dev/null
+++ b/kernel/api/pinned_docs_test.go
@@ -0,0 +1,35 @@
+package api
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestAPIContractPinnedDocs(t *testing.T) {
+ previous := util.DataDir
+ util.DataDir = t.TempDir()
+ t.Cleanup(func() { util.DataDir = previous })
+ gin.SetMode(gin.TestMode)
+ engine := gin.New()
+ engine.POST("/api/filetree/getPinnedDocs", getPinnedDocs)
+ engine.POST("/api/filetree/updatePinnedDocs", updatePinnedDocs)
+ response := httptest.NewRecorder()
+ engine.ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/api/filetree/getPinnedDocs", nil))
+ requireAPIContract(t, http.MethodPost, "/api/filetree/getPinnedDocs", response)
+ if !strings.Contains(response.Body.String(), `"data":[]`) {
+ t.Fatal(response.Body.String())
+ }
+ for _, body := range []string{`{}`, `{"ids":[],"action":"pin"}`, `{"ids":[null],"action":"pin"}`, `{"ids":["invalid"],"action":"pin"}`} {
+ response = httptest.NewRecorder()
+ engine.ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/api/filetree/updatePinnedDocs", strings.NewReader(body)))
+ requireAPIContract(t, http.MethodPost, "/api/filetree/updatePinnedDocs", response)
+ if !strings.Contains(response.Body.String(), `"code":-1`) {
+ t.Fatal(response.Body.String())
+ }
+ }
+}
diff --git a/kernel/api/router.go b/kernel/api/router.go
index 517e045a57..3a6e7ad2a4 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -160,6 +160,8 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/notebook/touchEncryptedNotebooks", model.CheckAuth, model.CheckAdminRole, touchEncryptedNotebooks)
ginServer.Handle("POST", "/api/filetree/searchDocs", model.CheckAuth, searchDocs)
+ ginServer.Handle("POST", "/api/filetree/getPinnedDocs", model.CheckAuth, model.CheckAdminRole, getPinnedDocs)
+ ginServer.Handle("POST", "/api/filetree/updatePinnedDocs", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, updatePinnedDocs)
ginServer.Handle("POST", "/api/filetree/listDocsByPath", model.CheckAuth, listDocsByPath)
ginServer.Handle("POST", "/api/filetree/getDoc", model.CheckAuth, getDoc)
ginServer.Handle("POST", "/api/filetree/getDocCreateSavePath", model.CheckAuth, getDocCreateSavePath)
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index 4abc4ba2b5..a2e44c116e 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -35,6 +35,11 @@ type ResponseOptions struct {
var definitions []Definition
+var (
+ GetPinnedDocs = define[EmptyRequest, []PinnedDoc]("getPinnedDocs", "/api/filetree/getPinnedDocs", NoBody, ResponseOptions{NonNullable: true}, "POST")
+ UpdatePinnedDocs = define[UpdatePinnedDocsRequest, Null]("updatePinnedDocs", "/api/filetree/updatePinnedDocs", JSONBody, ResponseOptions{}, "POST")
+)
+
func define[Request, Data any](name, path string, body BodyMode, response ResponseOptions, methods ...string) Endpoint[Request, Data] {
d := Definition{Name: name, Path: path, Methods: methods, Body: body,
Request: reflect.TypeFor[Request](), Data: reflect.TypeFor[Data](),
diff --git a/kernel/apicontract/pinned_docs.go b/kernel/apicontract/pinned_docs.go
new file mode 100644
index 0000000000..a21efb99d4
--- /dev/null
+++ b/kernel/apicontract/pinned_docs.go
@@ -0,0 +1,19 @@
+package apicontract
+
+type PinnedDoc struct {
+ ID string `json:"id"`
+ Notebook string `json:"notebook"`
+ Name string `json:"name"`
+ Path string `json:"path"`
+ Icon string `json:"icon"`
+ SubFileCount int `json:"subFileCount"`
+ Unavailable bool `json:"unavailable"`
+ ChildrenSortMode *int `json:"childrenSortMode"`
+}
+
+type UpdatePinnedDocsRequest struct {
+ IDs []string `json:"ids"`
+ Action string `json:"action"`
+ TargetID string `json:"targetID" api:"optional"`
+ After bool `json:"after" api:"optional"`
+}
diff --git a/kernel/apicontract/pinned_docs_test.go b/kernel/apicontract/pinned_docs_test.go
new file mode 100644
index 0000000000..bc01022744
--- /dev/null
+++ b/kernel/apicontract/pinned_docs_test.go
@@ -0,0 +1,17 @@
+package apicontract
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestPinnedDocsContract(t *testing.T) {
+ for _, body := range []string{`{}`, `{"ids":null,"action":"pin"}`, `{"ids":[null],"action":"pin"}`, `{"ids":["id"],"action":"pin","after":"true"}`} {
+ if _, err := UpdatePinnedDocs.Decode(strings.NewReader(body)); err == nil {
+ t.Fatalf("invalid request accepted: %s", body)
+ }
+ }
+ if _, err := UpdatePinnedDocs.Decode(strings.NewReader(`{"ids":["id"],"action":"pin"}`)); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index eac15f4297..b68fe1e1d4 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -651,6 +651,53 @@
],
"additionalProperties": false
},
+ "PinnedDoc": {
+ "type": "object",
+ "properties": {
+ "childrenSortMode": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "icon": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "notebook": {
+ "type": "string"
+ },
+ "path": {
+ "type": "string"
+ },
+ "subFileCount": {
+ "type": "integer"
+ },
+ "unavailable": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "childrenSortMode",
+ "icon",
+ "id",
+ "name",
+ "notebook",
+ "path",
+ "subFileCount",
+ "unavailable"
+ ],
+ "additionalProperties": false
+ },
"PublishedBlockInfo": {
"type": "object",
"properties": {
@@ -970,6 +1017,31 @@
],
"additionalProperties": false
},
+ "UpdatePinnedDocsRequestInput": {
+ "type": "object",
+ "properties": {
+ "action": {
+ "type": "string"
+ },
+ "after": {
+ "type": "boolean"
+ },
+ "ids": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "targetID": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "action",
+ "ids"
+ ],
+ "additionalProperties": false
+ },
"VirtualBlockRefRequestInput": {
"type": "object",
"properties": {
@@ -2713,6 +2785,159 @@
]
}
},
+ {
+ "method": "POST",
+ "path": "/api/filetree/getPinnedDocs",
+ "handler": "getPinnedDocs",
+ "body": "none",
+ "request": {
+ "$ref": "#/$defs/EmptyRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/PinnedDoc"
+ }
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
+ {
+ "method": "POST",
+ "path": "/api/filetree/updatePinnedDocs",
+ "handler": "updatePinnedDocs",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/UpdatePinnedDocsRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "type": "null"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
{
"method": "POST",
"path": "/api/history/clearWorkspaceHistory",
diff --git a/kernel/model/file.go b/kernel/model/file.go
index a4f394d8b2..4500468d5a 100644
--- a/kernel/model/file.go
+++ b/kernel/model/file.go
@@ -2124,6 +2124,11 @@ func removeDoc(box *Box, p string, luteEngine *lute.Lute) (ret *parse.Tree, err
return
}
logging.LogInfof("removed doc [%s%s]", box.ID, p)
+ removedPins := map[string]bool{}
+ for rootID := range removedRootPaths {
+ removedPins[rootID] = true
+ }
+ maintainPinnedDocs(removedPins, "", "")
box.removeSort(removeIDs)
if "/" != dir {
@@ -2565,6 +2570,11 @@ func moveSorts(rootID, fromBox, toBox string) {
fromRootSorts := map[string]int{}
ids := treenode.RootChildIDs(rootID)
+ movedPins := map[string]bool{rootID: true}
+ for _, id := range ids {
+ movedPins[id] = true
+ }
+ maintainPinnedDocs(movedPins, "", toBox)
fromConfPath := filepath.Join(util.DataDir, fromBox, ".siyuan", "sort.json")
fromFullSortIDs, err := readSortConfMap(fromConfPath)
if err != nil {
diff --git a/kernel/model/mount.go b/kernel/model/mount.go
index a768c86365..0fdf1688ca 100644
--- a/kernel/model/mount.go
+++ b/kernel/model/mount.go
@@ -356,6 +356,7 @@ func RemoveBox(boxID string) (err error) {
if err = removeBoxDir(localPath); err != nil {
return
}
+ maintainPinnedDocs(nil, boxID, "")
// 目录删除成功后再清理,避免删除失败时提前移除数据库条目。
flushDeletedAttributeViewBlocks(deletedAttrViewBlockIDs)
// 加密笔记本删除时清理其独立加密 db 文件(含 WAL/SHM),避免残留
diff --git a/kernel/model/pinned_docs.go b/kernel/model/pinned_docs.go
new file mode 100644
index 0000000000..a8b75c5ef4
--- /dev/null
+++ b/kernel/model/pinned_docs.go
@@ -0,0 +1,249 @@
+package model
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "sync"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/filelock"
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+type pinnedDocRef struct {
+ ID string `json:"id"`
+ Notebook string `json:"notebook"`
+}
+
+type pinnedDocsStorage struct {
+ Version int `json:"version"`
+ Docs []pinnedDocRef `json:"docs"`
+}
+
+type PinnedDoc struct {
+ ID, Notebook, Name, Path, Icon string
+ SubFileCount int
+ Unavailable bool
+ ChildrenSortMode *int
+}
+
+var pinnedDocsLock sync.Mutex
+
+func readPinnedDocs() (ret pinnedDocsStorage, err error) {
+ ret = pinnedDocsStorage{Version: 1, Docs: []pinnedDocRef{}}
+ data, err := filelock.ReadFile(filepath.Join(util.DataDir, "storage", "pinned-docs.json"))
+ if os.IsNotExist(err) {
+ return ret, nil
+ }
+ if err != nil {
+ return
+ }
+ ret = pinnedDocsStorage{}
+ if err = json.Unmarshal(data, &ret); err != nil {
+ return
+ }
+ if ret.Version != 1 || ret.Docs == nil {
+ return ret, fmt.Errorf("unsupported pinned documents version [%d]", ret.Version)
+ }
+ seen := map[string]bool{}
+ for _, doc := range ret.Docs {
+ if !ast.IsNodeIDPattern(doc.ID) || !ast.IsNodeIDPattern(doc.Notebook) || seen[doc.ID] {
+ return ret, fmt.Errorf("invalid pinned document [%s]", doc.ID)
+ }
+ seen[doc.ID] = true
+ }
+ return
+}
+
+func writePinnedDocs(data pinnedDocsStorage) error {
+ encoded, err := json.Marshal(data)
+ if err != nil {
+ return err
+ }
+ dir := filepath.Join(util.DataDir, "storage")
+ if err = os.MkdirAll(dir, 0755); err != nil {
+ return err
+ }
+ if err = filelock.WriteFile(filepath.Join(dir, "pinned-docs.json"), encoded); err != nil {
+ return err
+ }
+ IncSyncIfNeeded(filepath.Join(dir, "pinned-docs.json"))
+ util.BroadcastByType("filetree", "pinnedDocsChanged", 0, "", nil)
+ return nil
+}
+
+// 置顶只保存普通文档的标识,名称和子文档始终从源文档读取。
+func GetPinnedDocs() (ret []PinnedDoc, err error) {
+ pinnedDocsLock.Lock()
+ defer pinnedDocsLock.Unlock()
+ ret = []PinnedDoc{}
+ stored, err := readPinnedDocs()
+ if err != nil {
+ return nil, err
+ }
+ if len(stored.Docs) == 0 {
+ return ret, nil
+ }
+ notebooks, err := ListNotebooks()
+ if err != nil {
+ return nil, err
+ }
+ boxes := map[string]*Box{}
+ for _, box := range notebooks {
+ boxes[box.ID] = box
+ }
+ for _, ref := range stored.Docs {
+ boxID := ref.Notebook
+ bt := treenode.GetBlockTree(ref.ID)
+ if bt != nil {
+ boxID = bt.BoxID
+ }
+ box := boxes[boxID]
+ if box == nil || IsEncryptedBox(boxID) {
+ continue
+ }
+ doc := PinnedDoc{ID: ref.ID, Notebook: boxID, Name: ref.ID, Unavailable: box.Closed}
+ if box.Closed {
+ ret = append(ret, doc)
+ continue
+ }
+ if !isSortableDocument(bt) {
+ continue
+ }
+ info := box.Stat(bt.Path)
+ if info == nil {
+ continue
+ }
+ ial := box.docIAL(bt.Path)
+ if ial == nil {
+ return nil, fmt.Errorf("cannot read pinned document [%s]", ref.ID)
+ }
+ file := box.docFromFileInfo(info, ial)
+ if file == nil {
+ return nil, fmt.Errorf("cannot read pinned document [%s]", ref.ID)
+ }
+ doc.Name, doc.Path, doc.Icon = file.Name, file.Path, file.Icon
+ doc.ChildrenSortMode = file.ChildrenSortMode
+ if file.TitleEmpty {
+ doc.Name = Conf.Language(16)
+ }
+ entries, readErr := os.ReadDir(filepath.Join(util.DataDir, boxID, strings.TrimSuffix(bt.Path, ".sy")))
+ if readErr != nil && !os.IsNotExist(readErr) {
+ return nil, readErr
+ }
+ for _, entry := range entries {
+ if !entry.IsDir() && strings.HasSuffix(entry.Name(), ".sy") && ast.IsNodeIDPattern(strings.TrimSuffix(entry.Name(), ".sy")) {
+ doc.SubFileCount++
+ }
+ }
+ ret = append(ret, doc)
+ }
+ return
+}
+
+// 根层顺序独立于源文档顺序,按相对位置更新以保留其他窗口新增的入口。
+func UpdatePinnedDocs(ids []string, action, targetID string, after bool) error {
+ if len(ids) == 0 {
+ return fmt.Errorf("document IDs are required")
+ }
+ if action != "pin" && action != "unpin" {
+ return fmt.Errorf("invalid pinned document action")
+ }
+ pinnedDocsLock.Lock()
+ defer pinnedDocsLock.Unlock()
+ stored, err := readPinnedDocs()
+ if err != nil {
+ return err
+ }
+ selected := map[string]bool{}
+ refs := []pinnedDocRef{}
+ for _, id := range ids {
+ if !ast.IsNodeIDPattern(id) {
+ return fmt.Errorf("invalid document ID [%s]", id)
+ }
+ if selected[id] {
+ continue
+ }
+ selected[id] = true
+ if action == "unpin" {
+ continue
+ }
+ bt := treenode.GetBlockTree(id)
+ if !isSortableDocument(bt) || IsEncryptedBox(bt.BoxID) {
+ return fmt.Errorf("document [%s] cannot be pinned", id)
+ }
+ box := Conf.Box(bt.BoxID)
+ if box == nil || box.Stat(bt.Path) == nil {
+ return fmt.Errorf("document [%s] is unavailable", id)
+ }
+ refs = append(refs, pinnedDocRef{ID: id, Notebook: bt.BoxID})
+ }
+ if action == "pin" && selected[targetID] {
+ return nil
+ }
+ remaining := []pinnedDocRef{}
+ for _, ref := range stored.Docs {
+ if !selected[ref.ID] {
+ remaining = append(remaining, ref)
+ }
+ }
+ index := 0
+ if targetID != "" && action == "pin" {
+ index = -1
+ for i, ref := range remaining {
+ if ref.ID == targetID {
+ index = i
+ break
+ }
+ }
+ if index < 0 {
+ return fmt.Errorf("pinned target [%s] is unavailable", targetID)
+ }
+ if after {
+ index++
+ }
+ }
+ result := append([]pinnedDocRef{}, remaining[:index]...)
+ result = append(result, refs...)
+ result = append(result, remaining[index:]...)
+ if slices.Equal(stored.Docs, result) {
+ return nil
+ }
+ stored.Docs = result
+ return writePinnedDocs(stored)
+}
+
+// 源文档删除或跨笔记本移动后维护入口,异常配置保留原文件并记录错误。
+func maintainPinnedDocs(ids map[string]bool, notebook, destination string) {
+ pinnedDocsLock.Lock()
+ defer pinnedDocsLock.Unlock()
+ stored, err := readPinnedDocs()
+ if err != nil {
+ logging.LogErrorf("read pinned documents failed: %s", err)
+ return
+ }
+ ret := []pinnedDocRef{}
+ changed := false
+ for _, ref := range stored.Docs {
+ if ids[ref.ID] || notebook != "" && ref.Notebook == notebook {
+ changed = true
+ if destination == "" {
+ continue
+ }
+ ref.Notebook = destination
+ }
+ ret = append(ret, ref)
+ }
+ if changed {
+ stored.Docs = ret
+ if err = writePinnedDocs(stored); err != nil {
+ logging.LogErrorf("write pinned documents failed: %s", err)
+ }
+ }
+}
diff --git a/kernel/model/pinned_docs_test.go b/kernel/model/pinned_docs_test.go
new file mode 100644
index 0000000000..c655f6d4ef
--- /dev/null
+++ b/kernel/model/pinned_docs_test.go
@@ -0,0 +1,131 @@
+package model
+
+import (
+ "os"
+ "path/filepath"
+ "reflect"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestPinnedDocsOrderIsIndependent(t *testing.T) {
+ f := setupFileOperationTest(t)
+ before, _, err := ListDocTree(f.box.ID, "/", util.SortModeNameASC, false, true, 100)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, id := range []string{f.sourceID, f.targetID, f.sourceID} {
+ if err = UpdatePinnedDocs([]string{id}, "pin", "", false); err != nil {
+ t.Fatal(err)
+ }
+ }
+ stored, err := readPinnedDocs()
+ if err != nil || len(stored.Docs) != 2 || stored.Docs[0].ID != f.sourceID {
+ t.Fatalf("unexpected pins: %+v, %v", stored, err)
+ }
+ if err = UpdatePinnedDocs([]string{f.sourceID}, "pin", f.targetID, true); err != nil {
+ t.Fatal(err)
+ }
+ stored, _ = readPinnedDocs()
+ if stored.Docs[0].ID != f.targetID {
+ t.Fatal("relative reorder failed")
+ }
+ if err = UpdatePinnedDocs([]string{f.targetID}, "unpin", "", false); err != nil {
+ t.Fatal(err)
+ }
+ stored, _ = readPinnedDocs()
+ if len(stored.Docs) != 1 || stored.Docs[0].ID != f.sourceID {
+ t.Fatal("unpin removed another entry")
+ }
+ after, _, err := ListDocTree(f.box.ID, "/", util.SortModeNameASC, false, true, 100)
+ if err != nil || !reflect.DeepEqual(before, after) {
+ t.Fatalf("pinning changed source tree: %v", err)
+ }
+ if !PathsAffectSync(filepath.Join(util.DataDir, "storage", "pinned-docs.json")) {
+ t.Fatal("pinned documents are not synchronized")
+ }
+}
+
+func TestPinnedDocsPreserveInvalidStorage(t *testing.T) {
+ f := setupFileOperationTest(t)
+ file := filepath.Join(util.DataDir, "storage", "pinned-docs.json")
+ if err := os.MkdirAll(filepath.Dir(file), 0755); err != nil {
+ t.Fatal(err)
+ }
+ for _, data := range []string{`{`, `null`, `{"version":2,"docs":[]}`, `{"docs":[]}`, `{"version":1,"docs":[{"id":"../bad","notebook":"bad"}]}`} {
+ if err := os.WriteFile(file, []byte(data), 0644); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := GetPinnedDocs(); err == nil {
+ t.Fatalf("accepted invalid storage: %s", data)
+ }
+ if err := UpdatePinnedDocs([]string{f.sourceID}, "pin", "", false); err == nil {
+ t.Fatal("overwrote invalid storage")
+ }
+ actual, _ := os.ReadFile(file)
+ if string(actual) != data {
+ t.Fatal("original storage changed")
+ }
+ }
+}
+
+func TestPinnedDocsValidateAndMaintainReferences(t *testing.T) {
+ f := setupFileOperationTest(t)
+ if err := UpdatePinnedDocs([]string{f.sourceID}, "pin", "", false); err != nil {
+ t.Fatal(err)
+ }
+ for _, ids := range [][]string{{}, {"invalid"}, {f.targetID, "20260913000000-abcdefg"}} {
+ if err := UpdatePinnedDocs(ids, "pin", "", false); err == nil {
+ t.Fatal("invalid batch accepted")
+ }
+ }
+ stored, _ := readPinnedDocs()
+ if len(stored.Docs) != 1 {
+ t.Fatal("failed batch changed pins")
+ }
+ docs, err := GetPinnedDocs()
+ if err != nil || len(docs) != 1 || docs[0].ID != f.sourceID || docs[0].Path == "" {
+ t.Fatalf("cannot resolve pin: %+v, %v", docs, err)
+ }
+ maintainPinnedDocs(map[string]bool{f.sourceID: true}, "", "20260913000001-abcdefg")
+ stored, _ = readPinnedDocs()
+ if stored.Docs[0].Notebook != "20260913000001-abcdefg" {
+ t.Fatal("move did not update notebook")
+ }
+ maintainPinnedDocs(nil, "20260913000001-abcdefg", "")
+ stored, _ = readPinnedDocs()
+ if len(stored.Docs) != 0 {
+ t.Fatal("deleted notebook retained pins")
+ }
+}
+
+func TestPinnedDocsClosedAndEncryptedNotebook(t *testing.T) {
+ f := setupFileOperationTest(t)
+ t.Cleanup(func() { forgetRuntimeEncryptedBox(f.box.ID); forgetRuntimeNormalBox(f.box.ID) })
+ if err := UpdatePinnedDocs([]string{f.sourceID}, "pin", "", false); err != nil {
+ t.Fatal(err)
+ }
+ boxConf := f.box.GetConf()
+ boxConf.Closed = true
+ if err := f.box.SaveConf(boxConf); err != nil {
+ t.Fatal(err)
+ }
+ docs, err := GetPinnedDocs()
+ if err != nil || len(docs) != 1 || !docs[0].Unavailable {
+ t.Fatalf("closed notebook lost pin: %+v, %v", docs, err)
+ }
+ boxConf.Encrypted = true
+ forgetRuntimeNormalBox(f.box.ID)
+ if err := f.box.SaveConf(boxConf); err != nil {
+ t.Fatal(err)
+ }
+ forgetRuntimeNormalBox(f.box.ID)
+ if err := UpdatePinnedDocs([]string{f.sourceID}, "pin", "", false); err == nil {
+ t.Fatal("encrypted document accepted")
+ }
+ docs, err = GetPinnedDocs()
+ if err != nil || len(docs) != 0 {
+ t.Fatalf("encrypted document exposed: %+v, %v", docs, err)
+ }
+}
diff --git a/kernel/model/repository.go b/kernel/model/repository.go
index f901e4bbb5..8c34e5e458 100644
--- a/kernel/model/repository.go
+++ b/kernel/model/repository.go
@@ -2458,6 +2458,9 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,
removedBoxConfs, removedBoxCryptoBackups := map[string]bool{}, map[string]bool{}
for _, file := range mergeResult.Upserts {
upserts = append(upserts, file.Path)
+ if file.Path == "/storage/pinned-docs.json" {
+ needReloadFiletree = true
+ }
if strings.HasPrefix(file.Path, "/storage/riff/") {
needReloadFlashcard = true
}
@@ -2531,6 +2534,9 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,
unloadPluginSet, uninstallPluginSet := hashset.New(), hashset.New()
for _, file := range mergeResult.Removes {
removes = append(removes, file.Path)
+ if file.Path == "/storage/pinned-docs.json" {
+ needReloadFiletree = true
+ }
if strings.HasPrefix(file.Path, "/storage/riff/") {
needReloadFlashcard = true
}