Skip to content

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

:sparkles: Add editable top-level notebook documents https://github.com/siyuan-note/siyuan/issues/18266

Daniel914f5bf80e17
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 0eed482fff..e9689366ab 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -2194,6 +2194,7 @@
"337": "المسار المحدد ليس مجلدًا",
"338": "مسار Vault المحدد غير مدعوم؛ اختر مجلدًا عاديًا خارج مساحة عمل SiYuan",
"339": "يتم دعم Obsidian Vaults التي تستخدم مجلد .obsidian الافتراضي فقط",
- "340": "لا يحتوي Vault المحدد على ملف Markdown غير مخفي يمكن قراءته"
+ "340": "لا يحتوي Vault المحدد على ملف Markdown غير مخفي يمكن قراءته",
+ "341": "لا يمكن حذف مستند دفتر الملاحظات ذي المستوى الأعلى أو نقله"
}
}
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index d1a13e6b7d..30525ba90f 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -2194,6 +2194,7 @@
"337": "Der ausgewählte Pfad ist kein Ordner",
"338": "Der ausgewählte Vault-Pfad wird nicht unterstützt; wähle einen normalen Ordner außerhalb des SiYuan-Arbeitsbereichs",
"339": "Es werden nur Obsidian Vaults mit dem standardmäßigen .obsidian-Ordner unterstützt",
- "340": "Der ausgewählte Vault enthält keine lesbare, nicht ausgeblendete Markdown-Datei"
+ "340": "Der ausgewählte Vault enthält keine lesbare, nicht ausgeblendete Markdown-Datei",
+ "341": "Das Notizbuchdokument auf oberster Ebene kann nicht gelöscht oder verschoben werden"
}
}
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 379fad646d..54ceb7eb9b 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -2194,6 +2194,7 @@
"337": "The selected path is not a directory",
"338": "The selected Vault path is not supported; select a normal directory outside the SiYuan workspace",
"339": "Only Obsidian Vaults using the default .obsidian directory are supported",
- "340": "The selected Vault does not contain a readable non-hidden Markdown file"
+ "340": "The selected Vault does not contain a readable non-hidden Markdown file",
+ "341": "The top-level notebook document cannot be removed or moved"
}
}
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index cd8169217b..65de631532 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -2194,6 +2194,7 @@
"337": "La ruta seleccionada no es una carpeta",
"338": "La ruta del Vault seleccionado no es compatible; selecciona una carpeta normal fuera del espacio de trabajo de SiYuan",
"339": "Solo se admiten Obsidian Vaults que utilicen la carpeta .obsidian predeterminada",
- "340": "El Vault seleccionado no contiene ningún archivo Markdown legible y no oculto"
+ "340": "El Vault seleccionado no contiene ningún archivo Markdown legible y no oculto",
+ "341": "El documento de nivel superior del cuaderno no se puede eliminar ni mover"
}
}
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 61564f06be..63737814ea 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -2194,6 +2194,7 @@
"337": "Le chemin sélectionné n’est pas un dossier",
"338": "Le chemin du Vault sélectionné n’est pas pris en charge ; sélectionnez un dossier normal en dehors de l’espace de travail SiYuan",
"339": "Seuls les Obsidian Vaults utilisant le dossier .obsidian par défaut sont pris en charge",
- "340": "Le Vault sélectionné ne contient aucun fichier Markdown lisible et non masqué"
+ "340": "Le Vault sélectionné ne contient aucun fichier Markdown lisible et non masqué",
+ "341": "Le document de niveau supérieur du carnet ne peut pas être supprimé ni déplacé"
}
}
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index f347828eb9..814bdf66a8 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -2194,6 +2194,7 @@
"337": "הנתיב שנבחר אינו תיקייה",
"338": "נתיב ה־Vault שנבחר אינו נתמך; יש לבחור תיקייה רגילה מחוץ למרחב העבודה של SiYuan",
"339": "נתמכים רק Obsidian Vaults המשתמשים בתיקיית ברירת המחדל .obsidian",
- "340": "ה־Vault שנבחר אינו מכיל קובץ Markdown קריא שאינו מוסתר"
+ "340": "ה־Vault שנבחר אינו מכיל קובץ Markdown קריא שאינו מוסתר",
+ "341": "לא ניתן למחוק או להעביר את מסמך המחברת ברמה העליונה"
}
}
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 548846c538..b909b51100 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -2194,6 +2194,7 @@
"337": "चुना गया पथ कोई फ़ोल्डर नहीं है",
"338": "चुना गया Vault पथ समर्थित नहीं है; SiYuan कार्यस्थान के बाहर कोई सामान्य फ़ोल्डर चुनें",
"339": "केवल डिफ़ॉल्ट .obsidian फ़ोल्डर का उपयोग करने वाले Obsidian Vault समर्थित हैं",
- "340": "चुने गए Vault में पढ़ने योग्य गैर-छिपी Markdown फ़ाइल नहीं है"
+ "340": "चुने गए Vault में पढ़ने योग्य गैर-छिपी Markdown फ़ाइल नहीं है",
+ "341": "शीर्ष-स्तरीय नोटबुक दस्तावेज़ को हटाया या स्थानांतरित नहीं किया जा सकता"
}
}
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 70818e70a1..6f2b273509 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -2194,6 +2194,7 @@
"337": "Jalur yang dipilih bukan folder",
"338": "Jalur Vault yang dipilih tidak didukung; pilih folder biasa di luar ruang kerja SiYuan",
"339": "Hanya Obsidian Vault yang menggunakan folder .obsidian bawaan yang didukung",
- "340": "Vault yang dipilih tidak berisi file Markdown tak tersembunyi yang dapat dibaca"
+ "340": "Vault yang dipilih tidak berisi file Markdown tak tersembunyi yang dapat dibaca",
+ "341": "Dokumen buku catatan tingkat teratas tidak dapat dihapus atau dipindahkan"
}
}
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index ad3c267f7e..a576b0d638 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -2194,6 +2194,7 @@
"337": "Il percorso selezionato non è una cartella",
"338": "Il percorso del Vault selezionato non è supportato; seleziona una cartella normale esterna allo spazio di lavoro di SiYuan",
"339": "Sono supportati solo gli Obsidian Vault che utilizzano la cartella .obsidian predefinita",
- "340": "Il Vault selezionato non contiene file Markdown leggibili e non nascosti"
+ "340": "Il Vault selezionato non contiene file Markdown leggibili e non nascosti",
+ "341": "Il documento di primo livello del taccuino non può essere eliminato o spostato"
}
}
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 128562b2d6..221487718a 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -2194,6 +2194,7 @@
"337": "選択したパスはフォルダーではありません",
"338": "選択した Vault のパスはサポートされていません。SiYuan ワークスペース外の通常のフォルダーを選択してください",
"339": "既定の .obsidian フォルダーを使用する Obsidian Vault のみサポートされています",
- "340": "選択した Vault に読み取り可能な非表示ではない Markdown ファイルがありません"
+ "340": "選択した Vault に読み取り可能な非表示ではない Markdown ファイルがありません",
+ "341": "最上位のノートブック文書は削除または移動できません"
}
}
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 2247bc99e2..598c288602 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -2194,6 +2194,7 @@
"337": "선택한 경로가 폴더가 아닙니다",
"338": "선택한 Vault 경로는 지원되지 않습니다. SiYuan 작업 공간 외부의 일반 폴더를 선택하세요",
"339": "기본 .obsidian 폴더를 사용하는 Obsidian Vault만 지원됩니다",
- "340": "선택한 Vault에 읽을 수 있는 숨김이 아닌 Markdown 파일이 없습니다"
+ "340": "선택한 Vault에 읽을 수 있는 숨김이 아닌 Markdown 파일이 없습니다",
+ "341": "최상위 노트북 문서는 삭제하거나 이동할 수 없습니다"
}
}
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index b9f11520b6..164a5bdfaf 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -2194,6 +2194,7 @@
"337": "Het geselecteerde pad is geen map",
"338": "Het geselecteerde Vault-pad wordt niet ondersteund; selecteer een normale map buiten de SiYuan-werkruimte",
"339": "Alleen Obsidian Vaults die de standaardmap .obsidian gebruiken worden ondersteund",
- "340": "De geselecteerde Vault bevat geen leesbaar, niet-verborgen Markdown-bestand"
+ "340": "De geselecteerde Vault bevat geen leesbaar, niet-verborgen Markdown-bestand",
+ "341": "Het notebookdocument op het hoogste niveau kan niet worden verwijderd of verplaatst"
}
}
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 7ca39f7a14..0a9aae6b15 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -2194,6 +2194,7 @@
"337": "Wybrana ścieżka nie jest folderem",
"338": "Wybrana ścieżka Vault nie jest obsługiwana; wybierz zwykły folder poza obszarem roboczym SiYuan",
"339": "Obsługiwane są tylko Obsidian Vaults używające domyślnego folderu .obsidian",
- "340": "Wybrany Vault nie zawiera czytelnego, nieukrytego pliku Markdown"
+ "340": "Wybrany Vault nie zawiera czytelnego, nieukrytego pliku Markdown",
+ "341": "Dokument notatnika najwyższego poziomu nie może zostać usunięty ani przeniesiony"
}
}
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 4179081a67..27042f2e98 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -2194,6 +2194,7 @@
"337": "O caminho selecionado não é uma pasta",
"338": "O caminho do Vault selecionado não é compatível; selecione uma pasta normal fora do espaço de trabalho do SiYuan",
"339": "Somente Obsidian Vaults que usam a pasta .obsidian padrão são compatíveis",
- "340": "O Vault selecionado não contém um arquivo Markdown legível e não oculto"
+ "340": "O Vault selecionado não contém um arquivo Markdown legível e não oculto",
+ "341": "O documento de nível superior do caderno não pode ser removido nem movido"
}
}
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 9ded0a0812..30c33259c4 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -2194,6 +2194,7 @@
"337": "Выбранный путь не является папкой",
"338": "Выбранный путь Vault не поддерживается; выберите обычную папку за пределами рабочего пространства SiYuan",
"339": "Поддерживаются только Obsidian Vaults со стандартной папкой .obsidian",
- "340": "В выбранном Vault нет читаемого нескрытого файла Markdown"
+ "340": "В выбранном Vault нет читаемого нескрытого файла Markdown",
+ "341": "Документ блокнота верхнего уровня нельзя удалить или переместить"
}
}
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 1cabb9d319..8780e34829 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -2194,6 +2194,7 @@
"337": "Vybraná cesta nie je priečinok",
"338": "Vybraná cesta k Vault nie je podporovaná; vyberte bežný priečinok mimo pracovného priestoru SiYuan",
"339": "Podporované sú iba Obsidian Vaults používajúce predvolený priečinok .obsidian",
- "340": "Vybraný Vault neobsahuje čitateľný neskrývaný súbor Markdown"
+ "340": "Vybraný Vault neobsahuje čitateľný neskrývaný súbor Markdown",
+ "341": "Dokument zápisníka najvyššej úrovne nemožno odstrániť ani presunúť"
}
}
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 71118e821a..1ea3bd2d92 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -2194,6 +2194,7 @@
"337": "เส้นทางที่เลือกไม่ใช่โฟลเดอร์",
"338": "ไม่รองรับเส้นทาง Vault ที่เลือก โปรดเลือกโฟลเดอร์ปกติที่อยู่นอกพื้นที่ทำงาน SiYuan",
"339": "รองรับเฉพาะ Obsidian Vault ที่ใช้โฟลเดอร์ .obsidian เริ่มต้นเท่านั้น",
- "340": "Vault ที่เลือกไม่มีไฟล์ Markdown ที่อ่านได้และไม่ถูกซ่อน"
+ "340": "Vault ที่เลือกไม่มีไฟล์ Markdown ที่อ่านได้และไม่ถูกซ่อน",
+ "341": "ไม่สามารถลบหรือย้ายเอกสารสมุดบันทึกระดับบนสุดได้"
}
}
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 9f4e13f348..0910395b3f 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -2194,6 +2194,7 @@
"337": "Seçilen yol bir klasör değil",
"338": "Seçilen Vault yolu desteklenmiyor; SiYuan çalışma alanının dışında normal bir klasör seçin",
"339": "Yalnızca varsayılan .obsidian klasörünü kullanan Obsidian Vaults desteklenir",
- "340": "Seçilen Vault, okunabilir ve gizli olmayan bir Markdown dosyası içermiyor"
+ "340": "Seçilen Vault, okunabilir ve gizli olmayan bir Markdown dosyası içermiyor",
+ "341": "Üst düzey not defteri belgesi silinemez veya taşınamaz"
}
}
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index a78c66b5d9..434e6600c7 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -2194,6 +2194,7 @@
"337": "Вибраний шлях не є папкою",
"338": "Вибраний шлях Vault не підтримується; виберіть звичайну папку поза робочим простором SiYuan",
"339": "Підтримуються лише Obsidian Vaults зі стандартною папкою .obsidian",
- "340": "У вибраному Vault немає придатного для читання неприхованого файлу Markdown"
+ "340": "У вибраному Vault немає придатного для читання неприхованого файлу Markdown",
+ "341": "Документ нотатника верхнього рівня не можна видалити або перемістити"
}
}
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index b3cfaf1946..e53844e502 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -2194,6 +2194,7 @@
"337": "所选路径不是文件夹",
"338": "不支持所选 Vault 路径,请选择思源工作空间以外的普通文件夹",
"339": "仅支持使用默认 .obsidian 文件夹的 Obsidian Vault",
- "340": "所选 Vault 中没有可读取的非隐藏 Markdown 文件"
+ "340": "所选 Vault 中没有可读取的非隐藏 Markdown 文件",
+ "341": "顶层笔记本文档不能被删除或移动"
}
}
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 53578824d2..de7f3147d8 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -2194,6 +2194,7 @@
"337": "所選路徑不是資料夾",
"338": "不支援所選 Vault 路徑,請選擇思源工作空間以外的一般資料夾",
"339": "僅支援使用預設 .obsidian 資料夾的 Obsidian Vault",
- "340": "所選 Vault 中沒有可讀取的非隱藏 Markdown 檔案"
+ "340": "所選 Vault 中沒有可讀取的非隱藏 Markdown 檔案",
+ "341": "頂層筆記本文檔不能被刪除或移動"
}
}
diff --git a/app/src/layout/dock/Files.ts b/app/src/layout/dock/Files.ts
index 2c0dffa8e2..ae8d60c290 100644
--- a/app/src/layout/dock/Files.ts
+++ b/app/src/layout/dock/Files.ts
@@ -175,7 +175,7 @@ export class Files extends Model {
}
let target = event.target as HTMLElement;
while (target && !target.isEqualNode(this.element)) {
- if (target.tagName === "LI" && !target.getAttribute("data-opening")) {
+ if (target.tagName === "LI" && target.getAttribute("data-node-id") && !target.getAttribute("data-opening")) {
target.setAttribute("data-opening", "true");
openFileById({
app: options.app,
@@ -204,14 +204,16 @@ export class Files extends Model {
event.preventDefault();
event.stopPropagation();
const liElement = target.parentElement;
- if (liElement.getAttribute("data-type") === "navigation-file" && window.siyuan.config.fileTree.docIconClickExpand) {
- if (Number(liElement.getAttribute("data-count")) > 0) {
+ const isFile = liElement.getAttribute("data-type") === "navigation-file";
+ const isBoxDoc = liElement.getAttribute("data-type") === "navigation-root" && liElement.getAttribute("data-node-id");
+ if ((isFile || isBoxDoc) && window.siyuan.config.fileTree.docIconClickExpand) {
+ if (isBoxDoc || Number(liElement.getAttribute("data-count")) > 0) {
this.getLeaf(liElement, notebookId);
}
break;
}
const rect = target.getBoundingClientRect();
- if (liElement.getAttribute("data-type") === "navigation-file") {
+ if (isFile) {
openEmojiPanel(liElement.getAttribute("data-node-id"), "doc", {
x: rect.left,
y: rect.bottom,
@@ -237,8 +239,8 @@ export class Files extends Model {
event.preventDefault();
event.stopPropagation();
const rect = target.getBoundingClientRect();
- openPublishAccessDialog(target.parentElement.getAttribute("data-node-id") ||
- target.parentElement.parentElement.getAttribute("data-url"), {
+ openPublishAccessDialog(target.parentElement.getAttribute("data-type") === "navigation-root" ?
+ notebookId : target.parentElement.getAttribute("data-node-id"), {
x: rect.left,
y: rect.bottom,
h: rect.height,
@@ -277,9 +279,11 @@ export class Files extends Model {
break;
} else if (event.button === 0 && isNotCtrl(event) && !event.altKey && !event.shiftKey &&
target.classList.contains("b3-list-item__text") &&
- target.parentElement.getAttribute("data-type") === "navigation-file" &&
+ (target.parentElement.getAttribute("data-type") === "navigation-file" ||
+ (target.parentElement.getAttribute("data-type") === "navigation-root" && target.parentElement.getAttribute("data-node-id"))) &&
window.siyuan.config.fileTree.parentDocClickExpand &&
- Number(target.parentElement.getAttribute("data-count")) > 0) {
+ (target.parentElement.getAttribute("data-type") === "navigation-root" ||
+ Number(target.parentElement.getAttribute("data-count")) > 0)) {
this.getLeaf(target.parentElement, notebookId);
event.preventDefault();
event.stopPropagation();
@@ -322,7 +326,8 @@ export class Files extends Model {
} else {
this.lastSelectedElement = target;
this.setCurrent(target, false);
- if (target.getAttribute("data-type") === "navigation-file") {
+ if (target.getAttribute("data-type") === "navigation-file" ||
+ (target.getAttribute("data-type") === "navigation-root" && target.getAttribute("data-node-id"))) {
// 更新最后点击的文档项
needFocus = false;
if (target.getAttribute("data-opening")) {
@@ -897,9 +902,14 @@ export class Files extends Model {
case "li2doc":
this.selectItem(data.data.box.id, data.data.path);
break;
- case "renamenotebook":
+ case "renamenotebook": {
+ const notebook = window.siyuan.notebooks.find((item) => item.id === data.data.box);
+ if (notebook) {
+ notebook.name = data.data.name;
+ }
this.element.querySelector(`[data-url="${data.data.box}"] .b3-list-item__text`).innerHTML = escapeHtml(data.data.name);
break;
+ }
case "rename":
this.onRename(data.data);
break;
@@ -908,7 +918,7 @@ export class Files extends Model {
}
private updateDocInfo(data: IWebSocketData) {
- const liElement = this.element.querySelector(`li[data-node-id="${data.data.rootID}"]`);
+ const liElement = this.element.querySelector(`li[data-type="navigation-file"][data-node-id="${data.data.rootID}"]`);
if (liElement) {
liElement.setAttribute("data-count", data.data.subFileCount);
liElement.querySelector(".ariaLabel")?.setAttribute("aria-label", this.genDocAriaLabel(data.data, escapeLessThans));
@@ -1006,7 +1016,7 @@ export class Files extends Model {
return `<ul class="b3-list b3-list--background" data-url="${item.id}" data-sort="${item.sort}" data-sortmode="${item.sortMode}">
<li class="b3-list-item b3-list-item--hide-action" ${window.siyuan.config.fileTree.sort === 6 ? 'draggable="true"' : ""}
style="--file-toggle-width:22px"
-data-type="navigation-root" data-path="/">
+data-type="navigation-root" data-path="/" data-node-id="${item.boxDocID || ""}">
<span class="b3-list-item__toggle b3-list-item__toggle--hl">
<svg class="b3-list-item__arrow"><use xlink:href="#iconRight"></use></svg>
</span>
@@ -1371,6 +1381,14 @@ data-type="navigation-root" data-path="/">
// 有文件树和编辑器的布局初始化时,文件树还未挂载
return;
}
+ const boxDocID = window.siyuan.notebooks.find((item) => item.id === notebookId)?.boxDocID;
+ if (boxDocID && filePath === `/${boxDocID}.sy`) {
+ const boxDocElement = treeElement.querySelector("[data-type=\"navigation-root\"]") as HTMLElement;
+ if (isSetCurrent) {
+ this.setCurrent(boxDocElement);
+ }
+ return boxDocElement;
+ }
let currentPath = filePath;
let liElement: HTMLElement;
const visitedPaths = new Set<string>();
@@ -1563,7 +1581,7 @@ aria-label="${ariaLabel}">${getDocDisplayName(item.name, item.titleEmpty, true)}
}
const ids: string[] = [];
this.element.querySelectorAll("[data-url]").forEach((element: HTMLElement) => ids.push(element.getAttribute("data-url")));
- this.element.querySelectorAll("[data-node-id]").forEach((element: HTMLElement) => ids.push(element.getAttribute("data-node-id")));
+ this.element.querySelectorAll("[data-type=\"navigation-file\"][data-node-id]").forEach((element: HTMLElement) => ids.push(element.getAttribute("data-node-id")));
fetchPost("/api/filetree/getPublishAccess", {
ids
}, response => {
diff --git a/app/src/mobile/dock/MobileFiles.ts b/app/src/mobile/dock/MobileFiles.ts
index bcd0c9fb81..52fa17b19e 100644
--- a/app/src/mobile/dock/MobileFiles.ts
+++ b/app/src/mobile/dock/MobileFiles.ts
@@ -110,8 +110,9 @@ export class MobileFiles extends Model {
break;
} else if (target.classList.contains("b3-list-item__switch")) {
const rect = target.getBoundingClientRect();
- openPublishAccessDialog(target.parentElement.getAttribute("data-node-id") ||
- target.parentElement.parentElement.getAttribute("data-url"), {
+ const rootUL = hasTopClosestByTag(target, "UL");
+ openPublishAccessDialog(target.parentElement.getAttribute("data-type") === "navigation-root" ?
+ rootUL?.getAttribute("data-url") : target.parentElement.getAttribute("data-node-id"), {
x: rect.left,
y: rect.bottom,
h: rect.height,
@@ -210,8 +211,11 @@ export class MobileFiles extends Model {
if (target.getAttribute("data-type") === "navigation-file") {
openMobileFileById(app, target.getAttribute("data-node-id"), [Constants.CB_GET_SCROLL]);
} else if (target.getAttribute("data-type") === "navigation-root") {
+ const boxDocID = target.getAttribute("data-node-id");
const ulElement = hasTopClosestByTag(target, "UL");
- if (ulElement) {
+ if (boxDocID) {
+ openMobileFileById(app, boxDocID, [Constants.CB_GET_SCROLL]);
+ } else if (ulElement) {
const notebookId = ulElement.getAttribute("data-url");
this.getLeaf(target, notebookId);
}
@@ -535,9 +539,14 @@ export class MobileFiles extends Model {
case "reloadDocInfo":
this.updateDocInfo(data);
break;
- case "renamenotebook":
+ case "renamenotebook": {
+ const notebook = window.siyuan.notebooks.find((item) => item.id === data.data.box);
+ if (notebook) {
+ notebook.name = data.data.name;
+ }
this.element.querySelector(`[data-url="${data.data.box}"] .b3-list-item__text`).innerHTML = escapeHtml(data.data.name);
break;
+ }
case "rename":
this.onRename(data.data);
break;
@@ -605,7 +614,7 @@ export class MobileFiles extends Model {
}
private updateDocInfo(data: IWebSocketData) {
- const liElement = this.element.querySelector(`li[data-node-id="${data.data.rootID}"]`);
+ const liElement = this.element.querySelector(`li[data-type="navigation-file"][data-node-id="${data.data.rootID}"]`);
if (liElement) {
liElement.setAttribute("data-count", data.data.subFileCount);
if (data.data.subFileCount === 0) {
@@ -638,7 +647,7 @@ export class MobileFiles extends Model {
</li>`;
} else {
return `<ul class="b3-list b3-list--background" data-url="${item.id}" data-sortmode="${item.sortMode}">
-<li class="b3-list-item" data-type="navigation-root" data-path="/" style="--file-toggle-width:24px">
+<li class="b3-list-item" data-type="navigation-root" data-path="/" data-node-id="${item.boxDocID || ""}" style="--file-toggle-width:24px">
<span class="b3-list-item__toggle${item.closed ? " fn__hidden" : ""}">
<svg class="b3-list-item__arrow"><use xlink:href="#iconRight"></use></svg>
</span>
@@ -1003,6 +1012,14 @@ export class MobileFiles extends Model {
// 有文件树和编辑器的布局初始化时,文件树还未挂载
return;
}
+ const boxDocID = window.siyuan.notebooks.find((item) => item.id === notebookId)?.boxDocID;
+ if (boxDocID && filePath === `/${boxDocID}.sy`) {
+ const boxDocElement = treeElement.querySelector("[data-type=\"navigation-root\"]") as HTMLElement;
+ if (isSetCurrent) {
+ this.setCurrent(boxDocElement);
+ }
+ return boxDocElement;
+ }
let currentPath = filePath;
let liElement: HTMLElement;
while (!liElement) {
@@ -1108,7 +1125,7 @@ class="b3-list-item" data-path="${item.path}" style="--file-toggle-width:${paddi
}
const ids: string[] = [];
this.element.querySelectorAll("[data-url]").forEach((element: HTMLElement) => ids.push(element.getAttribute("data-url")));
- this.element.querySelectorAll("[data-node-id]").forEach((element: HTMLElement) => ids.push(element.getAttribute("data-node-id")));
+ this.element.querySelectorAll("[data-type=\"navigation-file\"][data-node-id]").forEach((element: HTMLElement) => ids.push(element.getAttribute("data-node-id")));
fetchPost("/api/filetree/getPublishAccess", {
ids
}, response => {
diff --git a/app/src/protyle/header/openTitleMenu.ts b/app/src/protyle/header/openTitleMenu.ts
index 58234d6ede..0450b1e7e7 100644
--- a/app/src/protyle/header/openTitleMenu.ts
+++ b/app/src/protyle/header/openTitleMenu.ts
@@ -44,6 +44,7 @@ export const openTitleMenu = (protyle: IProtyle, position: IPosition, from: stri
fetchPost("/api/block/getDocInfo", docInfoParam, (response) => {
window.siyuan.menus.menu.remove();
window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_TITLE);
+ const isBoxDoc = window.siyuan.notebooks.find((item) => item.id === protyle.notebookId)?.boxDocID === protyle.block.rootID;
const popoverElement = hasTopClosestByClassName(protyle.element, "block__popover", true);
window.siyuan.menus.menu.element.setAttribute("data-from", popoverElement ? popoverElement.dataset.level + "popover-" + from : "app-" + from);
const submenu = copySubMenu([protyle.block.rootID], true, undefined, protyle.block.showAll ? protyle.block.id : protyle.block.rootID);
@@ -86,7 +87,9 @@ export const openTitleMenu = (protyle: IProtyle, position: IPosition, from: stri
submenu,
}).element);
if (!protyle.disabled) {
- window.siyuan.menus.menu.append(movePathToMenu([protyle.path]));
+ if (!isBoxDoc) {
+ window.siyuan.menus.menu.append(movePathToMenu([protyle.path]));
+ }
const range = getSelection().rangeCount > 0 ? getSelection().getRangeAt(0) : undefined;
window.siyuan.menus.menu.append(new MenuItem({
id: "addToDatabase",
@@ -97,14 +100,16 @@ export const openTitleMenu = (protyle: IProtyle, position: IPosition, from: stri
addEditorToDatabase(protyle, range, "title");
}
}).element);
- window.siyuan.menus.menu.append(new MenuItem({
- id: "delete",
- icon: "iconTrashcan",
- label: window.siyuan.languages.delete,
- click: () => {
- deleteFile(protyle.notebookId, protyle.path);
- }
- }).element);
+ if (!isBoxDoc) {
+ window.siyuan.menus.menu.append(new MenuItem({
+ id: "delete",
+ icon: "iconTrashcan",
+ label: window.siyuan.languages.delete,
+ click: () => {
+ deleteFile(protyle.notebookId, protyle.path);
+ }
+ }).element);
+ }
}
/// #if !MOBILE
window.siyuan.menus.menu.append(new MenuItem({id: "separator_1", type: "separator"}).element);
@@ -237,16 +242,16 @@ export const openTitleMenu = (protyle: IProtyle, position: IPosition, from: stri
icon: "iconSearch",
accelerator: window.siyuan.config.keymap.general.search.custom,
async click() {
- const searchPath = getDisplayName(protyle.path, false, true);
+ const searchPath = isBoxDoc ? "" : getDisplayName(protyle.path, false, true);
/// #if MOBILE
- const pathResponse = await fetchSyncPost("/api/filetree/getHPathByPath", {
- notebook: protyle.notebookId,
- path: searchPath + ".sy"
- });
+ const pathResponse = isBoxDoc ? undefined : await fetchSyncPost("/api/filetree/getHPathByPath", {
+ notebook: protyle.notebookId,
+ path: searchPath + ".sy"
+ });
popSearch(protyle.app, {
hasReplace: false,
- hPath: pathPosix().join(getNotebookName(protyle.notebookId), pathResponse.data),
- idPath: [pathPosix().join(protyle.notebookId, searchPath)],
+ hPath: isBoxDoc ? getNotebookName(protyle.notebookId) : pathPosix().join(getNotebookName(protyle.notebookId), pathResponse.data),
+ idPath: [isBoxDoc ? protyle.notebookId : pathPosix().join(protyle.notebookId, searchPath)],
page: 1,
});
/// #else
diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.ts
index 8b08ce1d67..be2f9d0b54 100644
--- a/app/src/types/index.d.ts
+++ b/app/src/types/index.d.ts
@@ -510,6 +510,7 @@ interface IEmoji {
interface INotebook {
name: string;
id: string;
+ boxDocID: string;
closed: boolean;
icon: string;
sort: number;
diff --git a/kernel/api/filetree.go b/kernel/api/filetree.go
index e00e44d5ee..e642bb427c 100644
--- a/kernel/api/filetree.go
+++ b/kernel/api/filetree.go
@@ -613,7 +613,10 @@ func removeDoc(c *gin.Context) {
}
p := arg["path"].(string)
- model.RemoveDoc(notebook, p)
+ if err := model.RemoveDoc(notebook, p); err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ }
}
func removeDocByID(c *gin.Context) {
@@ -638,7 +641,10 @@ func removeDocByID(c *gin.Context) {
return
}
- model.RemoveDoc(tree.Box, tree.Path)
+ if err = model.RemoveDoc(tree.Box, tree.Path); err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ }
}
func removeDocs(c *gin.Context) {
@@ -655,7 +661,10 @@ func removeDocs(c *gin.Context) {
for _, path := range pathsArg {
paths = append(paths, path.(string))
}
- model.RemoveDocs(paths)
+ if err := model.RemoveDocs(paths); err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ }
}
func renameDoc(c *gin.Context) {
diff --git a/kernel/cli/cmd/document.go b/kernel/cli/cmd/document.go
index e7c006db6a..57e0befc5a 100644
--- a/kernel/cli/cmd/document.go
+++ b/kernel/cli/cmd/document.go
@@ -160,7 +160,9 @@ var documentRemoveCmd = &cobra.Command{
if err != nil {
return err
}
- model.RemoveDoc(tree.Box, tree.Path)
+ if err = model.RemoveDoc(tree.Box, tree.Path); err != nil {
+ return err
+ }
model.AppendPushRemoveEntry(tree.Box, tree.Path, id)
parentPath := path.Dir(tree.Path) + ".sy"
if parentPath != "/.sy" {
diff --git a/kernel/mcp/tools/document.go b/kernel/mcp/tools/document.go
index c872e8c745..d21288dc8c 100644
--- a/kernel/mcp/tools/document.go
+++ b/kernel/mcp/tools/document.go
@@ -189,7 +189,9 @@ func documentDelete(args map[string]any) (CallToolResult, error) {
return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("load doc failed: %s", err)}}, IsError: true}, nil
}
- model.RemoveDoc(tree.Box, tree.Path)
+ if err = model.RemoveDoc(tree.Box, tree.Path); err != nil {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("delete doc failed: %s", err)}}, IsError: true}, nil
+ }
return CallToolResult{Content: []ContentItem{{Type: "text", Text: "document deleted: " + id}}}, nil
}
diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.go
index b1f742bac3..b25630e2e7 100644
--- a/kernel/model/attribute_view.go
+++ b/kernel/model/attribute_view.go
@@ -4138,7 +4138,7 @@ func removeAttributeViewBlock(srcIDs []string, avID string, tx *Transaction) (er
func removeNodeAvID(node *ast.Node, avID string, tx *Transaction, tree *parse.Tree) (err error) {
attrs := parse.IAL2Map(node.KramdownIAL)
- if ast.NodeDocument == node.Type {
+ if ast.NodeDocument == node.Type && !IsBoxDoc(tree.Box, tree.ID) {
delete(attrs, DocHiddenAttr)
node.RemoveIALAttr(DocHiddenAttr)
}
diff --git a/kernel/model/blockial.go b/kernel/model/blockial.go
index 2c528652e5..1c55bdb740 100644
--- a/kernel/model/blockial.go
+++ b/kernel/model/blockial.go
@@ -148,6 +148,7 @@ func BatchSetBlockAttrs(blockAttrs []map[string]any) (err error) {
trees := filesys.LoadTrees(blockIDs)
var nodes []*ast.Node
+ boxIcons := map[string]string{}
for _, blockAttr := range blockAttrs {
id := blockAttr["id"].(string)
tree := trees[id]
@@ -161,6 +162,14 @@ func BatchSetBlockAttrs(blockAttrs []map[string]any) (err error) {
}
attrs := blockAttr["attrs"].(map[string]string)
+ if IsBoxDoc(tree.Box, tree.ID) {
+ attrs[BoxDocAttr] = tree.Box
+ attrs[DocHiddenAttr] = "true"
+ if icon, ok := attrs["icon"]; ok {
+ boxIcons[tree.Box] = filterBoxIcon(icon)
+ attrs["icon"] = boxIcons[tree.Box]
+ }
+ }
oldAttrs, e := setNodeAttrs0(node, attrs, tree.Box)
if nil != e {
return e
@@ -176,6 +185,17 @@ func BatchSetBlockAttrs(blockAttrs []map[string]any) (err error) {
return
}
}
+ for boxID, icon := range boxIcons {
+ box := &Box{ID: boxID}
+ boxConf := box.GetConf()
+ boxConf.Icon = icon
+ if err = box.SaveConf(boxConf); err != nil {
+ return
+ }
+ }
+ if 0 < len(boxIcons) {
+ ReloadFiletree()
+ }
IncSync()
// 不做锚文本刷新
@@ -186,6 +206,9 @@ func SetBlockAttrs(id string, nameValues map[string]string) (err error) {
if util.ReadOnly {
return
}
+ if nil == nameValues {
+ nameValues = map[string]string{}
+ }
FlushTxQueue()
@@ -199,7 +222,25 @@ func SetBlockAttrs(id string, nameValues map[string]string) (err error) {
return fmt.Errorf(Conf.Language(15), id)
}
+ if IsBoxDoc(tree.Box, tree.ID) {
+ nameValues[BoxDocAttr] = tree.Box
+ nameValues[DocHiddenAttr] = "true"
+ if icon, ok := nameValues["icon"]; ok {
+ nameValues["icon"] = filterBoxIcon(icon)
+ }
+ }
err = setNodeAttrs(node, tree, nameValues)
+ if nil == err && IsBoxDoc(tree.Box, tree.ID) {
+ if icon, ok := nameValues["icon"]; ok {
+ box := &Box{ID: tree.Box}
+ boxConf := box.GetConf()
+ boxConf.Icon = icon
+ err = box.SaveConf(boxConf)
+ if nil == err {
+ ReloadFiletree()
+ }
+ }
+ }
return
}
diff --git a/kernel/model/blockinfo.go b/kernel/model/blockinfo.go
index bdc5d484d0..ac441eece2 100644
--- a/kernel/model/blockinfo.go
+++ b/kernel/model/blockinfo.go
@@ -135,12 +135,16 @@ func GetDocInfoInBox(blockID, boxID string) (ret *BlockInfo, err error) {
}
var subFileCount int
- boxLocalPath := filepath.Join(util.DataDir, tree.Box)
- subFiles, err := os.ReadDir(filepath.Join(boxLocalPath, strings.TrimSuffix(tree.Path, ".sy")))
- if err == nil {
- for _, subFile := range subFiles {
- if strings.HasSuffix(subFile.Name(), ".sy") {
- subFileCount++
+ if IsBoxDoc(tree.Box, tree.ID) {
+ subFileCount = boxDocSubFileCount(tree.Box)
+ } else {
+ boxLocalPath := filepath.Join(util.DataDir, tree.Box)
+ subFiles, readErr := os.ReadDir(filepath.Join(boxLocalPath, strings.TrimSuffix(tree.Path, ".sy")))
+ if readErr == nil {
+ for _, subFile := range subFiles {
+ if strings.HasSuffix(subFile.Name(), ".sy") {
+ subFileCount++
+ }
}
}
}
@@ -239,12 +243,16 @@ func GetDocsInfo(blockIDs []string, queryRefCount bool, queryAv bool) (rets []*B
}
var subFileCount int
- boxLocalPath := filepath.Join(util.DataDir, tree.Box)
- subFiles, err := os.ReadDir(filepath.Join(boxLocalPath, strings.TrimSuffix(tree.Path, ".sy")))
- if err == nil {
- for _, subFile := range subFiles {
- if strings.HasSuffix(subFile.Name(), ".sy") {
- subFileCount++
+ if IsBoxDoc(tree.Box, tree.ID) {
+ subFileCount = boxDocSubFileCount(tree.Box)
+ } else {
+ boxLocalPath := filepath.Join(util.DataDir, tree.Box)
+ subFiles, readErr := os.ReadDir(filepath.Join(boxLocalPath, strings.TrimSuffix(tree.Path, ".sy")))
+ if readErr == nil {
+ for _, subFile := range subFiles {
+ if strings.HasSuffix(subFile.Name(), ".sy") {
+ subFileCount++
+ }
}
}
}
@@ -576,7 +584,11 @@ func buildBlockBreadcrumb(node *ast.Node, excludeTypes []string, isEmbedBlock bo
name := parent.IALAttr("name")
if ast.NodeDocument == parent.Type {
- name = box.Name + hPath
+ if IsBoxDoc(node.Box, parent.ID) {
+ name = box.Name
+ } else {
+ name = box.Name + hPath
+ }
} else if ast.NodeAttributeView == parent.Type {
name, _ = av.GetAttributeViewName(parent.AttributeViewID)
} else {
diff --git a/kernel/model/box.go b/kernel/model/box.go
index 9297465009..2cba39ff0f 100644
--- a/kernel/model/box.go
+++ b/kernel/model/box.go
@@ -50,6 +50,7 @@ import (
// Box 笔记本。
type Box struct {
ID string `json:"id"`
+ BoxDocID string `json:"boxDocID"`
Name string `json:"name"`
Icon string `json:"icon"`
Sort int `json:"sort"`
@@ -163,8 +164,18 @@ func ListNotebooks() (ret []*Box, err error) {
icon = util.FilterUploadEmojiFileName(icon)
}
+ var boxDocID string
+ if !boxConf.Encrypted && !IsUserGuide(id) {
+ var readBoxDocErr error
+ boxDocID, readBoxDocErr = readBoxDocID(id)
+ if nil != readBoxDocErr {
+ logging.LogErrorf("read box document metadata [%s] failed: %s", id, readBoxDocErr)
+ }
+ }
+
box := &Box{
ID: id,
+ BoxDocID: boxDocID,
Name: boxConf.Name,
Icon: icon,
Sort: boxConf.Sort,
@@ -504,7 +515,9 @@ func (box *Box) GetInfo() (ret *BoxInfo) {
continue
}
- ret.DocCount++
+ if id != box.BoxDocID {
+ ret.DocCount++
+ }
ret.Size += uint64(info.Size())
docModT := info.ModTime()
if docModT.After(docLatestModTime) {
@@ -925,15 +938,28 @@ func ChangeBoxSort(boxIDs []string) {
}
func SetBoxIcon(boxID, icon string) {
- if strings.Contains(icon, ".") {
- // XSS through emoji name https://github.com/siyuan-note/siyuan/issues/15034
- icon = util.FilterUploadEmojiFileName(icon)
- }
+ icon = filterBoxIcon(icon)
box := &Box{ID: boxID}
boxConf := box.GetConf()
boxConf.Icon = icon
- box.SaveConf(boxConf)
+ if err := box.SaveConf(boxConf); err != nil {
+ logging.LogErrorf("save box icon [%s] failed: %s", boxID, err)
+ return
+ }
+ if err := setBoxDocIcon(boxID, icon); err != nil {
+ logging.LogErrorf("set box document icon [%s] failed: %s", boxID, err)
+ return
+ }
+ IncSync()
+}
+
+func filterBoxIcon(icon string) string {
+ if strings.Contains(icon, ".") {
+ // XSS through emoji name https://github.com/siyuan-note/siyuan/issues/15034
+ icon = util.FilterUploadEmojiFileName(icon)
+ }
+ return icon
}
func (box *Box) UpdateHistoryGenerated() {
diff --git a/kernel/model/box_doc.go b/kernel/model/box_doc.go
new file mode 100644
index 0000000000..916d0cc429
--- /dev/null
+++ b/kernel/model/box_doc.go
@@ -0,0 +1,365 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import (
+ "crypto/sha256"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/88250/gulu"
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/html"
+ "github.com/88250/lute/parse"
+ "github.com/siyuan-note/filelock"
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/cache"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+const (
+ boxDocMetaSpec = 1
+ boxDocMetaName = "boxDoc.json"
+ BoxDocAttr = "custom-sy-box-doc"
+)
+
+type boxDocMeta struct {
+ Spec int `json:"spec"`
+ BoxDocID string `json:"boxDocID"`
+}
+
+func boxDocMetaPath(boxID string) string {
+ return filepath.Join(util.DataDir, boxID, ".siyuan", boxDocMetaName)
+}
+
+func boxDocPath(boxDocID string) string {
+ if "" == boxDocID {
+ return ""
+ }
+ return "/" + boxDocID + ".sy"
+}
+
+func readBoxDocID(boxID string) (ret string, err error) {
+ data, err := filelock.ReadFile(boxDocMetaPath(boxID))
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ err = nil
+ }
+ return
+ }
+
+ meta := &boxDocMeta{}
+ if err = gulu.JSON.UnmarshalJSON(data, meta); err != nil {
+ return "", fmt.Errorf("unmarshal box document metadata failed: %w", err)
+ }
+ if boxDocMetaSpec != meta.Spec {
+ return "", fmt.Errorf("unsupported box document metadata spec [%d]", meta.Spec)
+ }
+ if !ast.IsNodeIDPattern(meta.BoxDocID) {
+ return "", fmt.Errorf("invalid box document ID [%s]", meta.BoxDocID)
+ }
+ return meta.BoxDocID, nil
+}
+
+func writeBoxDocID(boxID, boxDocID string) error {
+ meta := &boxDocMeta{Spec: boxDocMetaSpec, BoxDocID: boxDocID}
+ data, err := gulu.JSON.MarshalIndentJSON(meta, "", " ")
+ if err != nil {
+ return fmt.Errorf("marshal box document metadata failed: %w", err)
+ }
+ return filelock.WriteFile(boxDocMetaPath(boxID), data)
+}
+
+// deterministicBoxDocID 保证多台离线设备迁移同一笔记本时生成相同的文档 ID。
+func deterministicBoxDocID(boxID string) string {
+ if !ast.IsNodeIDPattern(boxID) {
+ return ""
+ }
+
+ const alphabet = "0123456789abcdefghijklmnopqrstuvwxyz"
+ digest := sha256.Sum256([]byte("siyuan-box-doc:" + boxID))
+ suffix := make([]byte, 7)
+ for i := range suffix {
+ suffix[i] = alphabet[int(digest[i])%len(alphabet)]
+ }
+ return boxID[:14] + "-" + string(suffix)
+}
+
+func supportsBoxDoc(boxID string) bool {
+ return !IsUserGuide(boxID) && !IsEncryptedBox(boxID)
+}
+
+func EnsureBoxDoc(boxID string) (boxDocID string, err error) {
+ createDocLock.Lock()
+ defer createDocLock.Unlock()
+ return ensureBoxDoc0(boxID)
+}
+
+// ensureBoxDoc0 的调用方必须持有 createDocLock。
+func ensureBoxDoc0(boxID string) (boxDocID string, err error) {
+ if !supportsBoxDoc(boxID) {
+ return
+ }
+
+ box := Conf.Box(boxID)
+ if nil == box {
+ return "", ErrBoxNotFound
+ }
+
+ boxDocID, err = readBoxDocID(boxID)
+ if err != nil {
+ logging.LogErrorf("read box document metadata [%s] failed: %s", boxID, err)
+ return "", err
+ }
+ if "" != boxDocID {
+ if !box.Exist(boxDocPath(boxDocID)) {
+ return "", fmt.Errorf("box document [%s] is missing", boxDocID)
+ }
+ indexBoxDocIfNeeded(boxID, boxDocID)
+ if err = reconcileBoxDoc(box, boxDocID); err != nil {
+ return "", err
+ }
+ return
+ }
+
+ boxDocID, err = findBoxDocByMarker(box)
+ if err != nil {
+ return "", err
+ }
+ if "" == boxDocID {
+ boxDocID = deterministicBoxDocID(boxID)
+ if "" == boxDocID {
+ return "", fmt.Errorf("invalid box ID [%s]", boxID)
+ }
+ if box.Exist(boxDocPath(boxDocID)) || nil != treenode.GetBlockTree(boxDocID) || "" != findUnindexedTreePathInAllBoxes(boxDocID) {
+ return "", fmt.Errorf("box document ID [%s] is already in use", boxDocID)
+ }
+ if err = createBoxDoc(box, boxDocID); err != nil {
+ return "", err
+ }
+ }
+
+ if err = writeBoxDocID(boxID, boxDocID); err != nil {
+ return "", err
+ }
+ IncSync()
+ logging.LogInfof("initialized box document [box=%s, id=%s]", boxID, boxDocID)
+ return
+}
+
+func findBoxDocByMarker(box *Box) (ret string, err error) {
+ files, _, err := box.Ls("/")
+ if err != nil {
+ return "", err
+ }
+
+ luteEngine := util.NewLute()
+ for _, file := range files {
+ if file.isdir || !strings.HasSuffix(file.path, ".sy") {
+ continue
+ }
+ id := util.GetTreeID(file.path)
+ if !ast.IsNodeIDPattern(id) {
+ continue
+ }
+ tree, loadErr := filesys.LoadTree(box.ID, file.path, luteEngine)
+ if loadErr != nil || box.ID != tree.Root.IALAttr(BoxDocAttr) {
+ continue
+ }
+ if "" != ret && ret != id {
+ return "", fmt.Errorf("multiple box documents found in notebook [%s]", box.ID)
+ }
+ ret = id
+ }
+ return
+}
+
+func createBoxDoc(box *Box, boxDocID string) error {
+ boxConf := box.GetConf()
+ title := normalizeDocTitle(boxConf.Name)
+ if "" == title {
+ title = Conf.Language(16)
+ }
+ p := boxDocPath(boxDocID)
+ tree := treenode.NewTree(box.ID, p, "/"+title, html.EscapeAttrVal(title))
+ tree.Root.SetIALAttr(BoxDocAttr, box.ID)
+ tree.Root.SetIALAttr(DocHiddenAttr, "true")
+ if "" != boxConf.Icon {
+ tree.Root.SetIALAttr("icon", boxConf.Icon)
+ }
+ if err := indexWriteTreeIndexQueue(tree); err != nil {
+ return err
+ }
+ cache.PutDocIALInBox(tree.Path, tree.Box, parse.IAL2Map(tree.Root.KramdownIAL))
+ return nil
+}
+
+func indexBoxDocIfNeeded(boxID, boxDocID string) {
+ if nil != treenode.GetBlockTreeInBox(boxDocID, boxID) {
+ return
+ }
+ tree, err := filesys.LoadTree(boxID, boxDocPath(boxDocID), util.NewLute())
+ if err != nil {
+ logging.LogErrorf("load box document [box=%s, id=%s] failed: %s", boxID, boxDocID, err)
+ return
+ }
+ treenode.IndexBlockTree(tree)
+ sql.IndexTreeQueue(tree)
+ cache.PutDocIALInBox(tree.Path, tree.Box, parse.IAL2Map(tree.Root.KramdownIAL))
+}
+
+func reconcileBoxDoc(box *Box, boxDocID string) error {
+ tree, err := filesys.LoadTree(box.ID, boxDocPath(boxDocID), util.NewLute())
+ if err != nil {
+ return err
+ }
+ boxConf := box.GetConf()
+ title := normalizeDocTitle(boxConf.Name)
+ if "" == title {
+ title = Conf.Language(16)
+ }
+ titleChanged := tree.Root.IALAttr("title") != title
+ changed := titleChanged || tree.HPath != "/"+title || tree.Root.IALAttr(BoxDocAttr) != box.ID ||
+ tree.Root.IALAttr(DocHiddenAttr) != "true" || tree.Root.IALAttr("icon") != boxConf.Icon
+ if !changed {
+ return nil
+ }
+ tree.HPath = "/" + title
+ tree.Root.SetIALAttr("title", title)
+ tree.Root.SetIALAttr(BoxDocAttr, box.ID)
+ tree.Root.SetIALAttr(DocHiddenAttr, "true")
+ if "" == boxConf.Icon {
+ tree.Root.RemoveIALAttr("icon")
+ } else {
+ tree.Root.SetIALAttr("icon", boxConf.Icon)
+ }
+ tree.Root.SetIALAttr("updated", util.CurrentTimeSecondsStr())
+ if err = indexWriteTreeUpsertQueue(tree); err != nil {
+ return err
+ }
+ if titleChanged {
+ updateRefTextRenameDoc(tree)
+ }
+ IncSync()
+ return nil
+}
+
+func boxDocSubFileCount(boxID string) int {
+ box := Conf.Box(boxID)
+ if nil == box || "" == box.BoxDocID {
+ return 0
+ }
+ entries, err := os.ReadDir(filepath.Join(util.DataDir, boxID))
+ if err != nil {
+ return 0
+ }
+ ret := 0
+ for _, entry := range entries {
+ if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sy") {
+ continue
+ }
+ id := strings.TrimSuffix(entry.Name(), ".sy")
+ if id == box.BoxDocID || !ast.IsNodeIDPattern(id) {
+ continue
+ }
+ ial := filesys.DocIAL(filepath.Join(util.DataDir, boxID, entry.Name()))
+ if "true" == ial[DocHiddenAttr] {
+ continue
+ }
+ ret++
+ }
+ return ret
+}
+
+func IsBoxDoc(boxID, id string) bool {
+ box := Conf.Box(boxID)
+ return nil != box && "" != box.BoxDocID && box.BoxDocID == id
+}
+
+func IsBoxDocPath(boxID, p string) bool {
+ return IsBoxDoc(boxID, util.GetTreeID(p))
+}
+
+// normalizeBoxDocPath 将虚拟根文档下的路径映射到笔记本物理根路径。
+func normalizeBoxDocPath(boxID, p string) string {
+ box := Conf.Box(boxID)
+ if nil == box || "" == box.BoxDocID {
+ return p
+ }
+ prefix := "/" + box.BoxDocID + "/"
+ if strings.HasPrefix(p, prefix) {
+ return "/" + strings.TrimPrefix(p, prefix)
+ }
+ return p
+}
+
+func normalizeBoxDocTarget(boxID, p string) string {
+ box := Conf.Box(boxID)
+ if nil == box || "" == box.BoxDocID {
+ return p
+ }
+ if boxDocPath(box.BoxDocID) == p {
+ return "/"
+ }
+ return normalizeBoxDocPath(boxID, p)
+}
+
+func renameBoxDoc(boxID, name string) error {
+ box := Conf.Box(boxID)
+ if nil == box || "" == box.BoxDocID || !box.Exist(boxDocPath(box.BoxDocID)) {
+ return nil
+ }
+ return renameDoc0(boxID, boxDocPath(box.BoxDocID), name)
+}
+
+func setBoxDocIcon(boxID, icon string) error {
+ box := Conf.Box(boxID)
+ if nil == box || "" == box.BoxDocID {
+ return nil
+ }
+ tree, err := filesys.LoadTree(boxID, boxDocPath(box.BoxDocID), util.NewLute())
+ if err != nil {
+ return err
+ }
+ oldAttrs := parse.IAL2Map(tree.Root.KramdownIAL)
+ if "" == icon {
+ tree.Root.RemoveIALAttr("icon")
+ } else {
+ tree.Root.SetIALAttr("icon", icon)
+ }
+ tree.Root.SetIALAttr("updated", util.CurrentTimeSecondsStr())
+ if err = indexWriteTreeUpsertQueue(tree); err != nil {
+ return err
+ }
+ cache.PutDocIALInBox(tree.Path, tree.Box, parse.IAL2Map(tree.Root.KramdownIAL))
+ pushBlockAttrs(oldAttrs, tree.Root)
+ return nil
+}
+
+func removeBoxDocAttrs(tree *parse.Tree) {
+ if nil == tree || nil == tree.Root {
+ return
+ }
+ tree.Root.RemoveIALAttr(BoxDocAttr)
+ tree.Root.RemoveIALAttr(DocHiddenAttr)
+}
diff --git a/kernel/model/box_doc_test.go b/kernel/model/box_doc_test.go
new file mode 100644
index 0000000000..3846813137
--- /dev/null
+++ b/kernel/model/box_doc_test.go
@@ -0,0 +1,37 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import (
+ "testing"
+
+ "github.com/88250/lute/ast"
+)
+
+func TestDeterministicBoxDocID(t *testing.T) {
+ boxID := "20260716120000-abcdefg"
+ boxDocID := deterministicBoxDocID(boxID)
+ if !ast.IsNodeIDPattern(boxDocID) {
+ t.Fatalf("invalid box document ID [%s]", boxDocID)
+ }
+ if boxDocID != deterministicBoxDocID(boxID) {
+ t.Fatalf("box document ID is not deterministic [%s]", boxDocID)
+ }
+ if boxDocID == deterministicBoxDocID("20260716120000-hijklmn") {
+ t.Fatalf("different boxes generated the same document ID [%s]", boxDocID)
+ }
+}
diff --git a/kernel/model/conf.go b/kernel/model/conf.go
index 297e51af9d..27242a22db 100644
--- a/kernel/model/conf.go
+++ b/kernel/model/conf.go
@@ -1121,7 +1121,7 @@ func (conf *AppConf) GetBoxes() (ret []*Box) {
name := notebook.Name
closed := notebook.Closed
encrypted := IsEncryptedBox(id) // 使用 IsEncryptedBox 统一判定(含 backup fallback)
- box := &Box{ID: id, Name: name, Closed: closed, Encrypted: encrypted}
+ box := &Box{ID: id, BoxDocID: notebook.BoxDocID, Name: name, Closed: closed, Encrypted: encrypted}
ret = append(ret, box)
}
return
@@ -1176,6 +1176,9 @@ func InitBoxes() {
blockCount := treenode.CountBlocks()
initialized := 0 < blockCount
for _, box := range Conf.GetOpenedBoxes() {
+ if _, err := EnsureBoxDoc(box.ID); nil != err {
+ logging.LogErrorf("ensure box document [%s] failed: %s", box.ID, err)
+ }
box.UpdateHistoryGenerated() // 初始化历史生成时间为当前时间
if !initialized {
diff --git a/kernel/model/export.go b/kernel/model/export.go
index 91af3ffa30..0158bae61f 100644
--- a/kernel/model/export.go
+++ b/kernel/model/export.go
@@ -583,8 +583,15 @@ func ExportSYs(ids []string) (zipPath string) {
docPaths = append(docPaths, bt.Path)
if Conf.Export.IncludeSubDocs {
- docFiles := box.ListFiles(strings.TrimSuffix(bt.Path, ".sy"))
+ listPath := strings.TrimSuffix(bt.Path, ".sy")
+ if IsBoxDoc(bt.BoxID, bt.RootID) {
+ listPath = "/"
+ }
+ docFiles := box.ListFiles(listPath)
for _, docFile := range docFiles {
+ if docFile.path == bt.Path {
+ continue
+ }
docPaths = append(docPaths, docFile.path)
}
}
@@ -2143,8 +2150,15 @@ func ExportPandocConvertZip(ids []string, pandocTo, ext string) (name, zipPath s
docPaths = append(docPaths, bt.Path)
if Conf.Export.IncludeSubDocs {
- docFiles := box.ListFiles(strings.TrimSuffix(bt.Path, ".sy"))
+ listPath := strings.TrimSuffix(bt.Path, ".sy")
+ if IsBoxDoc(bt.BoxID, bt.RootID) {
+ listPath = "/"
+ }
+ docFiles := box.ListFiles(listPath)
for _, docFile := range docFiles {
+ if docFile.path == bt.Path {
+ continue
+ }
docPaths = append(docPaths, docFile.path)
}
}
diff --git a/kernel/model/export_merge.go b/kernel/model/export_merge.go
index 3b690be663..ebaf86c15b 100644
--- a/kernel/model/export_merge.go
+++ b/kernel/model/export_merge.go
@@ -116,7 +116,11 @@ func loadTreeNodes(box string, p string, level int) (ret []*ast.Node, err error)
}
func buildBlockChildren(block *Block) (err error) {
- files, _, err := ListDocTree(block.Box, block.Path, util.SortModeUnassigned, false, false, Conf.FileTree.MaxListCount)
+ listPath := block.Path
+ if IsBoxDoc(block.Box, block.ID) {
+ listPath = "/"
+ }
+ files, _, err := ListDocTree(block.Box, listPath, util.SortModeUnassigned, false, false, Conf.FileTree.MaxListCount)
if err != nil {
return
}
diff --git a/kernel/model/file.go b/kernel/model/file.go
index 83e4bdb841..06ffe9b3af 100644
--- a/kernel/model/file.go
+++ b/kernel/model/file.go
@@ -302,6 +302,9 @@ func ListDocTree(boxID, listPath string, sortMode int, flashcard, showHidden boo
boxLocalPath := filepath.Join(util.DataDir, box.ID)
var docs []*File
for _, file := range files {
+ if "/" == listPath && "" != box.BoxDocID && box.BoxDocID == util.GetTreeID(file.path) {
+ continue
+ }
if file.isdir {
if !ast.IsNodeIDPattern(file.name) {
continue
@@ -1039,8 +1042,12 @@ func DuplicateDoc(tree *parse.Tree) {
msgId := util.PushMsg(Conf.Language(116), 30000)
defer util.PushClearMsg(msgId)
+ isBoxDoc := IsBoxDoc(tree.Box, tree.ID)
previousPath := tree.Path
resetTree(tree, "Duplicated", false)
+ if isBoxDoc {
+ removeBoxDocAttrs(tree)
+ }
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering || !n.IsBlock() {
@@ -1285,6 +1292,10 @@ func GetHPathByPath(boxID, p string) (hPath string, err error) {
hPath = "/"
return
}
+ if IsBoxDocPath(boxID, p) {
+ hPath = "/"
+ return
+ }
bt := treenode.GetBlockTreeByBoxPath(boxID, p)
if nil == bt {
@@ -1309,7 +1320,11 @@ func GetHPathsByPaths(paths []string) (hPaths []string, err error) {
continue
}
- hPaths = append(hPaths, box.Name+bt.HPath)
+ if box.BoxDocID == bt.RootID {
+ hPaths = append(hPaths, box.Name)
+ } else {
+ hPaths = append(hPaths, box.Name+bt.HPath)
+ }
}
return
}
@@ -1319,6 +1334,10 @@ func GetHPathByID(id string) (hPath string, err error) {
if err != nil {
return
}
+ if IsBoxDoc(tree.Box, tree.ID) {
+ hPath = "/"
+ return
+ }
hPath = tree.HPath
return
}
@@ -1345,12 +1364,21 @@ func GetFullHPathByID(id string) (hPath string, err error) {
err = ErrBoxNotFound
return
}
+ if box.BoxDocID == tree.ID {
+ hPath = box.Name
+ return
+ }
hPath = box.Name + tree.HPath
return
}
func GetIDsByHPath(hpath, boxID string) (ret []string, err error) {
ret = []string{}
+ if "/" == hpath {
+ if box := Conf.Box(boxID); nil != box && "" != box.BoxDocID {
+ return []string{box.BoxDocID}, nil
+ }
+ }
roots := treenode.GetBlockTreeRootsByHPath(boxID, hpath)
if 1 > len(roots) {
return
@@ -1372,6 +1400,7 @@ func MoveDocs(fromPaths []string, toBoxID, toPath string, callback any) (err err
err = errors.New(Conf.Language(0))
return
}
+ toPath = normalizeBoxDocTarget(toBoxID, toPath)
fromPaths = util.FilterMoveDocFromPaths(fromPaths, toPath)
if 1 > len(fromPaths) {
@@ -1379,6 +1408,11 @@ func MoveDocs(fromPaths []string, toBoxID, toPath string, callback any) (err err
}
pathsBoxes := getBoxesByPaths(fromPaths)
+ for fromPath, fromBox := range pathsBoxes {
+ if nil != fromBox && IsBoxDocPath(fromBox.ID, fromPath) {
+ return errors.New(Conf.Language(341))
+ }
+ }
if 1 == len(fromPaths) {
// 移动到自己的父文档下的情况相当于不移动,直接返回
@@ -1600,10 +1634,13 @@ func moveDoc(fromBox *Box, fromPath string, toBox *Box, toPath string, luteEngin
return
}
-func RemoveDoc(boxID, p string) {
+func RemoveDoc(boxID, p string) error {
box := Conf.Box(boxID)
if nil == box {
- return
+ return ErrBoxNotFound
+ }
+ if IsBoxDocPath(boxID, p) {
+ return errors.New(Conf.Language(341))
}
FlushTxQueue()
@@ -1612,14 +1649,20 @@ func RemoveDoc(boxID, p string) {
IncSync()
refreshParentDocInfo(tree)
+ return nil
}
-func RemoveDocs(paths []string) {
+func RemoveDocs(paths []string) error {
util.PushEndlessProgress(Conf.Language(116))
defer util.PushClearProgress()
paths = util.FilterSelfChildDocs(paths)
pathsBoxes := getBoxesByPaths(paths)
+ for p, box := range pathsBoxes {
+ if nil != box && IsBoxDocPath(box.ID, p) {
+ return errors.New(Conf.Language(341))
+ }
+ }
FlushTxQueue()
luteEngine := util.NewLute()
@@ -1639,6 +1682,7 @@ func RemoveDocs(paths []string) {
for _, parentTree := range parentTrees {
refreshDocInfo(parentTree)
}
+ return nil
}
func removeDoc(box *Box, p string, luteEngine *lute.Lute) (ret *parse.Tree) {
@@ -1738,6 +1782,22 @@ func removeDoc0(tree *parse.Tree, childrenDir string) {
}
func RenameDoc(boxID, p, title string) (err error) {
+ if IsBoxDocPath(boxID, p) {
+ if err = RenameBox(boxID, title); err != nil {
+ return
+ }
+ box := Conf.Box(boxID)
+ if nil != box {
+ evt := util.NewCmdResult("renamenotebook", 0, util.PushModeBroadcast)
+ evt.Data = map[string]any{"box": boxID, "name": box.Name}
+ util.PushEvent(evt)
+ }
+ return
+ }
+ return renameDoc0(boxID, p, title)
+}
+
+func renameDoc0(boxID, p, title string) (err error) {
box := Conf.Box(boxID)
if nil == box {
err = errors.New(Conf.Language(0))
@@ -1827,6 +1887,7 @@ func RenameDoc(boxID, p, title string) (err error) {
}
func createDoc(boxID, p, title, dom string, titleEmpty bool) (tree *parse.Tree, err error) {
+ p = normalizeBoxDocPath(boxID, p)
title = normalizeDocTitle(title)
if 512 < utf8.RuneCountInString(title) {
// 限制笔记本名和文档名最大长度为 `512` https://github.com/siyuan-note/siyuan/issues/6299
diff --git a/kernel/model/flashcard.go b/kernel/model/flashcard.go
index 2ce04d2504..431d7cc9c5 100644
--- a/kernel/model/flashcard.go
+++ b/kernel/model/flashcard.go
@@ -660,6 +660,9 @@ func getTreeSubTreeChildBlocks(rootID string) (treeBlockIDsMap map[string]bool,
if nil == root {
return
}
+ if IsBoxDoc(root.BoxID, rootID) {
+ return getBoxBlocks(root.BoxID)
+ }
bts := treenode.GetBlockTreesByPathPrefix(root.BoxID, strings.TrimSuffix(root.Path, ".sy"))
for _, bt := range bts {
diff --git a/kernel/model/heading.go b/kernel/model/heading.go
index 605d4740d1..057345197c 100644
--- a/kernel/model/heading.go
+++ b/kernel/model/heading.go
@@ -153,6 +153,10 @@ func Doc2Heading(srcID, targetID string, after bool) (srcTreeBox, srcTreePath st
err = ErrBlockNotFound
return
}
+ if IsBoxDoc(srcTree.Box, srcTree.ID) {
+ err = errors.New(Conf.Language(341))
+ return
+ }
subDir := filepath.Join(util.DataDir, srcTree.Box, strings.TrimSuffix(srcTree.Path, ".sy"))
if gulu.File.IsDir(subDir) {
@@ -307,6 +311,7 @@ func Doc2Heading(srcID, targetID string, after bool) (srcTreeBox, srcTreePath st
}
func Heading2Doc(srcHeadingID, targetBoxID, targetPath, previousPath string, toTop bool) (srcRootBlockID, newTargetPath string, err error) {
+ targetPath = normalizeBoxDocTarget(targetBoxID, targetPath)
FlushTxQueue()
srcTree, _ := LoadTreeByBlockID(srcHeadingID)
diff --git a/kernel/model/import.go b/kernel/model/import.go
index 1c2a1c0144..b0c47b965e 100644
--- a/kernel/model/import.go
+++ b/kernel/model/import.go
@@ -113,6 +113,7 @@ func HTML2Tree(htmlStr string, luteEngine *lute.Lute, boxID string) (tree *parse
}
func ImportSY(zipPath, boxID, toPath string) (err error) {
+ toPath = normalizeBoxDocTarget(boxID, toPath)
util.PushEndlessProgress(Conf.Language(73))
defer util.ClearPushProgress(100)
@@ -199,6 +200,9 @@ func ImportSY(zipPath, boxID, toPath string) (err error) {
})
tree.ID = tree.Root.ID
tree.Path = filepath.ToSlash(strings.TrimPrefix(syPath, unzipRootPath))
+ if "" != tree.Root.IALAttr(BoxDocAttr) {
+ removeBoxDocAttrs(tree)
+ }
trees[tree.ID] = tree
util.PushEndlessProgress(Conf.language(73) + " " + fmt.Sprintf(Conf.language(70), fmt.Sprintf("%d/%d", i+1, len(syPaths))))
}
@@ -928,6 +932,7 @@ func ImportData(zipPath string) (err error) {
}
func ImportFromLocalPath(boxID, localPath string, toPath string) (err error) {
+ toPath = normalizeBoxDocTarget(boxID, toPath)
util.PushEndlessProgress(Conf.Language(73))
defer func() {
util.PushClearProgress()
diff --git a/kernel/model/listitem.go b/kernel/model/listitem.go
index 7221efac06..fac5458dd9 100644
--- a/kernel/model/listitem.go
+++ b/kernel/model/listitem.go
@@ -28,6 +28,7 @@ import (
)
func ListItem2Doc(srcListItemID, targetBoxID, targetPath, previousPath string, toTop bool) (srcRootBlockID, newTargetPath string, err error) {
+ targetPath = normalizeBoxDocTarget(targetBoxID, targetPath)
FlushTxQueue()
srcTree, _ := LoadTreeByBlockID(srcListItemID)
diff --git a/kernel/model/mount.go b/kernel/model/mount.go
index acca747307..f25b1c4ae5 100644
--- a/kernel/model/mount.go
+++ b/kernel/model/mount.go
@@ -85,6 +85,14 @@ func CreateBox(name string) (id string, err error) {
if err := box.SaveConf(boxConf); err != nil {
logging.LogErrorf("save box conf [%s] failed: %s", id, err)
}
+ if _, err = ensureBoxDoc0(id); err != nil {
+ treenode.RemoveBlockTreesByBoxID(id)
+ sql.DeleteBoxQueue(id)
+ if removeErr := filelock.Remove(boxLocalPath); nil != removeErr {
+ logging.LogErrorf("remove box [%s] after initializing box document failed: %s", id, removeErr)
+ }
+ return "", err
+ }
IncSync()
logging.LogInfof("created box [%s]", id)
return
@@ -109,8 +117,13 @@ func RenameBox(boxID, name string) (err error) {
boxConf := box.GetConf()
boxConf.Name = name
box.Name = name
- if err := box.SaveConf(boxConf); err != nil {
+ if err = box.SaveConf(boxConf); err != nil {
logging.LogErrorf("save box conf [%s] failed: %s", boxID, err)
+ return
+ }
+ if err = renameBoxDoc(boxID, name); err != nil {
+ logging.LogErrorf("rename box document [box=%s] failed: %s", boxID, err)
+ return
}
IncSync()
logging.LogInfof("renamed box [%s] to [%s]", boxID, name)
@@ -361,10 +374,14 @@ func Mount(boxID string) (alreadyMount bool, err error) {
if err := box.SaveConf(boxConf); err != nil {
logging.LogErrorf("save box conf [%s] failed: %s", boxID, err)
}
+ if _, ensureErr := EnsureBoxDoc(boxID); nil != ensureErr {
+ logging.LogErrorf("ensure box document [%s] failed: %s", boxID, ensureErr)
+ }
// 缓存根一级的文档树展开
files, _, _ := ListDocTree(box.ID, "/", util.SortModeUnassigned, false, false, Conf.FileTree.MaxListCount)
- if 0 < len(files) {
+ box = Conf.Box(boxID)
+ if 0 < len(files) || (nil != box && "" != box.BoxDocID) {
box.Index()
}
diff --git a/kernel/model/path.go b/kernel/model/path.go
index 3d75ebbeda..d06603c7ee 100644
--- a/kernel/model/path.go
+++ b/kernel/model/path.go
@@ -42,6 +42,14 @@ func createDocsByHPath(boxID, hPath, content, parentID, id string, titleEmpty bo
hPath = strings.TrimSuffix(hPath, ".sy")
hPath = util.TrimSpaceInPath(hPath)
if "" != parentID {
+ if box := Conf.Box(boxID); nil != box && "" != box.BoxDocID && box.BoxDocID == parentID {
+ name := path.Base(hPath)
+ p := "/" + id + ".sy"
+ if _, err = createDoc(boxID, p, name, content, titleEmpty); err != nil {
+ logging.LogErrorf("create doc [%s] failed: %s", p, err)
+ }
+ return
+ }
// The save path is incorrect when creating a sub-doc by ref in a doc with the same name https://github.com/siyuan-note/siyuan/issues/8138
// 在指定了父文档 ID 的情况下优先查找父文档
parentHPath, name := path.Split(hPath)
diff --git a/kernel/model/push_reload.go b/kernel/model/push_reload.go
index 78c1618cfd..3b010b7c55 100644
--- a/kernel/model/push_reload.go
+++ b/kernel/model/push_reload.go
@@ -135,7 +135,9 @@ func refreshDocInfo0(tree *parse.Tree, size uint64) {
}
subFileCount := 0
- if "true" != tree.Root.IALAttr(DocHiddenAttr) {
+ if IsBoxDoc(tree.Box, tree.ID) {
+ subFileCount = boxDocSubFileCount(tree.Box)
+ } else if "true" != tree.Root.IALAttr(DocHiddenAttr) {
subDir := filepath.Join(util.DataDir, tree.Box, strings.TrimSuffix(tree.Path, ".sy"))
subFiles, err := os.ReadDir(subDir)
if err == nil {
diff --git a/kernel/model/repository.go b/kernel/model/repository.go
index a403bf6f1f..2d8b49008c 100644
--- a/kernel/model/repository.go
+++ b/kernel/model/repository.go
@@ -2114,6 +2114,12 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,
needUnindexBoxes[boxID] = true
needIndexBoxes[boxID] = true
}
+ if strings.HasSuffix(file.Path, "/.siyuan/boxDoc.json") {
+ needReloadFiletree = true
+ boxID := strings.TrimSuffix(strings.TrimPrefix(file.Path, "/"), "/.siyuan/boxDoc.json")
+ needUnindexBoxes[boxID] = true
+ needIndexBoxes[boxID] = true
+ }
if file.Path == "/.siyuan/notebook-crypto-backup.json" {
needRestoreNotebookCrypto = true
@@ -2175,6 +2181,12 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,
boxID := strings.TrimSuffix(strings.TrimPrefix(file.Path, "/"), "/.siyuan/conf.json")
needUnindexBoxes[boxID] = true
}
+ if strings.HasSuffix(file.Path, "/.siyuan/boxDoc.json") {
+ needReloadFiletree = true
+ boxID := strings.TrimSuffix(strings.TrimPrefix(file.Path, "/"), "/.siyuan/boxDoc.json")
+ needUnindexBoxes[boxID] = true
+ needIndexBoxes[boxID] = true
+ }
if strings.HasPrefix(file.Path, "/storage/petal/") {
needReloadPlugin = true
@@ -2263,6 +2275,9 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,
}
for boxID := range needIndexBoxes {
if box := Conf.GetBox(boxID); nil != box {
+ if _, err := EnsureBoxDoc(boxID); nil != err {
+ logging.LogErrorf("ensure box document [%s] after sync failed: %s", boxID, err)
+ }
box.Index()
}
}
diff --git a/kernel/model/transaction.go b/kernel/model/transaction.go
index ae2a44d334..b8873afccf 100644
--- a/kernel/model/transaction.go
+++ b/kernel/model/transaction.go
@@ -1914,6 +1914,15 @@ func (tx *Transaction) doSetAttrs(operation *Operation) (ret *TxErr) {
logging.LogErrorf("unmarshal attrs failed: %s", err)
return &TxErr{code: TxErrCodeBlockNotFound, id: id}
}
+ if IsBoxDoc(tree.Box, tree.ID) {
+ attrs[BoxDocAttr] = tree.Box
+ attrs[DocHiddenAttr] = "true"
+ if icon, ok := attrs["icon"]; ok {
+ icon = filterBoxIcon(icon)
+ attrs["icon"] = icon
+ tx.boxIcons[tree.Box] = icon
+ }
+ }
if _, setErr := setNodeAttrs0(node, attrs, tree.Box); nil != setErr {
logging.LogErrorf("set attrs failed: %s", setErr)
@@ -1969,6 +1978,7 @@ type Transaction struct {
nodes map[string]*ast.Node // 事务中变更的节点
relatedAvIDs []string // 事务中变更的属性视图 ID
changedRootIDs []string // 变更的树 ID 列表(包含了变更定义块后影响的动态锚文本所在的树)
+ boxIcons map[string]string // 事务提交后需要同步的笔记本图标
isGlobalAssetsInit bool // 是否初始化过全局资源判断
isGlobalAssets bool // 是否属于全局资源
@@ -2027,6 +2037,7 @@ func (tx *Transaction) WaitForCommit() {
func (tx *Transaction) begin() (err error) {
tx.trees = map[string]*parse.Tree{}
tx.nodes = map[string]*ast.Node{}
+ tx.boxIcons = map[string]string{}
tx.luteEngine = util.NewLute()
tx.m.Lock()
tx.state.Store(1)
@@ -2045,6 +2056,17 @@ func (tx *Transaction) commit() (err error) {
checkUpsertInUserGuide(tree)
}
+ for boxID, icon := range tx.boxIcons {
+ box := &Box{ID: boxID}
+ boxConf := box.GetConf()
+ boxConf.Icon = icon
+ if err = box.SaveConf(boxConf); err != nil {
+ return
+ }
+ }
+ if 0 < len(tx.boxIcons) {
+ ReloadFiletree()
+ }
tx.changedRootIDs = refreshDynamicRefTexts(tx.nodes, tx.trees)
tx.relatedAvIDs = gulu.Str.RemoveDuplicatedElem(tx.relatedAvIDs)
@@ -2068,7 +2090,7 @@ func (tx *Transaction) commit() (err error) {
}
func (tx *Transaction) rollback() {
- tx.trees, tx.nodes = nil, nil
+ tx.trees, tx.nodes, tx.boxIcons = nil, nil, nil
tx.state.Store(3)
tx.m.Unlock()
return