Skip to content

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

:sparkles: Support global backlink anchor sorting with paginated loading https://github.com/siyuan-note/siyuan/issues/19579

Danielcd75c3cd14d4
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index c7b472234e..f1b9e645b6 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,5 @@
{
+ "backlinkGlobalSort": "ترتيب المراجع على مستوى الكل",
"backlinkDocumentSort": "ترتيب المستندات",
"backlinkBlockSort": "ترتيب المراجع داخل المستندات",
"backlinkBodyOrder": "ترتيب الظهور في المستند (الافتراضي)",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 0a97e98d46..933e0b4ecb 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,5 @@
{
+ "backlinkGlobalSort": "Globale Referenzsortierung",
"backlinkDocumentSort": "Dokumentsortierung",
"backlinkBlockSort": "Referenzen innerhalb von Dokumenten",
"backlinkBodyOrder": "Reihenfolge im Dokument (Standard)",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index d45c362d46..f8df61c587 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,5 @@
{
+ "backlinkGlobalSort": "Global reference sorting",
"backlinkDocumentSort": "Document sorting",
"backlinkBlockSort": "References within documents",
"backlinkBodyOrder": "Document order (default)",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 95f3e4eb6b..06510466b6 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,5 @@
{
+ "backlinkGlobalSort": "Orden global de referencias",
"backlinkDocumentSort": "Orden de documentos",
"backlinkBlockSort": "Referencias dentro de los documentos",
"backlinkBodyOrder": "Orden en el documento (predeterminado)",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index cba8c739f5..bb2bc3f135 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,5 @@
{
+ "backlinkGlobalSort": "Tri global des références",
"backlinkDocumentSort": "Tri des documents",
"backlinkBlockSort": "Références dans les documents",
"backlinkBodyOrder": "Ordre dans le document (par défaut)",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index a95619081d..2e79453589 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,5 @@
{
+ "backlinkGlobalSort": "מיון הפניות גלובלי",
"backlinkDocumentSort": "מיון מסמכים",
"backlinkBlockSort": "מיון הפניות בתוך מסמכים",
"backlinkBodyOrder": "סדר ההופעה במסמך (ברירת מחדל)",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index b89f90a52a..6d2f2763c9 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,5 @@
{
+ "backlinkGlobalSort": "सभी संदर्भों का क्रम",
"backlinkDocumentSort": "दस्तावेज़ों का क्रम",
"backlinkBlockSort": "दस्तावेज़ों के भीतर संदर्भों का क्रम",
"backlinkBodyOrder": "दस्तावेज़ में क्रम (डिफ़ॉल्ट)",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index ce2472eb3d..bcb4d852d0 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,5 @@
{
+ "backlinkGlobalSort": "Urutan referensi global",
"backlinkDocumentSort": "Urutan dokumen",
"backlinkBlockSort": "Urutan referensi dalam dokumen",
"backlinkBodyOrder": "Urutan dalam dokumen (bawaan)",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index eac975b182..c122354199 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,5 @@
{
+ "backlinkGlobalSort": "Ordinamento globale dei riferimenti",
"backlinkDocumentSort": "Ordinamento dei documenti",
"backlinkBlockSort": "Riferimenti all’interno dei documenti",
"backlinkBodyOrder": "Ordine nel documento (predefinito)",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 033cc8928a..83a5ef6507 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,5 @@
{
+ "backlinkGlobalSort": "参照全体の並び順",
"backlinkDocumentSort": "ドキュメントの並び順",
"backlinkBlockSort": "ドキュメント内の参照の並び順",
"backlinkBodyOrder": "本文の順序(既定)",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 2dbb8d5289..d2a32e8402 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,5 @@
{
+ "backlinkGlobalSort": "전체 참조 정렬",
"backlinkDocumentSort": "문서 정렬",
"backlinkBlockSort": "문서 내 참조 정렬",
"backlinkBodyOrder": "본문 순서 (기본값)",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 1e23d343b9..ddd8a4bfb1 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,5 @@
{
+ "backlinkGlobalSort": "Alle verwijzingen sorteren",
"backlinkDocumentSort": "Documenten sorteren",
"backlinkBlockSort": "Verwijzingen binnen documenten",
"backlinkBodyOrder": "Volgorde in het document (standaard)",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index cd3e318bb3..987a01bf1d 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,5 @@
{
+ "backlinkGlobalSort": "Globalne sortowanie odwołań",
"backlinkDocumentSort": "Sortowanie dokumentów",
"backlinkBlockSort": "Odwołania wewnątrz dokumentów",
"backlinkBodyOrder": "Kolejność w dokumencie (domyślna)",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 2fe6705318..6053127599 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,5 @@
{
+ "backlinkGlobalSort": "Ordenação global de referências",
"backlinkDocumentSort": "Ordenação de documentos",
"backlinkBlockSort": "Referências dentro dos documentos",
"backlinkBodyOrder": "Ordem no documento (padrão)",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index bc4d53a820..7d393529bb 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,5 @@
{
+ "backlinkGlobalSort": "Глобальная сортировка ссылок",
"backlinkDocumentSort": "Сортировка документов",
"backlinkBlockSort": "Ссылки внутри документов",
"backlinkBodyOrder": "Порядок в документе (по умолчанию)",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 573f470ce5..5b44e47421 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,5 @@
{
+ "backlinkGlobalSort": "Globálne zoradenie odkazov",
"backlinkDocumentSort": "Zoradenie dokumentov",
"backlinkBlockSort": "Odkazy v dokumentoch",
"backlinkBodyOrder": "Poradie v dokumente (predvolené)",
diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.json
index b446ef5ad7..337151cc6b 100644
--- a/app/appearance/langs/sr.json
+++ b/app/appearance/langs/sr.json
@@ -1,4 +1,5 @@
{
+ "backlinkGlobalSort": "Глобално сортирање референци",
"backlinkDocumentSort": "Сортирање докумената",
"backlinkBlockSort": "Референце унутар докумената",
"backlinkBodyOrder": "Редослед у документу (подразумевано)",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index bc1d827912..f7c6fc04a6 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,5 @@
{
+ "backlinkGlobalSort": "การเรียงการอ้างอิงทั้งหมด",
"backlinkDocumentSort": "การเรียงเอกสาร",
"backlinkBlockSort": "การเรียงการอ้างอิงภายในเอกสาร",
"backlinkBodyOrder": "ลำดับในเนื้อหา (ค่าเริ่มต้น)",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index f21592004b..5879b8aead 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,5 @@
{
+ "backlinkGlobalSort": "Genel başvuru sıralaması",
"backlinkDocumentSort": "Belge sıralaması",
"backlinkBlockSort": "Belge içindeki başvurular",
"backlinkBodyOrder": "Belgedeki sıra (varsayılan)",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index d481620b34..f13197b3af 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,5 @@
{
+ "backlinkGlobalSort": "Глобальне сортування посилань",
"backlinkDocumentSort": "Сортування документів",
"backlinkBlockSort": "Посилання всередині документів",
"backlinkBodyOrder": "Порядок у документі (типово)",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 7871412728..bec1df8aab 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,5 @@
{
+ "backlinkGlobalSort": "全局引用排序",
"backlinkDocumentSort": "文档排序",
"backlinkBlockSort": "文档内引用排序",
"backlinkBodyOrder": "正文顺序(默认)",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 93389da49d..acd88d782c 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,5 @@
{
+ "backlinkGlobalSort": "全域引用排序",
"backlinkDocumentSort": "文件排序",
"backlinkBlockSort": "文件內引用排序",
"backlinkBodyOrder": "內文順序(預設)",
diff --git a/app/src/assets/scss/protyle/_protyle.scss b/app/src/assets/scss/protyle/_protyle.scss
index 6a50ca77e6..4a2d1e60d3 100644
--- a/app/src/assets/scss/protyle/_protyle.scss
+++ b/app/src/assets/scss/protyle/_protyle.scss
@@ -530,6 +530,38 @@
}
.sy__backlink {
+ .backlinkList__source {
+ appearance: none;
+ display: block;
+ box-sizing: border-box;
+ width: 100%;
+ min-width: 0;
+ margin: 0;
+ padding: 4px 28px;
+ border: 0;
+ border-radius: var(--b3-border-radius);
+ background-color: transparent;
+ color: var(--b3-theme-on-surface-light);
+ font: inherit;
+ font-size: 12px;
+ line-height: 20px;
+ text-align: start;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ cursor: pointer;
+
+ &:hover {
+ background-color: var(--b3-list-hover);
+ color: var(--b3-theme-on-background);
+ }
+
+ &:focus-visible {
+ outline: 1px solid var(--b3-theme-primary);
+ outline-offset: -1px;
+ }
+ }
+
// 仅为上下文首块已有的属性栏留出空间,普通块保持紧凑。
.protyle-wysiwyg > .protyle-breadcrumb__bar + [data-node-id]:is(
[name]:not([name=""]),
diff --git a/app/src/layout/dock/BacklinkContent.ts b/app/src/layout/dock/BacklinkContent.ts
index 701bb12b02..65a9728e4c 100644
--- a/app/src/layout/dock/BacklinkContent.ts
+++ b/app/src/layout/dock/BacklinkContent.ts
@@ -1,4 +1,5 @@
import {normalizeAssetOpenConfig} from "../../editor/assetOpen";
+import {GlobalBacklinkList} from "./GlobalBacklinkList";
import {bindPanelSearch} from "./panelSearch";
import type {Tab} from "../Tab";
import {Model} from "../Model";
@@ -180,6 +181,7 @@ export class BacklinkContent extends Model {
private ownerScrollListener?: () => void;
private onlyBacklinks: boolean;
private surface: string;
+ private globalList?: GlobalBacklinkList;
constructor(options: {
app: App,
@@ -416,6 +418,10 @@ export class BacklinkContent extends Model {
}
// 为了快捷键的 dispatch
this.element.querySelector('[data-type="collapse"]').addEventListener("click", () => {
+ if (this.globalList) {
+ this.globalList.setCollapsed(true);
+ return;
+ }
const finishScroll = this.beginBottomScroll();
this.cancelContextRequests(this.tree.element, false);
this.hideEditorGutters(this.tree.element);
@@ -433,6 +439,10 @@ export class BacklinkContent extends Model {
finishScroll?.();
});
this.element.querySelector('[data-type="expand"]').addEventListener("click", () => {
+ if (this.globalList) {
+ this.globalList.setCollapsed(false);
+ return;
+ }
this.expandDocumentItems(this.tree, false);
});
this.element.addEventListener("click", (event) => {
@@ -768,12 +778,14 @@ export class BacklinkContent extends Model {
}
private showSortMenu(type: string, sort: string) {
+ const globalSort = window.siyuan.config.editor.backlinkGlobalSort || 0;
const clickEvent = (currentSort: string) => {
(type === "sort" ? this.tree : this.mTree).element.previousElementSibling.querySelector(`[data-type="${type}"]`).setAttribute("data-sort", currentSort);
// 保存排序状态到配置
const sortValue = parseInt(currentSort);
if (type === "sort") {
window.siyuan.config.editor.backlinkSort = sortValue;
+ window.siyuan.config.editor.backlinkGlobalSort = 0;
} else {
window.siyuan.config.editor.backmentionSort = sortValue;
}
@@ -791,7 +803,7 @@ export class BacklinkContent extends Model {
}).element);
}
window.siyuan.menus.menu.append(new MenuItem({
- checked: sort === "0",
+ checked: (type !== "sort" || !globalSort) && sort === "0",
iconHTML: "",
label: window.siyuan.languages.fileNameASC,
click: () => {
@@ -799,7 +811,7 @@ export class BacklinkContent extends Model {
}
}).element);
window.siyuan.menus.menu.append(new MenuItem({
- checked: sort === "1",
+ checked: (type !== "sort" || !globalSort) && sort === "1",
iconHTML: "",
label: window.siyuan.languages.fileNameDESC,
click: () => {
@@ -807,7 +819,7 @@ export class BacklinkContent extends Model {
}
}).element);
window.siyuan.menus.menu.append(new MenuItem({
- checked: sort === "4",
+ checked: (type !== "sort" || !globalSort) && sort === "4",
iconHTML: "",
label: window.siyuan.languages.fileNameNatASC,
click: () => {
@@ -815,7 +827,7 @@ export class BacklinkContent extends Model {
}
}).element);
window.siyuan.menus.menu.append(new MenuItem({
- checked: sort === "5",
+ checked: (type !== "sort" || !globalSort) && sort === "5",
iconHTML: "",
label: window.siyuan.languages.fileNameNatDESC,
click: () => {
@@ -824,7 +836,7 @@ export class BacklinkContent extends Model {
}).element);
window.siyuan.menus.menu.append(new MenuItem({type: "separator"}).element);
window.siyuan.menus.menu.append(new MenuItem({
- checked: sort === "9",
+ checked: (type !== "sort" || !globalSort) && sort === "9",
iconHTML: "",
label: window.siyuan.languages.createdASC,
click: () => {
@@ -832,7 +844,7 @@ export class BacklinkContent extends Model {
}
}).element);
window.siyuan.menus.menu.append(new MenuItem({
- checked: sort === "10",
+ checked: (type !== "sort" || !globalSort) && sort === "10",
iconHTML: "",
label: window.siyuan.languages.createdDESC,
click: () => {
@@ -840,7 +852,7 @@ export class BacklinkContent extends Model {
}
}).element);
window.siyuan.menus.menu.append(new MenuItem({
- checked: sort === "2",
+ checked: (type !== "sort" || !globalSort) && sort === "2",
iconHTML: "",
label: window.siyuan.languages.modifiedASC,
click: () => {
@@ -848,7 +860,7 @@ export class BacklinkContent extends Model {
}
}).element);
window.siyuan.menus.menu.append(new MenuItem({
- checked: sort === "3",
+ checked: (type !== "sort" || !globalSort) && sort === "3",
iconHTML: "",
label: window.siyuan.languages.modifiedDESC,
click: () => {
@@ -867,17 +879,36 @@ export class BacklinkContent extends Model {
window.siyuan.menus.menu.append(new MenuItem({
label,
iconHTML: "",
- checked: mode === (window.siyuan.config.editor.backlinkBlockSort || 0),
+ checked: !globalSort && mode === (window.siyuan.config.editor.backlinkBlockSort || 0),
click: () => {
window.siyuan.config.editor.backlinkBlockSort = mode;
+ window.siyuan.config.editor.backlinkGlobalSort = 0;
fetchPost("/api/setting/setEditor", window.siyuan.config.editor, (response) => {
window.siyuan.config.editor = {...response.data, assetOpen: normalizeAssetOpenConfig(response.data.assetOpen)};
});
this.cancelContextRequests(this.tree.element, false);
+ if (this.globalList) {
+ this.searchBacklinks(true);
+ return;
+ }
this.refreshExpandedContexts(new Set<string>(), true, true);
},
}).element);
});
+ window.siyuan.menus.menu.append(new MenuItem({type: "separator"}).element);
+ window.siyuan.menus.menu.append(new MenuItem({
+ type: "readonly", iconHTML: "", label: window.siyuan.languages.backlinkGlobalSort,
+ }).element);
+ [window.siyuan.languages.backlinkAnchorASC, window.siyuan.languages.backlinkAnchorDESC].forEach((label, index) => {
+ window.siyuan.menus.menu.append(new MenuItem({
+ label, iconHTML: "", checked: globalSort === index + 1,
+ click: () => {
+ window.siyuan.config.editor.backlinkGlobalSort = index + 1;
+ fetchPost("/api/setting/setEditor", window.siyuan.config.editor);
+ this.searchBacklinks();
+ },
+ }).element);
+ });
}
}
@@ -887,6 +918,63 @@ export class BacklinkContent extends Model {
this.searchBacklinks();
}
+ private syncGlobalList(refresh: boolean) {
+ const mode = window.siyuan.config.editor.backlinkGlobalSort || 0;
+ if (mode !== 1 && mode !== 2) {
+ if (this.globalList) {
+ this.globalList.destroy();
+ this.globalList = undefined;
+ this.listQueryKey = "";
+ this.listRevision = "";
+ this.tree.element.scrollTop = this.status[this.blockId]?.scrollTop || 0;
+ }
+ return;
+ }
+ if (!this.globalList) {
+ if (this.status[this.blockId] && !this.showingLoading) { this.saveStatus(); }
+ this.cancelContextRequests(this.tree.element, false);
+ this.itemRecords[0].forEach(record => this.destroyItemRecord(record));
+ this.itemRecords[0].clear();
+ this.globalList = new GlobalBacklinkList({
+ app: this.app,
+ host: this.tree.element,
+ scroll: this.getScrollElement(this.tree),
+ state: () => this.viewState,
+ foldedTypes: () => normalizeBacklinkFoldTypes(this.viewState?.get("foldedBlockTypes")),
+ open: id => this.openDocument({app: this.app, id, action: [Constants.CB_GET_CONTEXT]}),
+ editorAdded: editor => {
+ this.editors.push(editor);
+ if (this.type === "bottom") {
+ editor.protyle.wysiwyg.element.addEventListener("focusin", () => this.setOwnerFocus());
+ }
+ },
+ editorRemoved: editor => {
+ const index = this.editors.indexOf(editor);
+ if (index !== -1) { this.editors.splice(index, 1); }
+ },
+ count: total => {
+ const countElement = this.element.querySelector(".listCount");
+ countElement.textContent = total.toString();
+ countElement.classList.toggle("fn__none", total === 0 && this.type !== "bottom");
+ if (this.type === "bottom") {
+ this.element.classList.toggle("sy__backlink--backlinks-empty", total === 0 && !this.inputsElement[0].value);
+ const empty = total === 0 && !this.inputsElement[0].value &&
+ this.element.classList.contains("sy__backlink--mentions-empty");
+ if (empty !== this.empty) { this.empty = empty; this.emptyChange?.(empty); }
+ }
+ },
+ });
+ }
+ this.globalList.search({
+ id: this.blockId,
+ notebook: isEncryptedBox(this.notebookId) ? this.notebookId : "",
+ keyword: this.inputsElement[0].value,
+ sort: mode,
+ containChildren: window.siyuan.config.editor.backlinkContainChildren,
+ sourceFilter: getBacklinkSourceFilterParam(this.sourceFilter),
+ }, refresh);
+ }
+
private updateSourceFilterButton() {
this.element.querySelector('[data-type="sourceFilter"]')?.classList.toggle(
"block__icon--active",
@@ -931,6 +1019,7 @@ export class BacklinkContent extends Model {
configureBacklinkTypeFold(record.editor.protyle, types, this.viewState);
}
});
+ this.globalList?.updateFoldTypes();
};
const blockTypeFoldSubmenu: IMenu[] = [{
label: window.siyuan.languages.reset,
@@ -1546,6 +1635,7 @@ export class BacklinkContent extends Model {
}
private captureReadingAnchor(isMention: boolean) {
+ if (!isMention && this.globalList) { return; }
if (this.type !== "bottom") {
return this.capturePaneReadingAnchor(isMention);
}
@@ -1585,6 +1675,7 @@ export class BacklinkContent extends Model {
}
private restorePersistedReadingAnchor(isMention: boolean, loadedRootID?: string) {
+ if (!isMention && this.globalList) { return; }
if (this.type === "bottom" && !this.isBottomReadingAnchorViewportActive()) {
return;
}
@@ -1732,6 +1823,8 @@ export class BacklinkContent extends Model {
}
private resetRenderedData(resetLists: boolean) {
+ this.globalList?.destroy();
+ this.globalList = undefined;
cancelHeightAnimation(this.tree.element);
cancelHeightAnimation(this.mTree.element);
this.bottomLayoutScroll?.reset();
@@ -1923,6 +2016,7 @@ export class BacklinkContent extends Model {
notebook?: string,
knownRevision?: string,
includeMentions?: boolean,
+ includeBacklinks?: boolean,
} = {
sort: parseInt(this.tree.element.previousElementSibling.querySelector('[data-type="sort"]').getAttribute("data-sort")).toString(),
mSort: parseInt(this.mTree.element.previousElementSibling.querySelector('[data-type="mSort"]').getAttribute("data-sort")).toString(),
@@ -1930,6 +2024,9 @@ export class BacklinkContent extends Model {
mk: this.inputsElement[1].value,
id: this.blockId,
};
+ if (notebookId) { this.notebookId = notebookId; }
+ this.syncGlobalList(init || refreshAllContexts || this.dirty);
+ if (this.globalList) { param.includeBacklinks = false; }
if (this.onlyBacklinks) {
param.includeMentions = false;
}
@@ -2033,9 +2130,9 @@ export class BacklinkContent extends Model {
this.status[this.blockId] = {
sort: parseInt(this.tree.element.previousElementSibling.querySelector('[data-type="sort"]').getAttribute("data-sort")),
mSort: parseInt(this.mTree.element.previousElementSibling.querySelector('[data-type="mSort"]').getAttribute("data-sort")),
- scrollTop: this.tree.element.scrollTop,
+ scrollTop: this.globalList ? this.status[this.blockId]?.scrollTop || 0 : this.tree.element.scrollTop,
mScrollTop: this.mTree.element.scrollTop,
- backlinkOpenIds: [],
+ backlinkOpenIds: this.globalList ? this.status[this.blockId]?.backlinkOpenIds || [] : [],
backlinkMOpenIds: [],
backlinkMStatus: 3, // 0 全展开,1 展开一半箭头向下,2 展开一半箭头向上,3 全收起
backlinkFolded: this.tree.element.classList.contains("fn__none") ||
@@ -2082,6 +2179,7 @@ export class BacklinkContent extends Model {
};
}
const wasLoading = this.showingLoading;
+ if (this.globalList) { data = {...data, linkRefsCount: this.globalList.count}; }
this.showingLoading = false;
this.setRequesting(false);
@@ -2096,7 +2194,7 @@ export class BacklinkContent extends Model {
}));
const runtimeAnchorBlockID = this.blockId;
const runtimeAnchorQueryKey = this.renderedQueryKey;
- const backlinkChanged = this.reconcileList(this.tree, data.backlinks, false);
+ const backlinkChanged = this.globalList ? false : this.reconcileList(this.tree, data.backlinks, false);
const backmentionChanged = this.reconcileList(this.mTree, data.backmentions, true);
this.renderedQueryKey = this.listQueryKey;
if (backlinkChanged || backmentionChanged) {
@@ -2145,7 +2243,7 @@ export class BacklinkContent extends Model {
data.backmentions.map(item => item.id),
);
const backlinkFolded = backlinkState.folded ||
- (this.type !== "bottom" && data.linkRefsCount === 0 && data.mentionsCount > 0);
+ (!this.globalList && this.type !== "bottom" && data.linkRefsCount === 0 && data.mentionsCount > 0);
const backmentionFolded = backmentionState.folded ||
(this.type !== "bottom" && data.mentionsCount === 0);
this.status[this.blockId] = {
@@ -2287,6 +2385,7 @@ export class BacklinkContent extends Model {
}
public markDirty() {
+ this.globalList?.markDirty();
this.indexChangeVersion++;
this.dirty = true;
this.pendingFull = true;
@@ -2299,6 +2398,7 @@ export class BacklinkContent extends Model {
if (!change?.backlinkChanged) {
return;
}
+ this.globalList?.markDirty();
this.indexChangeVersion++;
this.dirty = true;
this.pendingFull = this.pendingFull || Boolean(change.backlinkFull);
@@ -2364,6 +2464,8 @@ export class BacklinkContent extends Model {
if (this.blockId && !this.showingLoading) {
this.saveStatus();
}
+ this.globalList?.destroy();
+ this.globalList = undefined;
this.destroyed = true;
this.viewStateGeneration++;
this.clearReadingAnchorTimers();
diff --git a/app/src/layout/dock/GlobalBacklinkList.ts b/app/src/layout/dock/GlobalBacklinkList.ts
new file mode 100644
index 0000000000..b2f008659b
--- /dev/null
+++ b/app/src/layout/dock/GlobalBacklinkList.ts
@@ -0,0 +1,469 @@
+import type {App} from "../../index";
+/// #if MOBILE
+import {registerMobileSecondaryEditor} from "../../mobile/util/secondaryEditors";
+/// #endif
+import type {GlobalBacklinkItem, GlobalBacklinkListRequestInput} from "../../types/api";
+import {fetchSyncPost} from "../../util/fetch";
+import {Protyle} from "../../protyle";
+import {hasAVEditorSession} from "../../protyle/render/av/editorSession";
+import {searchMarkRender} from "../../protyle/render/searchMarkRender";
+import {waitForPendingTransactions} from "../../protyle/util/transactionQueue";
+import {registerViewFoldContext, unregisterViewFoldContext} from "../../protyle/util/viewFold";
+import {configureBacklinkTypeFold} from "../../protyle/wysiwyg/backlinkTypeFold";
+import type {ViewStateService} from "../../util/viewState";
+import {GLOBAL_BACKLINK_PAGE_SIZE, globalBacklinkPageWindow} from "./globalBacklinkPaging";
+
+interface IGlobalBacklinkRecord {
+ item: GlobalBacklinkItem;
+ element: HTMLElement;
+ source: HTMLElement;
+ body: HTMLElement;
+ editor?: Protyle;
+ releasing?: boolean;
+}
+
+type GlobalBacklinkQueryInput = Omit<GlobalBacklinkListRequestInput, "snapshot" | "offset" | "anchorID">;
+
+interface IGlobalBacklinkAnchor {
+ id: string;
+ offset: number;
+}
+
+// 固定数量的页容器与编辑器留在视口附近,其余位置由高度占位维持。
+export class GlobalBacklinkList {
+ public readonly element = document.createElement("div");
+ private top = document.createElement("div");
+ private bottom = document.createElement("div");
+ private message = document.createElement("button");
+ private records = new Map<string, IGlobalBacklinkRecord>();
+ private pages = new Map<number, HTMLElement>();
+ private heights = new Map<number, number>();
+ private query?: GlobalBacklinkQueryInput;
+ private key = "";
+ private snapshot = "";
+ private total = 0;
+ private generation = 0;
+ private loading = false;
+ private loadingContexts = false;
+ private frame = 0;
+ private destroyed = false;
+ private dirty = false;
+ private composing = false;
+ private dragging = false;
+ private scrollVersion = 0;
+ private onUserScroll = () => { this.scrollVersion++; this.onScroll(); };
+ private controller = new AbortController();
+ private collapsed = false;
+ private pendingAnchor?: IGlobalBacklinkAnchor;
+ private lastAnchor?: IGlobalBacklinkAnchor;
+ private onScroll = () => {
+ if (!this.frame) {
+ this.frame = window.requestAnimationFrame(() => {
+ this.frame = 0;
+ this.lastAnchor = this.captureAnchor() || this.lastAnchor;
+ this.options.state()?.set(this.anchorField(), this.lastAnchor);
+ void this.updateViewport();
+ });
+ }
+ };
+ private onFocusout = () => window.setTimeout(() => {
+ if (this.dirty && !this.isEditing()) {
+ void this.refresh(true);
+ } else {
+ this.onScroll();
+ }
+ }, 100);
+ private onCompositionStart = () => { this.composing = true; };
+ private onCompositionEnd = () => { this.composing = false; this.onFocusout(); };
+ private onDragStart = () => { this.dragging = true; };
+ private onDragEnd = () => { this.dragging = false; this.onFocusout(); };
+ private resize: ResizeObserver;
+
+ constructor(private options: {
+ app: App;
+ host: HTMLElement;
+ scroll: HTMLElement;
+ state: () => ViewStateService | undefined;
+ foldedTypes: () => string[];
+ open: (id: string) => void;
+ editorAdded: (editor: Protyle) => void;
+ editorRemoved: (editor: Protyle) => void;
+ count: (total: number) => void;
+ }) {
+ this.element.className = "backlinkList__global";
+ this.message.className = "b3-button b3-button--text fn__block";
+ this.message.addEventListener("click", () => {
+ if (!this.snapshot) { void this.refresh(true); } else { this.onScroll(); }
+ });
+ this.element.append(this.top, this.bottom, this.message);
+ options.host.replaceChildren(this.element);
+ options.scroll.addEventListener("scroll", this.onUserScroll, {passive: true});
+ this.element.addEventListener("focusout", this.onFocusout);
+ this.element.addEventListener("av-editor-close", this.onFocusout);
+ this.element.addEventListener("compositionstart", this.onCompositionStart);
+ this.element.addEventListener("compositionend", this.onCompositionEnd);
+ this.element.addEventListener("dragstart", this.onDragStart);
+ this.element.addEventListener("dragend", this.onDragEnd);
+ this.resize = new ResizeObserver(this.onScroll);
+ this.resize.observe(options.scroll);
+ }
+
+ private anchorField() { return `anchor:global:${this.query?.sort}`; }
+
+ public search(query: GlobalBacklinkQueryInput, refresh: boolean) {
+ const key = JSON.stringify(query);
+ if (key !== this.key) {
+ this.generation++;
+ this.controller.abort();
+ this.key = key;
+ this.query = query;
+ this.lastAnchor = this.options.state()?.get<IGlobalBacklinkAnchor>(this.anchorField());
+ this.heights.clear();
+ void this.refresh(false);
+ } else if (refresh) {
+ this.dirty = true;
+ if (!this.isEditing()) { void this.refresh(true); }
+ }
+ }
+
+ public markDirty() { this.dirty = true; }
+
+ public updateFoldTypes() {
+ const state = this.options.state();
+ if (state) {
+ this.records.forEach(record => {
+ if (record.editor) { configureBacklinkTypeFold(record.editor.protyle, this.options.foldedTypes(), state); }
+ });
+ }
+ }
+
+ public get count() { return this.total; }
+
+ public setCollapsed(value: boolean) {
+ this.collapsed = value;
+ this.records.forEach(record => {
+ record.body.classList.toggle("fn__none", value);
+ record.source.classList.toggle("fn__none", !value && Boolean(record.editor));
+ });
+ this.onScroll();
+ }
+
+ private isEditing() {
+ return this.composing || this.dragging || hasAVEditorSession(this.element) ||
+ Array.from(this.records.values()).some(record => record.editor?.protyle.element.contains(document.activeElement));
+ }
+
+ private captureAnchor(): IGlobalBacklinkAnchor | undefined {
+ const viewport = this.options.scroll.getBoundingClientRect();
+ for (const page of Array.from(this.pages.entries()).sort((a, b) => a[0] - b[0])) {
+ for (const element of Array.from(page[1].children)) {
+ const rect = element.getBoundingClientRect();
+ if (rect.bottom > viewport.top && rect.top < viewport.bottom) {
+ return {id: element.getAttribute("data-global-backlink-id"), offset: rect.top - viewport.top};
+ }
+ }
+ }
+ }
+
+ private restoreAnchor(anchor?: IGlobalBacklinkAnchor) {
+ const record = anchor && this.records.get(anchor.id);
+ if (record) {
+ this.options.scroll.scrollTop += record.element.getBoundingClientRect().top -
+ this.options.scroll.getBoundingClientRect().top - anchor.offset;
+ }
+ }
+
+ private async refresh(preserve: boolean) {
+ if (this.destroyed || !this.query || this.isEditing()) { this.dirty = true; return; }
+ const generation = ++this.generation;
+ this.controller.abort();
+ this.controller = new AbortController();
+ const anchor = preserve ? this.captureAnchor() || this.lastAnchor : this.lastAnchor;
+ this.pendingAnchor = anchor;
+ this.dirty = false;
+ await Promise.all(Array.from(this.records.values()).map(record =>
+ record.editor ? waitForPendingTransactions(record.editor.protyle) : Promise.resolve()));
+ if (generation !== this.generation || this.destroyed || this.isEditing()) { this.dirty = true; return; }
+ this.clearPages();
+ this.snapshot = "";
+ this.loading = false;
+ this.loadingContexts = false;
+ this.total = 0;
+ this.top.style.height = this.bottom.style.height = "0px";
+ await this.loadPage(0, anchor?.id);
+ }
+
+ private async loadPage(offset: number, anchorID?: string) {
+ if (this.loading || this.destroyed || !this.query) { return; }
+ this.loading = true;
+ const generation = this.generation;
+ this.message.textContent = window.siyuan.languages.loading;
+ try {
+ const response = await fetchSyncPost("/api/ref/getGlobalBacklinks", {...this.query, snapshot: this.snapshot, offset, anchorID}, undefined, true, this.controller.signal);
+ if (this.destroyed || generation !== this.generation) { return; }
+ if (response.code !== 0 || !response.data) {
+ this.clearUnavailable();
+ throw new Error(response.msg);
+ }
+ const data = response.data;
+ if (data.expired) { this.snapshot = ""; this.dirty = true; this.onFocusout(); return; }
+ this.snapshot = data.snapshot;
+ this.total = data.total;
+ this.options.count(this.total);
+ const anchor = this.captureAnchor();
+ this.addPage(data.offset, data.items);
+ this.updateSpacers();
+ this.restoreAnchor(this.pendingAnchor || anchor);
+ this.lastAnchor = this.pendingAnchor || anchor || this.lastAnchor;
+ this.pendingAnchor = undefined;
+ this.message.textContent = this.total === 0 ? window.siyuan.languages.emptyContent : "";
+ this.message.classList.toggle("fn__none", this.total > 0);
+ this.onScroll();
+ } catch (error) {
+ if (generation === this.generation && !this.destroyed) {
+ this.message.classList.remove("fn__none");
+ this.message.textContent = window.siyuan.languages.retry;
+ console.error(error);
+ }
+ } finally {
+ if (generation === this.generation) { this.loading = false; }
+ }
+ }
+
+ private addPage(offset: number, items: GlobalBacklinkItem[]) {
+ if (this.pages.has(offset)) { return; }
+ const page = document.createElement("div");
+ this.pages.set(offset, page);
+ items.forEach(item => {
+ const element = document.createElement("div");
+ element.className = "backlinkList__item";
+ element.setAttribute("data-global-backlink-id", item.id);
+ const source = document.createElement("button");
+ source.className = "backlinkList__source";
+ source.type = "button";
+ source.textContent = item.hPath;
+ source.title = item.hPath;
+ source.addEventListener("click", event => { event.stopPropagation(); this.options.open(item.id); });
+ const body = document.createElement("div");
+ body.style.minHeight = "72px";
+ body.classList.toggle("fn__none", this.collapsed);
+ body.textContent = item.anchor || window.siyuan.languages.loading;
+ element.append(source, body);
+ page.append(element);
+ this.records.set(item.id, {item, element, source, body});
+ });
+ const next = Array.from(this.pages.keys()).sort((a, b) => a - b).find(value => value > offset);
+ this.element.insertBefore(page, next === undefined ? this.bottom : this.pages.get(next));
+ }
+
+ private height(offset: number) {
+ return this.heights.get(offset) ?? Math.min(GLOBAL_BACKLINK_PAGE_SIZE, this.total - offset) * 104;
+ }
+
+ private updateSpacers() {
+ const offsets = Array.from(this.pages.keys()).sort((a, b) => a - b);
+ if (offsets.length === 0) { return; }
+ let top = 0;
+ let bottom = 0;
+ for (let offset = 0; offset < this.total; offset += GLOBAL_BACKLINK_PAGE_SIZE) {
+ if (offset < offsets[0]) { top += this.height(offset); }
+ if (offset > offsets[offsets.length - 1]) { bottom += this.height(offset); }
+ }
+ this.top.style.height = `${top}px`;
+ this.bottom.style.height = `${bottom}px`;
+ this.element.querySelectorAll("[data-global-gap]").forEach(element => element.remove());
+ offsets.forEach((offset, index) => {
+ if (index === 0) { return; }
+ let height = 0;
+ for (let missing = offsets[index - 1] + GLOBAL_BACKLINK_PAGE_SIZE; missing < offset; missing += GLOBAL_BACKLINK_PAGE_SIZE) {
+ height += this.height(missing);
+ }
+ if (height > 0) {
+ const gap = document.createElement("div");
+ gap.setAttribute("data-global-gap", "true");
+ gap.style.height = `${height}px`;
+ this.element.insertBefore(gap, this.pages.get(offset));
+ }
+ });
+ }
+
+ private trimPages(center: number) {
+ const range = globalBacklinkPageWindow(center, this.total);
+ this.pages.forEach((page, offset) => {
+ if (offset >= range.start && offset < range.end || page.contains(document.activeElement) || hasAVEditorSession(page)) { return; }
+ if (Array.from(this.records.values()).some(record => page.contains(record.element) && record.editor)) {
+ this.records.forEach(record => { if (page.contains(record.element)) { void this.release(record); } });
+ return;
+ }
+ this.heights.set(offset, page.getBoundingClientRect().height);
+ this.records.forEach((record, id) => { if (page.contains(record.element)) { this.records.delete(id); } });
+ page.remove();
+ this.pages.delete(offset);
+ });
+ }
+
+ private async updateViewport() {
+ if (this.destroyed || !this.snapshot || !this.element.getClientRects().length) { return; }
+ const generation = this.generation;
+ const viewport = this.options.scroll.getBoundingClientRect();
+ const candidates: IGlobalBacklinkRecord[] = [];
+ this.records.forEach(record => {
+ const rect = record.element.getBoundingClientRect();
+ if (!this.collapsed && rect.bottom > viewport.top - 320 && rect.top < viewport.bottom + 320) {
+ candidates.push(record);
+ } else { void this.release(record); }
+ });
+ const centerY = (viewport.top + viewport.bottom) / 2;
+ candidates.sort((a, b) => Math.abs(a.element.getBoundingClientRect().top - centerY) - Math.abs(b.element.getBoundingClientRect().top - centerY));
+ candidates.slice(16).forEach(record => { void this.release(record); });
+ void this.loadContexts(candidates.slice(0, 16).filter(record => !record.editor && !record.releasing));
+ let y = this.element.getBoundingClientRect().top;
+ let center = 0;
+ for (; center + GLOBAL_BACKLINK_PAGE_SIZE < this.total; center += GLOBAL_BACKLINK_PAGE_SIZE) {
+ const height = this.pages.get(center)?.getBoundingClientRect().height ?? this.height(center);
+ if (y + height > centerY) { break; }
+ y += height;
+ }
+ const range = globalBacklinkPageWindow(center, this.total);
+ if (this.pages.has(center)) {
+ const offsets: number[] = [];
+ for (let offset = range.start; offset < range.end; offset += GLOBAL_BACKLINK_PAGE_SIZE) { offsets.push(offset); }
+ offsets.sort((a, b) => Math.abs(a - center) - Math.abs(b - center));
+ for (const offset of offsets) {
+ if (!this.pages.has(offset)) { await this.loadPage(offset); break; }
+ }
+ } else { await this.loadPage(center); }
+ if (this.destroyed || generation !== this.generation) { return; }
+ const anchor = this.captureAnchor();
+ this.trimPages(center);
+ this.updateSpacers();
+ this.restoreAnchor(anchor);
+ }
+
+ private async loadContexts(records: IGlobalBacklinkRecord[]) {
+ if (this.loadingContexts || records.length === 0) { return; }
+ this.loadingContexts = true;
+ const generation = this.generation;
+ try {
+ const response = await fetchSyncPost("/api/ref/getGlobalBacklinkContexts", {...this.query, snapshot: this.snapshot, ids: records.map(record => record.item.id)}, undefined, true, this.controller.signal);
+ if (generation !== this.generation || this.destroyed) { return; }
+ if (response.code !== 0 || !response.data) {
+ this.clearUnavailable();
+ throw new Error(response.msg);
+ }
+ if (response.data.expired) { this.dirty = true; this.onFocusout(); return; }
+ const anchor = this.captureAnchor();
+ const scrollVersion = this.scrollVersion;
+ for (const item of response.data.items || []) {
+ const record = this.records.get(item.id);
+ if (!record || record.editor || !records.includes(record) || this.collapsed) { continue; }
+ const viewport = this.options.scroll.getBoundingClientRect();
+ const rect = record.element.getBoundingClientRect();
+ if (rect.bottom <= viewport.top - 320 || rect.top >= viewport.bottom + 320 ||
+ Array.from(this.records.values()).filter(value => value.editor).length >= 16) { continue; }
+ record.body.replaceChildren();
+ record.body.setAttribute("data-defid", this.query.id);
+ record.body.setAttribute("data-ismention", "false");
+ record.body.setAttribute("data-notebook-id", record.item.box);
+ record.body.setAttribute("data-backlink-show-document", "true");
+ const editor = new Protyle(this.options.app, record.body, {
+ blockId: record.item.rootID,
+ notebookId: record.item.box,
+ backlinkData: [item],
+ click: {preventInsetEmptyBlock: true},
+ render: {background: false, gutter: true, scroll: false, breadcrumb: false},
+ });
+ record.editor = editor;
+ record.source.classList.add("fn__none");
+ /// #if MOBILE
+ registerMobileSecondaryEditor(editor, () => this.options.open(record.item.id));
+ /// #endif
+ this.options.editorAdded(editor);
+ searchMarkRender(editor.protyle, this.query.keyword?.trim().split(/\s+/) || [], undefined, undefined, {
+ excludeSelector: ".protyle-breadcrumb__bar[data-backlink-id]",
+ });
+ const state = this.options.state();
+ if (state) {
+ configureBacklinkTypeFold(editor.protyle, this.options.foldedTypes(), state);
+ await registerViewFoldContext(editor.protyle, {
+ store: state, pane: "backlink", rootID: record.item.rootID,
+ getOccurrenceID: () => `global:${item.id}`,
+ getOccurrenceRevision: () => item.revision,
+ });
+ }
+ if (this.destroyed || generation !== this.generation) { return; }
+ }
+ if (scrollVersion === this.scrollVersion) { this.restoreAnchor(anchor); }
+ } catch (error) {
+ if (generation !== this.generation || this.destroyed) { return; }
+ console.error(error);
+ this.message.classList.remove("fn__none");
+ this.message.textContent = window.siyuan.languages.retry;
+ } finally {
+ if (generation === this.generation) { this.loadingContexts = false; }
+ }
+ }
+
+ private async release(record: IGlobalBacklinkRecord) {
+ const editor = record.editor;
+ if (!editor || record.releasing || this.composing || this.dragging ||
+ record.element.contains(document.activeElement) || hasAVEditorSession(record.element)) { return; }
+ record.releasing = true;
+ await waitForPendingTransactions(editor.protyle);
+ record.releasing = false;
+ if (this.destroyed || this.composing || this.dragging || record.editor !== editor ||
+ record.element.contains(document.activeElement) || hasAVEditorSession(record.element)) { return; }
+ const height = record.body.getBoundingClientRect().height;
+ unregisterViewFoldContext(editor.protyle);
+ this.options.editorRemoved(editor);
+ editor.destroy();
+ record.editor = undefined;
+ record.body.replaceChildren();
+ record.body.style.minHeight = `${Math.max(height, 72)}px`;
+ record.body.textContent = record.item.anchor;
+ record.source.classList.remove("fn__none");
+ this.onScroll();
+ }
+
+ private clearPages() {
+ this.records.forEach(record => {
+ if (record.editor) {
+ unregisterViewFoldContext(record.editor.protyle);
+ this.options.editorRemoved(record.editor);
+ record.editor.destroy();
+ record.editor = undefined;
+ }
+ });
+ this.records.clear();
+ this.pages.forEach(page => page.remove());
+ this.pages.clear();
+ this.element.querySelectorAll("[data-global-gap]").forEach(element => element.remove());
+ }
+
+ private clearUnavailable() {
+ this.generation++;
+ this.controller.abort();
+ this.controller = new AbortController();
+ this.loading = this.loadingContexts = false;
+ this.clearPages();
+ this.snapshot = "";
+ this.total = 0;
+ this.top.style.height = this.bottom.style.height = "0px";
+ this.options.count(0);
+ this.message.classList.remove("fn__none");
+ this.message.textContent = window.siyuan.languages.retry;
+ }
+
+ public destroy() {
+ this.lastAnchor = this.captureAnchor() || this.lastAnchor;
+ if (this.lastAnchor) { this.options.state()?.set(this.anchorField(), this.lastAnchor); }
+ this.destroyed = true;
+ this.controller.abort();
+ this.generation++;
+ window.cancelAnimationFrame(this.frame);
+ this.resize.disconnect();
+ this.options.scroll.removeEventListener("scroll", this.onUserScroll);
+ this.clearPages();
+ this.element.remove();
+ }
+}
diff --git a/app/src/layout/dock/globalBacklinkPaging.test.ts b/app/src/layout/dock/globalBacklinkPaging.test.ts
new file mode 100644
index 0000000000..304b38d856
--- /dev/null
+++ b/app/src/layout/dock/globalBacklinkPaging.test.ts
@@ -0,0 +1,16 @@
+import {test} from "node:test";
+import * as assert from "node:assert/strict";
+import {globalBacklinkPageOffset, globalBacklinkPageWindow, GLOBAL_BACKLINK_PAGE_WINDOW, GLOBAL_BACKLINK_PAGE_SIZE} from "./globalBacklinkPaging";
+
+test("global backlink windows remain bounded at the beginning, middle, and end", () => {
+ for (const total of [0, 1, 49, 50, 51, 249, 250, 251, 100000]) {
+ for (const index of [0, Math.floor(total / 2), total - 1]) {
+ const offset = globalBacklinkPageOffset(index);
+ const range = globalBacklinkPageWindow(offset, total);
+ assert.ok(range.start >= 0);
+ assert.ok(range.end <= total);
+ assert.ok(range.end - range.start <= GLOBAL_BACKLINK_PAGE_WINDOW * GLOBAL_BACKLINK_PAGE_SIZE);
+ if (total > 0) { assert.ok(offset >= range.start && offset < range.end); }
+ }
+ }
+});
diff --git a/app/src/layout/dock/globalBacklinkPaging.ts b/app/src/layout/dock/globalBacklinkPaging.ts
new file mode 100644
index 0000000000..03688ac18e
--- /dev/null
+++ b/app/src/layout/dock/globalBacklinkPaging.ts
@@ -0,0 +1,12 @@
+export const GLOBAL_BACKLINK_PAGE_SIZE = 50;
+export const GLOBAL_BACKLINK_PAGE_WINDOW = 5;
+
+export const globalBacklinkPageOffset = (index: number) =>
+ Math.floor(Math.max(0, index) / GLOBAL_BACKLINK_PAGE_SIZE) * GLOBAL_BACKLINK_PAGE_SIZE;
+
+export const globalBacklinkPageWindow = (center: number, total: number) => {
+ const last = globalBacklinkPageOffset(Math.max(0, total - 1));
+ const start = Math.max(0, Math.min(center - 2 * GLOBAL_BACKLINK_PAGE_SIZE,
+ last - (GLOBAL_BACKLINK_PAGE_WINDOW - 1) * GLOBAL_BACKLINK_PAGE_SIZE));
+ return {start, end: Math.min(total, start + GLOBAL_BACKLINK_PAGE_WINDOW * GLOBAL_BACKLINK_PAGE_SIZE)};
+};
diff --git a/app/src/protyle/wysiwyg/renderBacklink.ts b/app/src/protyle/wysiwyg/renderBacklink.ts
index cea96dcb8c..82325893ec 100644
--- a/app/src/protyle/wysiwyg/renderBacklink.ts
+++ b/app/src/protyle/wysiwyg/renderBacklink.ts
@@ -62,9 +62,9 @@ const removeBacklinkDOMRecord = (record: IBacklinkDOMRecord) => {
getBacklinkDOMNodes(record.anchor).forEach(item => item.parentNode?.removeChild(item));
};
-const createBacklinkDOMRecord = (item: IBacklinkData, index: number, id: string) => {
+const createBacklinkDOMRecord = (item: IBacklinkData, index: number, id: string, showDocument: boolean) => {
const template = document.createElement("template");
- template.innerHTML = genBreadcrumb(item.blockPaths, false, index, id) + setBacklinkFold(item.dom, item.expand);
+ template.innerHTML = genBreadcrumb(item.blockPaths, showDocument, index, id) + setBacklinkFold(item.dom, item.expand);
markBacklinkReference(template.content, item.referenceBlockID);
const nodes = Array.from(template.content.childNodes);
(nodes[0] as HTMLElement).setAttribute("data-backlink-revision", item.revision || "");
@@ -133,7 +133,7 @@ export const renderBacklink = (protyle: IProtyle, backlinkData: IBacklinkData[])
}
if (!record || !item.revision || record.revision !== item.revision) {
clearViewFoldDefaults(protyle, id);
- const created = createBacklinkDOMRecord(item, index, id);
+ const created = createBacklinkDOMRecord(item, index, id, protyle.element.hasAttribute("data-backlink-show-document"));
if (record) {
const restoreAVScroll = reuseBacklinkAVSources(created.nodes, created.record.databases, record.databases);
created.nodes.forEach(node => element.insertBefore(node, record.anchor));
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index a53c6d755e..4e07196d12 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -558,7 +558,7 @@ export type BacklinkDocumentRequestInput = { "blockSort"?: number; "containChild
export type BacklinkList = { "backlinks": Array<BacklinkPath | null> | null; "backmentions": Array<BacklinkPath | null> | null; "box": string; "k": string; "linkRefsCount": number; "mentionsCount": number; "mk": string; "revision": string; "unchanged": boolean; };
-export type BacklinkListRequestInput = { "containChildren"?: boolean | null; "id"?: string | null; "includeMentions"?: boolean | null; "k"?: string; "knownRevision"?: string | null; "mSort"?: string | null; "mk"?: string; "notebook"?: string | null; "refDefCandidates"?: boolean | null; "sort"?: string | null; "sourceFilter"?: BacklinkSourceFilterInput | null; };
+export type BacklinkListRequestInput = { "containChildren"?: boolean | null; "id"?: string | null; "includeBacklinks"?: boolean | null; "includeMentions"?: boolean | null; "k"?: string; "knownRevision"?: string | null; "mSort"?: string | null; "mk"?: string; "notebook"?: string | null; "refDefCandidates"?: boolean | null; "sort"?: string | null; "sourceFilter"?: BacklinkSourceFilterInput | null; };
export type BacklinkPath = { "blocks"?: Array<SearchBlock | null>; "box": string; "children"?: Array<SearchPath | null>; "count": number; "created": string; "depth": number; "folded": boolean; "hPath": string; "id": string; "name": string; "nameIsHTML"?: boolean; "nodeType": string; "number"?: string; "revision": string; "subType": string; "type": string; "updated": string; };
@@ -1112,6 +1112,16 @@ export type GetTagRequestInput = { "app"?: string | null; "ignoreMaxListHint"?:
export type GetUpdatedPackageRequestInput = { "frontend": string; };
+export type GlobalBacklinkContextData = { "expired": boolean; "items": Array<BacklinkContext | null> | null; };
+
+export type GlobalBacklinkContextRequestInput = { "containChildren": boolean; "id": string; "ids": Array<string>; "keyword"?: string; "notebook"?: string; "snapshot": string; "sort": number; "sourceFilter"?: BacklinkSourceFilterInput | null; };
+
+export type GlobalBacklinkItem = { "anchor": string; "box": string; "hPath": string; "id": string; "rootID": string; };
+
+export type GlobalBacklinkListData = { "expired": boolean; "items": Array<GlobalBacklinkItem | null> | null; "offset": number; "snapshot": string; "total": number; };
+
+export type GlobalBacklinkListRequestInput = { "anchorID"?: string; "containChildren": boolean; "id": string; "keyword"?: string; "notebook"?: string; "offset"?: number; "snapshot"?: string; "sort": number; "sourceFilter"?: BacklinkSourceFilterInput | null; };
+
export type GlobalGraphConf = { "d3": GraphD3 | null; "dailyNote": boolean; "minRefs": number; "type": GraphTypeFilter | null; };
export type GlobalGraphRequestInput = { "conf": GraphConfigurationFieldsInput; "k"?: string | null; "reqId"?: JSONValue | null; };
@@ -1684,7 +1694,7 @@ export type SetCriterionRequestInput = { "criterion": CriterionInput | null; };
export type SetDatabaseBlockViewRequestInput = { "avID": string; "id": string; "viewID": string; };
-export type SetEditorRequestInput = { "allowHTMLBLockScript"?: boolean | null; "allowSVGScript"?: boolean | null; "assetOpen"?: SettingAssetOpenInput | null; "backlinkBlockSort"?: number | null; "backlinkContainChildren"?: boolean | null; "backlinkExpandCount"?: number | null; "backlinkHideReference"?: boolean | null; "backlinkMentionExclude"?: string | null; "backlinkShowBottom"?: boolean | null; "backlinkSort"?: number | null; "backmentionExpandCount"?: number | null; "backmentionSort"?: number | null; "blockRefDynamicAnchorTextMaxLen"?: number | null; "checkBlockRef"?: boolean | null; "codeFontFamilies"?: Array<SettingEditorFontInput | null> | null; "codeLigatures"?: boolean | null; "codeLineWrap"?: boolean | null; "codeSyntaxHighlightLineNum"?: boolean | null; "codeTabSpaces"?: number | null; "cursorSurroundingLines"?: number | null; "databaseAttrClickMode"?: number | null; "databaseAttrHideEmpty"?: boolean | null; "databaseAttrShow"?: boolean | null; "databaseAttrUseTabs"?: boolean | null; "databaseAttrViewMode"?: number | null; "displayBookmarkIcon"?: boolean | null; "displayNetImgMark"?: boolean | null; "dragHTMLFileToIframe"?: boolean | null; "dynamicLoadBlocks"?: number | null; "embedBlockBreadcrumb"?: boolean | null; "emoji"?: Array<string> | null; "floatWindowDelay"?: number | null; "floatWindowMode"?: number | null; "fontFamilies"?: Array<SettingEditorFontInput | null> | null; "fontFamily"?: string | null; "fontFamilyDisplay"?: string | null; "fontSize"?: number | null; "fontSizeScrollZoom"?: boolean | null; "fontWeight"?: number | null; "fullWidth"?: boolean | null; "generateHistoryInterval"?: number | null; "hashTagSearch"?: boolean | null; "headingEmbedMode"?: number | null; "headingNumber"?: boolean | null; "headingNumberFormat"?: string | null; "historyRetentionDays"?: number | null; "justify"?: boolean | null; "katexMacros"?: string | null; "keepLoadedContent"?: boolean | null; "listItemDotNumberClickFocus"?: boolean | null; "listLogicalOutdent"?: boolean | null; "markdown"?: SettingMarkdownInput | null; "onlySearchForDoc"?: boolean | null; "pasteURLAutoConvert"?: boolean | null; "plantUMLServePath"?: string | null; "readOnly"?: boolean | null; "rtl"?: boolean | null; "spellcheck"?: boolean | null; "spellcheckLanguages"?: Array<string> | null; "virtualBlockRef"?: boolean | null; "virtualBlockRefExclude"?: string | null; "virtualBlockRefInclude"?: string | null; };
+export type SetEditorRequestInput = { "allowHTMLBLockScript"?: boolean | null; "allowSVGScript"?: boolean | null; "assetOpen"?: SettingAssetOpenInput | null; "backlinkBlockSort"?: number | null; "backlinkContainChildren"?: boolean | null; "backlinkExpandCount"?: number | null; "backlinkGlobalSort"?: number | null; "backlinkHideReference"?: boolean | null; "backlinkMentionExclude"?: string | null; "backlinkShowBottom"?: boolean | null; "backlinkSort"?: number | null; "backmentionExpandCount"?: number | null; "backmentionSort"?: number | null; "blockRefDynamicAnchorTextMaxLen"?: number | null; "checkBlockRef"?: boolean | null; "codeFontFamilies"?: Array<SettingEditorFontInput | null> | null; "codeLigatures"?: boolean | null; "codeLineWrap"?: boolean | null; "codeSyntaxHighlightLineNum"?: boolean | null; "codeTabSpaces"?: number | null; "cursorSurroundingLines"?: number | null; "databaseAttrClickMode"?: number | null; "databaseAttrHideEmpty"?: boolean | null; "databaseAttrShow"?: boolean | null; "databaseAttrUseTabs"?: boolean | null; "databaseAttrViewMode"?: number | null; "displayBookmarkIcon"?: boolean | null; "displayNetImgMark"?: boolean | null; "dragHTMLFileToIframe"?: boolean | null; "dynamicLoadBlocks"?: number | null; "embedBlockBreadcrumb"?: boolean | null; "emoji"?: Array<string> | null; "floatWindowDelay"?: number | null; "floatWindowMode"?: number | null; "fontFamilies"?: Array<SettingEditorFontInput | null> | null; "fontFamily"?: string | null; "fontFamilyDisplay"?: string | null; "fontSize"?: number | null; "fontSizeScrollZoom"?: boolean | null; "fontWeight"?: number | null; "fullWidth"?: boolean | null; "generateHistoryInterval"?: number | null; "hashTagSearch"?: boolean | null; "headingEmbedMode"?: number | null; "headingNumber"?: boolean | null; "headingNumberFormat"?: string | null; "historyRetentionDays"?: number | null; "justify"?: boolean | null; "katexMacros"?: string | null; "keepLoadedContent"?: boolean | null; "listItemDotNumberClickFocus"?: boolean | null; "listLogicalOutdent"?: boolean | null; "markdown"?: SettingMarkdownInput | null; "onlySearchForDoc"?: boolean | null; "pasteURLAutoConvert"?: boolean | null; "plantUMLServePath"?: string | null; "readOnly"?: boolean | null; "rtl"?: boolean | null; "spellcheck"?: boolean | null; "spellcheckLanguages"?: Array<string> | null; "virtualBlockRef"?: boolean | null; "virtualBlockRefExclude"?: string | null; "virtualBlockRefInclude"?: string | null; };
export type SetEntryVisibilityRequestInput = { "active"?: string | null; "profiles"?: Array<SettingEntryVisibilityProfileInput | null> | null; "version"?: number | null; };
@@ -1806,7 +1816,7 @@ export type SettingEditing = { "maxCompletionTokens": number; "maxHistoryMessage
export type SettingEditingInput = { "maxCompletionTokens"?: number | null; "maxHistoryMessages"?: number | null; "modelId"?: string | null; "temperature"?: number | null; };
-export type SettingEditor = { "allowHTMLBLockScript": boolean; "allowSVGScript": boolean; "assetOpen": SettingAssetOpen | null; "backlinkBlockSort": number; "backlinkContainChildren": boolean; "backlinkExpandCount": number; "backlinkHideReference": boolean; "backlinkMentionExclude": string; "backlinkShowBottom": boolean; "backlinkSort": number | null; "backmentionExpandCount": number; "backmentionSort": number | null; "blockRefDynamicAnchorTextMaxLen": number; "checkBlockRef": boolean | null; "codeFontFamilies": Array<SettingEditorFont | null> | null; "codeLigatures": boolean; "codeLineWrap": boolean; "codeSyntaxHighlightLineNum": boolean; "codeTabSpaces": number; "cursorSurroundingLines": number; "databaseAttrClickMode": number; "databaseAttrHideEmpty": boolean; "databaseAttrShow": boolean | null; "databaseAttrUseTabs": boolean | null; "databaseAttrViewMode": number; "displayBookmarkIcon": boolean; "displayNetImgMark": boolean; "dragHTMLFileToIframe": boolean; "dynamicLoadBlocks": number; "embedBlockBreadcrumb": boolean; "emoji": Array<string> | null; "floatWindowDelay": number | null; "floatWindowMode": number; "fontFamilies": Array<SettingEditorFont | null> | null; "fontFamily": string; "fontFamilyDisplay": string; "fontSize": number; "fontSizeScrollZoom": boolean; "fontWeight": number; "fullWidth": boolean; "generateHistoryInterval": number; "hashTagSearch": boolean | null; "headingEmbedMode": number; "headingNumber": boolean; "headingNumberFormat": string; "historyRetentionDays": number; "justify": boolean; "katexMacros": string; "keepLoadedContent": boolean; "listItemDotNumberClickFocus": boolean; "listLogicalOutdent": boolean; "markdown": SettingMarkdown | null; "onlySearchForDoc": boolean; "pasteURLAutoConvert": boolean; "plantUMLServePath": string; "readOnly": boolean; "rtl": boolean; "spellcheck": boolean; "spellcheckLanguages": Array<string> | null; "virtualBlockRef": boolean; "virtualBlockRefExclude": string; "virtualBlockRefInclude": string; };
+export type SettingEditor = { "allowHTMLBLockScript": boolean; "allowSVGScript": boolean; "assetOpen": SettingAssetOpen | null; "backlinkBlockSort": number; "backlinkContainChildren": boolean; "backlinkExpandCount": number; "backlinkGlobalSort": number; "backlinkHideReference": boolean; "backlinkMentionExclude": string; "backlinkShowBottom": boolean; "backlinkSort": number | null; "backmentionExpandCount": number; "backmentionSort": number | null; "blockRefDynamicAnchorTextMaxLen": number; "checkBlockRef": boolean | null; "codeFontFamilies": Array<SettingEditorFont | null> | null; "codeLigatures": boolean; "codeLineWrap": boolean; "codeSyntaxHighlightLineNum": boolean; "codeTabSpaces": number; "cursorSurroundingLines": number; "databaseAttrClickMode": number; "databaseAttrHideEmpty": boolean; "databaseAttrShow": boolean | null; "databaseAttrUseTabs": boolean | null; "databaseAttrViewMode": number; "displayBookmarkIcon": boolean; "displayNetImgMark": boolean; "dragHTMLFileToIframe": boolean; "dynamicLoadBlocks": number; "embedBlockBreadcrumb": boolean; "emoji": Array<string> | null; "floatWindowDelay": number | null; "floatWindowMode": number; "fontFamilies": Array<SettingEditorFont | null> | null; "fontFamily": string; "fontFamilyDisplay": string; "fontSize": number; "fontSizeScrollZoom": boolean; "fontWeight": number; "fullWidth": boolean; "generateHistoryInterval": number; "hashTagSearch": boolean | null; "headingEmbedMode": number; "headingNumber": boolean; "headingNumberFormat": string; "historyRetentionDays": number; "justify": boolean; "katexMacros": string; "keepLoadedContent": boolean; "listItemDotNumberClickFocus": boolean; "listLogicalOutdent": boolean; "markdown": SettingMarkdown | null; "onlySearchForDoc": boolean; "pasteURLAutoConvert": boolean; "plantUMLServePath": string; "readOnly": boolean; "rtl": boolean; "spellcheck": boolean; "spellcheckLanguages": Array<string> | null; "virtualBlockRef": boolean; "virtualBlockRefExclude": string; "virtualBlockRefInclude": string; };
export type SettingEditorFont = { "displayName": string; "family": string; "weight": number; };
@@ -4405,6 +4415,16 @@ export interface APIPOSTRoutes {
response: { "code": 0; "data": BacklinkContextData; "msg": string; } | { "code": -1 | 1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "json";
};
+ "/api/ref/getGlobalBacklinkContexts": {
+ request: GlobalBacklinkContextRequestInput;
+ response: { "code": 0; "data": GlobalBacklinkContextData; "msg": string; } | { "code": -1 | 1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
+ "/api/ref/getGlobalBacklinks": {
+ request: GlobalBacklinkListRequestInput;
+ response: { "code": 0; "data": GlobalBacklinkListData; "msg": string; } | { "code": -1 | 1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
"/api/ref/refreshBacklink": {
request: RefreshBacklinkRequestInput;
response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.ts
index 5ca56141ac..2642ac9c03 100644
--- a/app/src/types/config.d.ts
+++ b/app/src/types/config.d.ts
@@ -565,6 +565,7 @@ declare namespace Config {
* Backlink sort mode
*/
backlinkSort: number;
+ backlinkGlobalSort: number;
backlinkBlockSort: number;
/**
* Backmention sort mode
diff --git a/app/tests/backlinkSort.test.js b/app/tests/backlinkSort.test.js
index 77e3384143..ada31f775a 100644
--- a/app/tests/backlinkSort.test.js
+++ b/app/tests/backlinkSort.test.js
@@ -81,3 +81,23 @@ test("mention sorting does not offer anchor sorting", () => {
state.panel.showSortMenu("mSort", "2");
assert.equal(state.menuItems.some(item => item.label?.startsWith("backlink")), false);
});
+
+test("global sorting selects a flat mode and document sorting restores grouping", () => {
+ const state = createPanel();
+ let searches = 0;
+ state.panel.searchBacklinks = () => searches++;
+ state.panel.tree.element.previousElementSibling = {querySelector: () => ({setAttribute() {}})};
+ state.panel.showSortMenu("sort", "3");
+ const header = state.menuItems.findIndex(item => item.label === "backlinkGlobalSort");
+ state.menuItems[header + 1].click();
+ assert.equal(state.editor.backlinkGlobalSort, 1);
+ assert.equal(state.requests[0].data.backlinkGlobalSort, 1);
+ state.panel.showSortMenu("sort", "3");
+ assert.equal(state.menuItems.filter(item => item.checked).length, 1);
+ assert.equal(state.menuItems[header + 1].checked, true);
+ state.menuItems[header + 2].click();
+ assert.equal(state.editor.backlinkGlobalSort, 2);
+ state.menuItems.find(item => item.label === "modifiedDESC").click();
+ assert.equal(state.editor.backlinkGlobalSort, 0);
+ assert.equal(searches, 3);
+});
diff --git a/app/tests/globalBacklinkList.test.js b/app/tests/globalBacklinkList.test.js
new file mode 100644
index 0000000000..3e0adb90ed
--- /dev/null
+++ b/app/tests/globalBacklinkList.test.js
@@ -0,0 +1,136 @@
+const assert = require("node:assert/strict");
+const {readFileSync} = require("node:fs");
+const {test} = require("node:test");
+const {runInNewContext} = require("node:vm");
+const {ModuleKind, ScriptTarget, transpileModule} = require("typescript");
+
+const compiled = transpileModule(readFileSync("src/layout/dock/GlobalBacklinkList.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+}).outputText;
+
+const setup = () => {
+ const exports = {};
+ const requests = [];
+ let finishTransaction;
+ const transaction = new Promise(resolve => { finishTransaction = resolve; });
+ runInNewContext(compiled, {
+ exports, console, AbortController,
+ require: () => ({
+ fetchSyncPost: (url, data) => new Promise(resolve => requests.push({url, data, resolve})),
+ hasAVEditorSession: () => false,
+ waitForPendingTransactions: () => transaction,
+ unregisterViewFoldContext: () => {},
+ }),
+ document: {activeElement: null},
+ window: {siyuan: {languages: {loading: "loading", retry: "retry"}}},
+ });
+ const list = Object.create(exports.GlobalBacklinkList.prototype);
+ const applied = [];
+ Object.assign(list, {
+ generation: 1, query: {id: "target", sort: 1, containChildren: false}, snapshot: "snapshot",
+ controller: new AbortController(), loading: false, destroyed: false,
+ message: {classList: {toggle() {}, remove() {}}}, records: new Map(),
+ options: {count: total => applied.push(total), editorRemoved: editor => applied.push(editor)},
+ addPage: (...args) => applied.push(args), updateSpacers() {}, captureAnchor() {}, restoreAnchor() {}, onScroll() {},
+ });
+ return {list, requests, applied, finishTransaction};
+};
+
+test("late pages cannot replace a newer query", async () => {
+ const {list, requests, applied} = setup();
+ const pending = list.loadPage(50);
+ list.generation++;
+ requests[0].resolve({code: 0, data: {snapshot: "old", offset: 50, total: 100, items: []}});
+ await pending;
+ assert.equal(list.snapshot, "snapshot");
+ assert.equal(applied.length, 0);
+});
+
+test("page requests retain the snapshot and page position", async () => {
+ const {list, requests, applied} = setup();
+ const pending = list.loadPage(100);
+ assert.equal(requests[0].data.snapshot, "snapshot");
+ assert.equal(requests[0].data.offset, 100);
+ requests[0].resolve({code: 0, data: {snapshot: "snapshot", offset: 100, total: 121, items: []}});
+ await pending;
+ assert.equal(list.total, 121);
+ assert.equal(applied[0], 121);
+ assert.equal(list.loading, false);
+});
+
+test("editor recycling waits for transactions and preserves the measured height", async () => {
+ const {list, finishTransaction} = setup();
+ let destroyed = 0;
+ const editor = {protyle: {}, destroy: () => destroyed++};
+ const record = {editor, element: {contains: () => false}, body: {
+ style: {}, getBoundingClientRect: () => ({height: 280}), replaceChildren() {},
+ }, source: {classList: {remove() {}}}, item: {anchor: "A1"}};
+ const pending = list.release(record);
+ assert.equal(destroyed, 0);
+ finishTransaction();
+ await pending;
+ assert.equal(destroyed, 1);
+ assert.equal(record.body.style.minHeight, "280px");
+ assert.equal(record.editor, undefined);
+});
+
+test("returning focus while saving prevents editor recycling", async () => {
+ const {list, finishTransaction} = setup();
+ let focused = false;
+ let destroyed = 0;
+ const editor = {protyle: {}, destroy: () => destroyed++};
+ const record = {editor, element: {contains: () => focused}};
+ const pending = list.release(record);
+ focused = true;
+ finishTransaction();
+ await pending;
+ assert.equal(destroyed, 0);
+ assert.equal(record.editor, editor);
+});
+
+test("composition starting while saving prevents editor recycling", async () => {
+ const {list, finishTransaction} = setup();
+ let destroyed = 0;
+ const editor = {protyle: {}, destroy: () => destroyed++};
+ const record = {editor, element: {contains: () => false}};
+ const pending = list.release(record);
+ list.composing = true;
+ finishTransaction();
+ await pending;
+ assert.equal(destroyed, 0);
+ assert.equal(record.editor, editor);
+});
+
+test("clearing the list while saving destroys each editor once", async () => {
+ const {list, finishTransaction} = setup();
+ let destroyed = 0;
+ const editor = {protyle: {}, destroy: () => destroyed++};
+ const record = {editor, element: {contains: () => false}};
+ list.records.set("block", record);
+ list.pages = new Map();
+ list.element = {querySelectorAll: () => []};
+ const pending = list.release(record);
+ list.clearPages();
+ finishTransaction();
+ await pending;
+ assert.equal(destroyed, 1);
+ assert.equal(list.records.size, 0);
+});
+
+test("denied access clears content and invalidates other in-flight responses", async () => {
+ const {list, requests, applied} = setup();
+ let cleared = false;
+ list.clearPages = () => { cleared = true; };
+ list.top = {style: {}};
+ list.bottom = {style: {}};
+ const pending = list.loadPage(50);
+ const signal = list.controller.signal;
+ requests[0].resolve({code: 1, msg: "denied", data: null});
+ await pending;
+ assert.equal(cleared, true);
+ assert.equal(signal.aborted, true);
+ assert.equal(list.generation, 2);
+ assert.equal(list.snapshot, "");
+ assert.equal(list.loading, false);
+ assert.deepEqual(applied, [0]);
+});
diff --git a/app/tests/mobileBacklinks.test.js b/app/tests/mobileBacklinks.test.js
index 60abc3b5e8..0a7f4440a4 100644
--- a/app/tests/mobileBacklinks.test.js
+++ b/app/tests/mobileBacklinks.test.js
@@ -8,6 +8,7 @@ const sources = () => {
const preprocess = require("ifdef-loader/preprocessor").parse;
const modules = {};
for (const name of ["layout/dock/BacklinkContent", "layout/dock/backlinkRefresh",
+ "layout/dock/GlobalBacklinkList", "layout/dock/globalBacklinkPaging",
"layout/dock/backlinkReadingAnchor", "layout/dock/backlinkSourceFilter", "mobile/util/secondaryEditors",
"mobile/util/backlinkPanels", "mobile/util/openBacklinks", "mobile/util/bindBottomSheetDrag", "mobile/util/bindBottomSheetDialog", "protyle/util/transactionQueue",
"util/escape", "util/zIndex", "dialog/index", "layout/dock/panelSearch", "protyle/wysiwyg/backlinkTypeFold",
@@ -49,6 +50,8 @@ const runCases = async (sources) => {
"mobile/editor": {openMobileFileById: noop},
"util/fetch": {fetchPost: (url, data, callback) => new Promise(resolve => {
requests.push({url, data, reply: response => {callback?.({code: 0, data: response}); resolve();}});
+ }), fetchSyncPost: (url, data) => new Promise(resolve => {
+ requests.push({url, data, reply: response => resolve({code: 0, data: response})});
})},
"constants": {Constants: {TIMEOUT_LOAD: 0, TIMEOUT_OPENDIALOG: 0, TIMEOUT_DBLCLICK: 0}},
"protyle/util/compatibility": {updateHotkeyAfterTip: () => "", isNotCtrl: () => true},
@@ -179,6 +182,47 @@ const runCases = async (sources) => {
unregister();
panel.destroy();
+ window.siyuan.config.editor.backlinkGlobalSort = 1;
+ const globalElement = document.createElement("div");
+ globalElement.className = "panel";
+ document.body.appendChild(globalElement);
+ const globalPanel = new BacklinkContent({app: {}, element: globalElement, blockId: "host", rootId: "host",
+ notebookId: "box", type: "local", surface: "mobile-sheet", onlyBacklinks: true});
+ const unregisterGlobal = panels.registerMobileBacklinkPanel(globalPanel);
+ await tick();
+ for (const request of requests.splice(0)) {
+ if (request.url === "/api/ref/getBacklink2") {
+ assert.equal(request.data.includeBacklinks, false);
+ request.reply({...list, backlinks: [], linkRefsCount: 0});
+ } else {
+ assert.equal(request.url, "/api/ref/getGlobalBacklinks");
+ request.reply({snapshot: "global", offset: 0, total: 2, items: [
+ {id: "first", rootID: "source1", box: "box", hPath: "/Source 1", anchor: "A1"},
+ {id: "second", rootID: "source2", box: "box", hPath: "/Source 2", anchor: "A2"},
+ ]});
+ }
+ }
+ for (let i = 0; i < 20 && requests.length === 0; i++) { await tick(); }
+ assert.equal(requests[0]?.url, "/api/ref/getGlobalBacklinkContexts");
+ requests.shift().reply({expired: false, items: [
+ {id: "first", revision: "first1", dom: "", blockPaths: [], expand: true},
+ {id: "second", revision: "second1", dom: "", blockPaths: [], expand: true},
+ ]});
+ await tick();
+ assert.equal(globalPanel.editors.length, 2, "global entries from separate documents must mount independently");
+ assert.equal(globalElement.querySelector(".listCount").textContent, "2");
+ assert.equal(globalElement.querySelector(".listCount").classList.contains("fn__none"), false);
+ assert.equal(registry.getMobileSecondaryEditors().length, 2);
+ const globalEditors = [...globalPanel.editors];
+ panels.removeMobileBacklinkContent({notebookId: "box"});
+ assert.equal(globalPanel.editors.length, 0);
+ assert.equal(registry.getMobileSecondaryEditors().length, 0);
+ assert.ok(globalEditors.every(editor => editor.destroyed));
+ assert.equal(globalElement.querySelector("[data-global-backlink-id]"), null);
+ unregisterGlobal();
+ globalPanel.destroy();
+ window.siyuan.config.editor.backlinkGlobalSort = 0;
+
const ownerElement = document.createElement("div");
document.body.appendChild(ownerElement);
const owner = {app: {}, element: ownerElement, block: {rootID: "host"}, notebookId: "box"};
diff --git a/docs/API-CONTRACTS.md b/docs/API-CONTRACTS.md
index 37e0388e4f..7be8212fd6 100644
--- a/docs/API-CONTRACTS.md
+++ b/docs/API-CONTRACTS.md
@@ -118,6 +118,12 @@ Storage contracts keep arbitrary JSON limited to storage values; keys, recent do
`DirectJSONOutput` preserves protocols that return their own JSON objects or arrays without the kernel envelope. Use `SuccessDirectJSON` for these payloads. Endpoints that also support empty notification responses explicitly declare `NoContent` and return `SuccessNoContent`; HTTP validation requires status 204 and an empty body. However, authentication and read-only failures retain the kernel error envelope. Generated declarations record the direct output mode and optional empty-response support.
+The global backlink endpoints use a separate flat list. `/api/ref/getGlobalBacklinks` requires `id`, `sort` (`1` natural ascending or `2` natural descending), and `containChildren`, and accepts optional `notebook`, `keyword`, and `sourceFilter`. Each actual reference block appears once, keyed by its first matching inline reference with whitespace trimmed. Empty anchors sort last in either direction; ties use source-document ID, document order, then block ID. The first request returns an opaque snapshot token and at most 50 metadata entries. Subsequent requests reuse `snapshot` and `offset`; offsets are clamped to an existing page boundary. Optional `anchorID` locates the page containing the previous reading position. Snapshot ordering remains fixed while content changes; refreshing without a token incorporates edits. Expired or mismatched tokens, removed source documents, and removed or moved page entries return `expired: true`. The cache retains at most 16 snapshots for five minutes within a total 64 MiB metadata budget, stores no rendered bodies, and is cleared for a notebook when it locks.
+
+`/api/ref/getGlobalBacklinkContexts` takes the same query, its required `snapshot`, and up to 20 block `ids` from that snapshot. It renders independent editable blocks and preserves breadcrumb and attribute-view data. Both endpoints recheck source access before returning metadata or bodies and retain encrypted-notebook request leases. Published readers cannot access encrypted notebooks. The frontend loads 50 entries per page, retains a five-page window plus pages containing active editing sessions, and lazily mounts at most 16 editors. Recycling waits for pending transactions and preserves active composition, focus, drag, and attribute-view editing. Automatic refresh waits for editing to end and restores the visible block. The setting `backlinkGlobalSort` selects grouped mode (`0`, default) or global anchor order (`1`/`2`). `/api/ref/getBacklink2` accepts optional `includeBacklinks` (default `true`); `false` returns an empty backlink list and zero backlink count while preserving mentions, avoiding duplicate group loading. Existing callers and document-local `blockSort` keep their defaults.
+
+`TestGlobalBacklink*`, `TestAPIContractGlobalBacklink`, `TestBacklinkAnchorSortContext`, and `TestBacklink2OptionalMentions` cover cross-document pagination, first-reference selection, snapshot stability after edits, reading-position lookup, ordinary and encrypted reads, source permissions, expiration, cache bounds, HTTP response contracts, and mention compatibility. They run in the full kernel CI command below; run the affected subset with `go test -tags "fts5 sqlcipher" ./model ./api ./apicontract/... -run 'Test(GlobalBacklink|Backlink|APIContractGlobalBacklink|APIContractBack|APIContractSetting|PublishReaderBack|PublishReaderSearchAndBacklink|RouteCoverage)' -count=1`. Frontend regression files `globalBacklinkPaging.test.ts`, `globalBacklinkList.test.js`, and `backlinkSort.test.js` run in the existing full frontend CI selection and cover window bounds, stale responses, pending edits, and mode switching.
+
## File and streaming protocols
`RawSSEOptions` and `RawWebSocketOptions` declare byte-oriented broadcast protocols. Use `ValidateRawSSEEvent` and `ValidateRawWebSocketFrame` to check their event and frame metadata independently; JSON event and RPC message declarations retain their existing validation. Raw WebSocket failures are written by the upgrader rather than `RejectWebSocket`.
diff --git a/docs/API-CONTRACTS.zh-CN.md b/docs/API-CONTRACTS.zh-CN.md
index d00d91a056..a0eafdfeb1 100644
--- a/docs/API-CONTRACTS.zh-CN.md
+++ b/docs/API-CONTRACTS.zh-CN.md
@@ -118,6 +118,12 @@ SQL 查询契约保留成功信封顶层的 `limit` 和 `truncated`。`SuccessSQ
`DirectJSONOutput` 保留直接返回 JSON 对象或数组的独立协议,不添加内核信封,此类载荷使用 `SuccessDirectJSON` 返回。支持通知空响应的端点显式声明 `NoContent` 并返回 `SuccessNoContent`;HTTP 校验要求状态码为 204 且响应体为空。鉴权和只读错误仍保留内核错误信封。生成声明记录直接输出模式及可选的空响应支持。
+全局反链接口使用独立的平铺列表。`/api/ref/getGlobalBacklinks` 要求提供 `id`、`sort`(`1` 自然升序、`2` 自然降序)和 `containChildren`,支持可选的 `notebook`、`keyword` 和 `sourceFilter`。每个实际引用块只出现一次,取其首个匹配行内引用的锚文本并去除首尾空白;空锚文本在两个方向中均置后,相同锚文本按来源文档 ID、正文位置和块 ID 排列。首次请求返回不透明的快照令牌及最多 50 条元数据,后续请求复用 `snapshot` 和 `offset`,偏移量限制在已有页的边界。可选的 `anchorID` 用于定位原阅读位置所在页。正文变化期间快照顺序保持不变,不带令牌刷新时才纳入编辑结果。令牌过期、查询不匹配、来源文档消失或当前页条目删除、移动时返回 `expired: true`。缓存最多保留 16 份快照,期限为 5 分钟,总元数据预算为 64 MiB,不缓存正文;笔记本锁定时清除对应快照。
+
+`/api/ref/getGlobalBacklinkContexts` 使用相同查询、必需的 `snapshot` 和最多 20 个属于该快照的块 `ids`,返回可独立编辑的块正文,并保留面包屑和数据库引用信息。两个接口在返回元数据或正文前重新检查来源权限,保留加密笔记本请求租约;发布阅读者不能读取加密笔记本。前端每页加载 50 条,保留视口附近 5 页及正在编辑的页,最多按需创建 16 个编辑器。回收等待未完成事务,保留输入法组合、焦点、拖动和数据库编辑会话。自动刷新等待编辑结束并恢复可见块的位置。配置 `backlinkGlobalSort` 的 `0`(默认)表示文档分组,`1`、`2` 表示全局锚文本升降序。`/api/ref/getBacklink2` 新增可选的 `includeBacklinks`(默认 `true`);设为 `false` 时返回空反链列表及零反链计数,保留提及行为,避免重复加载文档分组。已有调用方和文档内 `blockSort` 的默认行为保持不变。
+
+`TestGlobalBacklink*`、`TestAPIContractGlobalBacklink`、`TestBacklinkAnchorSortContext` 和 `TestBacklink2OptionalMentions` 覆盖跨文档分页、首个引用取值、编辑后的快照稳定性、阅读定位、普通和加密读取、来源权限、过期、缓存上限、实际 HTTP 响应契约及提及兼容性。它们包含在下方内核全量 CI 命令中,可单独运行 `go test -tags "fts5 sqlcipher" ./model ./api ./apicontract/... -run 'Test(GlobalBacklink|Backlink|APIContractGlobalBacklink|APIContractBack|APIContractSetting|PublishReaderBack|PublishReaderSearchAndBacklink|RouteCoverage)' -count=1`。前端的 `globalBacklinkPaging.test.ts`、`globalBacklinkList.test.js` 和 `backlinkSort.test.js` 已由现有全量 CI 自动发现,覆盖页窗口上限、迟到响应、待提交编辑和模式切换。
+
## 文件与流式协议
`RawSSEOptions` 和 `RawWebSocketOptions` 声明以字节为载荷的广播协议,通过 `ValidateRawSSEEvent` 和 `ValidateRawWebSocketFrame` 单独校验事件及帧元数据;JSON 事件与 RPC 消息保留各自既有校验。原始 WebSocket 的错误由升级器写出,不使用 `RejectWebSocket`。
diff --git a/kernel/api/contract_ref_global_test.go b/kernel/api/contract_ref_global_test.go
new file mode 100644
index 0000000000..0d8fcb5223
--- /dev/null
+++ b/kernel/api/contract_ref_global_test.go
@@ -0,0 +1,69 @@
+package api
+
+import (
+ "encoding/json"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestAPIContractGlobalBacklink(t *testing.T) {
+ previousConf, previousData := model.Conf, util.DataDir
+ model.Conf, util.DataDir = model.NewAppConf(), t.TempDir()
+ model.Conf.Editor = conf.NewEditor()
+ t.Cleanup(func() { model.Conf, util.DataDir = previousConf, previousData })
+ const boxID = "20260726000003-encrypt"
+ boxConf := conf.NewBoxConf()
+ boxConf.Encrypted = true
+ if err := (&model.Box{ID: boxID}).SaveConf(boxConf); err != nil {
+ t.Fatal(err)
+ }
+ for _, entry := range []struct {
+ path string
+ handler gin.HandlerFunc
+ extra string
+ }{
+ {"/api/ref/getGlobalBacklinks", getGlobalBacklinks, ``},
+ {"/api/ref/getGlobalBacklinkContexts", getGlobalBacklinkContexts, `,"snapshot":"missing","ids":[]`},
+ } {
+ t.Run(entry.path, func(t *testing.T) {
+ engine := gin.New()
+ engine.Use(func(c *gin.Context) { c.Set(model.RoleContextKey, model.RoleReader) })
+ engine.POST(entry.path, entry.handler)
+ for _, body := range []string{`{}`, `{"id":"invalid","sort":1,"containChildren":false` + entry.extra + `}`, `{"id":"20260917165208-18eulw4","sort":1,"containChildren":false,"notebook":"` + boxID + `"` + entry.extra + `}`} {
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", entry.path, strings.NewReader(body)))
+ requireAPIContract(t, "POST", entry.path, recorder)
+ var response struct {
+ Code int `json:"code"`
+ Data json.RawMessage `json:"data"`
+ }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code == 0 || string(response.Data) != "null" {
+ t.Fatalf("invalid/published encrypted request exposed data: %s %v", recorder.Body.String(), err)
+ }
+ }
+ engine = gin.New()
+ engine.Use(func(c *gin.Context) { c.Set(model.RoleContextKey, model.RoleAdministrator) })
+ engine.POST(entry.path, entry.handler)
+ body := `{"id":"20260917165208-18eulw4","sort":1,"containChildren":false,"snapshot":"expired","ids":[]}`
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", entry.path, strings.NewReader(body)))
+ requireAPIContract(t, "POST", entry.path, recorder)
+ var response struct {
+ Code int `json:"code"`
+ Data struct {
+ Expired bool `json:"expired"`
+ Items []json.RawMessage `json:"items"`
+ } `json:"data"`
+ }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != 0 || !response.Data.Expired || response.Data.Items == nil {
+ t.Fatalf("expired success response: %s %v", recorder.Body.String(), err)
+ }
+ })
+ }
+}
diff --git a/kernel/api/ref.go b/kernel/api/ref.go
index 6e056714c3..639a1ec331 100644
--- a/kernel/api/ref.go
+++ b/kernel/api/ref.go
@@ -192,6 +192,7 @@ var getBacklink2 = contractHandler(apicontract.GetBacklink2, func(c *gin.Context
if request.IncludeMentions != nil {
includeMentions = *request.IncludeMentions
}
+ includeBacklinks := request.IncludeBacklinks == nil || *request.IncludeBacklinks
sort := util.SortModeUpdatedDESC
if request.Sort != nil {
sort, _ = strconv.Atoi(*request.Sort)
@@ -240,9 +241,9 @@ var getBacklink2 = contractHandler(apicontract.GetBacklink2, func(c *gin.Context
return apicontract.Failure[apicontract.BacklinkListData](1, err.Error())
}
if notebook != "" && model.IsEncryptedBox(notebook) {
- boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword, sort, mentionSort, containChildren, notebook, sourceFilter, includeMentions)
+ boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword, sort, mentionSort, containChildren, notebook, sourceFilter, includeMentions, includeBacklinks)
} else {
- boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword, sort, mentionSort, containChildren, "", sourceFilter, includeMentions)
+ boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword, sort, mentionSort, containChildren, "", sourceFilter, includeMentions, includeBacklinks)
}
}
if model.IsReadOnlyRoleContext(c) {
diff --git a/kernel/api/ref_global.go b/kernel/api/ref_global.go
new file mode 100644
index 0000000000..631a6a981c
--- /dev/null
+++ b/kernel/api/ref_global.go
@@ -0,0 +1,58 @@
+package api
+
+import (
+ "fmt"
+
+ "github.com/88250/lute/ast"
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+ "github.com/siyuan-note/siyuan/kernel/model"
+)
+
+func globalBacklinkQuery(c *gin.Context, request apicontract.GlobalBacklinkQuery) (model.GlobalBacklinkQuery, error) {
+ query := model.GlobalBacklinkQuery{ID: request.ID, Notebook: request.Notebook, Keyword: request.Keyword, Sort: request.Sort, ContainChildren: request.ContainChildren, SourceFilter: backlinkSourceFilterModel(request.SourceFilter)}
+ if !ast.IsNodeIDPattern(query.ID) || query.Sort != 1 && query.Sort != 2 {
+ return query, fmt.Errorf("invalid backlink query")
+ }
+ if isEncryptedNotebookDeniedForPublish(c, query.Notebook) || !isBacklinkDocAccessible(c, query.ID) {
+ return query, fmt.Errorf("backlink access denied")
+ }
+ if !model.IsEncryptedBox(query.Notebook) {
+ query.Notebook = ""
+ }
+ if err := holdEncryptedBoxRequest(c, query.Notebook); err != nil {
+ return query, err
+ }
+ return query, nil
+}
+
+var getGlobalBacklinks = contractHandler(apicontract.GetGlobalBacklinks, func(c *gin.Context, request apicontract.GlobalBacklinkListRequest) apicontract.Response[apicontract.GlobalBacklinkListData] {
+ query, err := globalBacklinkQuery(c, request.GlobalBacklinkQuery)
+ if err != nil {
+ return apicontract.Failure[apicontract.GlobalBacklinkListData](1, err.Error())
+ }
+ token, items, total, start, expired, err := model.GetGlobalBacklinks(query, request.Snapshot, request.Offset, request.AnchorID, func(id string) bool { return isBacklinkDocAccessible(c, id) })
+ if err != nil {
+ return apicontract.Failure[apicontract.GlobalBacklinkListData](1, err.Error())
+ }
+ ret := apicontract.GlobalBacklinkListData{Snapshot: token, Expired: expired, Total: total, Offset: start, Items: []*apicontract.GlobalBacklinkItem{}}
+ for _, item := range items {
+ ret.Items = append(ret.Items, &apicontract.GlobalBacklinkItem{ID: item.ID, RootID: item.RootID, Box: item.Box, HPath: item.HPath, Anchor: item.Anchor})
+ }
+ return apicontract.Success(ret)
+})
+
+var getGlobalBacklinkContexts = contractHandler(apicontract.GetGlobalBacklinkContexts, func(c *gin.Context, request apicontract.GlobalBacklinkContextRequest) apicontract.Response[apicontract.GlobalBacklinkContextData] {
+ query, err := globalBacklinkQuery(c, request.GlobalBacklinkQuery)
+ if err != nil {
+ return apicontract.Failure[apicontract.GlobalBacklinkContextData](1, err.Error())
+ }
+ if len(request.IDs) > 20 {
+ return apicontract.Failure[apicontract.GlobalBacklinkContextData](-1, "too many backlink contexts")
+ }
+ items, expired, err := model.GetGlobalBacklinkContexts(query, request.Snapshot, request.IDs, func(id string) bool { return isBacklinkDocAccessible(c, id) })
+ if err != nil {
+ return apicontract.Failure[apicontract.GlobalBacklinkContextData](1, err.Error())
+ }
+ return apicontract.Success(apicontract.GlobalBacklinkContextData{Expired: expired, Items: backlinkContextContracts(newBacklinkContextResponses(items))})
+})
diff --git a/kernel/api/router.go b/kernel/api/router.go
index 32cece964c..62ba60ad70 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -330,6 +330,8 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/ref/refreshBacklink", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, refreshBacklink)
ginServer.Handle("POST", "/api/ref/getBacklink2", model.CheckAuth, getBacklink2)
+ ginServer.Handle("POST", "/api/ref/getGlobalBacklinks", model.CheckAuth, getGlobalBacklinks)
+ ginServer.Handle("POST", "/api/ref/getGlobalBacklinkContexts", model.CheckAuth, getGlobalBacklinkContexts)
ginServer.Handle("POST", "/api/ref/getBacklinkDoc", model.CheckAuth, getBacklinkDoc)
ginServer.Handle("POST", "/api/ref/getBackmentionDoc", model.CheckAuth, getBackmentionDoc)
diff --git a/kernel/api/setting_contract.go b/kernel/api/setting_contract.go
index a303852324..3afeb2d9ad 100644
--- a/kernel/api/setting_contract.go
+++ b/kernel/api/setting_contract.go
@@ -376,6 +376,7 @@ func settingEditorPayload(value *conf.Editor) *apicontract.SettingEditor {
result.BacklinkHideReference = value.BacklinkHideReference
result.BacklinkShowBottom = value.BacklinkShowBottom
result.BacklinkSort = value.BacklinkSort
+ result.BacklinkGlobalSort = value.BacklinkGlobalSort
result.BacklinkBlockSort = value.BacklinkBlockSort
result.BackmentionSort = value.BackmentionSort
result.HeadingNumber = value.HeadingNumber
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index 0421ee15ee..aceb9a5b3b 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -547,6 +547,8 @@ var GetBackmentionDoc = define[BackmentionDocumentRequest, BacklinkContextData](
var GetBacklinkDoc = define[BacklinkDocumentRequest, BacklinkContextData]("getBacklinkDoc", "/api/ref/getBacklinkDoc", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")
var GetBacklink2 = define[BacklinkListRequest, BacklinkListData]("getBacklink2", "/api/ref/getBacklink2", JSONBody, ResponseOptions{AdditionalCodes: []int{1}, DataOnError: true}, "POST")
+var GetGlobalBacklinks = define[GlobalBacklinkListRequest, GlobalBacklinkListData]("getGlobalBacklinks", "/api/ref/getGlobalBacklinks", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")
+var GetGlobalBacklinkContexts = define[GlobalBacklinkContextRequest, GlobalBacklinkContextData]("getGlobalBacklinkContexts", "/api/ref/getGlobalBacklinkContexts", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")
var ContinueImportSY = define[ContinueImportSYRequest, ImportDocumentData]("continueImportSY", "/api/import/continueImportSY", JSONBody, ResponseOptions{}, "POST")
diff --git a/kernel/apicontract/ref_global.go b/kernel/apicontract/ref_global.go
new file mode 100644
index 0000000000..9ff0864216
--- /dev/null
+++ b/kernel/apicontract/ref_global.go
@@ -0,0 +1,45 @@
+package apicontract
+
+// 全局反链的分页快照仅固定条目次序,正文始终通过独立请求读取。
+type GlobalBacklinkQuery struct {
+ ID string `json:"id"`
+ Notebook string `json:"notebook" api:"optional"`
+ Keyword string `json:"keyword" api:"optional"`
+ Sort int `json:"sort"` // 1 自然升序,2 自然降序
+ ContainChildren bool `json:"containChildren"`
+ SourceFilter *BacklinkSourceFilter `json:"sourceFilter" api:"optional"`
+}
+
+type GlobalBacklinkListRequest struct {
+ GlobalBacklinkQuery
+ Snapshot string `json:"snapshot" api:"optional"`
+ Offset int `json:"offset" api:"optional"`
+ AnchorID string `json:"anchorID" api:"optional"`
+}
+
+type GlobalBacklinkItem struct {
+ ID string `json:"id"`
+ RootID string `json:"rootID"`
+ Box string `json:"box"`
+ HPath string `json:"hPath"`
+ Anchor string `json:"anchor"`
+}
+
+type GlobalBacklinkListData struct {
+ Snapshot string `json:"snapshot"`
+ Expired bool `json:"expired"`
+ Offset int `json:"offset"`
+ Total int `json:"total"`
+ Items []*GlobalBacklinkItem `json:"items"`
+}
+
+type GlobalBacklinkContextRequest struct {
+ GlobalBacklinkQuery
+ Snapshot string `json:"snapshot"`
+ IDs []string `json:"ids"`
+}
+
+type GlobalBacklinkContextData struct {
+ Expired bool `json:"expired"`
+ Items []*BacklinkContext `json:"items"`
+}
diff --git a/kernel/apicontract/ref_global_test.go b/kernel/apicontract/ref_global_test.go
new file mode 100644
index 0000000000..deede6f254
--- /dev/null
+++ b/kernel/apicontract/ref_global_test.go
@@ -0,0 +1,25 @@
+package apicontract
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestGlobalBacklinkContract(t *testing.T) {
+ const base = `"id":"20260917165208-18eulw4","sort":1,"containChildren":false`
+ request, err := GetGlobalBacklinks.Decode(strings.NewReader(`{` + base + `}`))
+ if err != nil || request.Offset != 0 || request.Snapshot != "" {
+ t.Fatalf("defaults: %+v %v", request, err)
+ }
+ for _, body := range []string{`{}`, `{` + base + `,"offset":"50"}`, `{` + base + `,"snapshot":null}`} {
+ if _, err = GetGlobalBacklinks.Decode(strings.NewReader(body)); err == nil {
+ t.Fatalf("invalid request accepted: %s", body)
+ }
+ }
+ if _, err = GetGlobalBacklinkContexts.Decode(strings.NewReader(`{` + base + `,"snapshot":"token","ids":["block"]}`)); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = GetGlobalBacklinkContexts.Decode(strings.NewReader(`{` + base + `,"snapshot":"token","ids":[null]}`)); err == nil {
+ t.Fatal("null ID accepted")
+ }
+}
diff --git a/kernel/apicontract/ref_list.go b/kernel/apicontract/ref_list.go
index 9a4dbb8483..3fab226579 100644
--- a/kernel/apicontract/ref_list.go
+++ b/kernel/apicontract/ref_list.go
@@ -13,6 +13,7 @@ type BacklinkListRequest struct {
KnownRevision string `json:"knownRevision" api:"optional,nullable,ignoretype"`
Notebook string `json:"notebook" api:"optional,nullable,ignoretype"`
IncludeMentions *bool `json:"includeMentions" api:"optional"`
+ IncludeBacklinks *bool `json:"includeBacklinks" api:"optional"`
Sort *string `json:"sort" api:"optional"`
MentionSort *string `json:"mSort" api:"optional"`
ContainChildren *bool `json:"containChildren" api:"optional"`
@@ -49,6 +50,13 @@ func decodeBacklinkListRequest(reader io.Reader) (request BacklinkListRequest, e
if raw := fields["includeMentions"]; !bytes.Equal(raw, []byte("null")) && json.Unmarshal(raw, &includeMentions) == nil {
request.IncludeMentions = &includeMentions
}
+ if _, exists := fields["includeBacklinks"]; exists {
+ value, decodeErr := legacyField[bool](fields, "includeBacklinks", "Bool", true)
+ if decodeErr != nil {
+ return request, decodeErr
+ }
+ request.IncludeBacklinks = &value
+ }
for _, field := range []struct {
name string
target **string
diff --git a/kernel/apicontract/ref_list_test.go b/kernel/apicontract/ref_list_test.go
index 0652f09c89..d9bdce291f 100644
--- a/kernel/apicontract/ref_list_test.go
+++ b/kernel/apicontract/ref_list_test.go
@@ -6,6 +6,16 @@ import (
)
func TestBacklinkListRequestCompatibility(t *testing.T) {
+ for _, raw := range []string{`true`, `false`, `null`, `"false"`} {
+ request, err := GetBacklink2.Decode(strings.NewReader(`{"id":"id","k":"","mk":"","includeBacklinks":` + raw + `}`))
+ if raw == "true" || raw == "false" {
+ if err != nil || request.IncludeBacklinks == nil || *request.IncludeBacklinks != (raw == "true") {
+ t.Fatalf("backlink flag: %+v %v", request, err)
+ }
+ } else if err == nil {
+ t.Fatalf("invalid backlink flag accepted: %s", raw)
+ }
+ }
for _, body := range []string{`{}`, `{"id":null,"k":false,"sort":false,"containChildren":null}`} {
request, err := decodeBacklinkListRequest(strings.NewReader(body))
if err != nil || request.ID != nil {
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index d0669cfbf3..a270c06cf1 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -14109,6 +14109,16 @@
}
]
},
+ "includeBacklinks": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"includeMentions": {
"anyOf": [
{
@@ -25667,6 +25677,204 @@
],
"additionalProperties": false
},
+ "GlobalBacklinkContextData": {
+ "type": "object",
+ "properties": {
+ "expired": {
+ "type": "boolean"
+ },
+ "items": {
+ "anyOf": [
+ {
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/BacklinkContext"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "required": [
+ "expired",
+ "items"
+ ],
+ "additionalProperties": false
+ },
+ "GlobalBacklinkContextRequestInput": {
+ "type": "object",
+ "properties": {
+ "containChildren": {
+ "type": "boolean"
+ },
+ "id": {
+ "type": "string"
+ },
+ "ids": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "keyword": {
+ "type": "string"
+ },
+ "notebook": {
+ "type": "string"
+ },
+ "snapshot": {
+ "type": "string"
+ },
+ "sort": {
+ "type": "integer"
+ },
+ "sourceFilter": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/BacklinkSourceFilterInput"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "required": [
+ "containChildren",
+ "id",
+ "ids",
+ "snapshot",
+ "sort"
+ ],
+ "additionalProperties": false
+ },
+ "GlobalBacklinkItem": {
+ "type": "object",
+ "properties": {
+ "anchor": {
+ "type": "string"
+ },
+ "box": {
+ "type": "string"
+ },
+ "hPath": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "rootID": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "anchor",
+ "box",
+ "hPath",
+ "id",
+ "rootID"
+ ],
+ "additionalProperties": false
+ },
+ "GlobalBacklinkListData": {
+ "type": "object",
+ "properties": {
+ "expired": {
+ "type": "boolean"
+ },
+ "items": {
+ "anyOf": [
+ {
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/GlobalBacklinkItem"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "offset": {
+ "type": "integer"
+ },
+ "snapshot": {
+ "type": "string"
+ },
+ "total": {
+ "type": "integer"
+ }
+ },
+ "required": [
+ "expired",
+ "items",
+ "offset",
+ "snapshot",
+ "total"
+ ],
+ "additionalProperties": false
+ },
+ "GlobalBacklinkListRequestInput": {
+ "type": "object",
+ "properties": {
+ "anchorID": {
+ "type": "string"
+ },
+ "containChildren": {
+ "type": "boolean"
+ },
+ "id": {
+ "type": "string"
+ },
+ "keyword": {
+ "type": "string"
+ },
+ "notebook": {
+ "type": "string"
+ },
+ "offset": {
+ "type": "integer"
+ },
+ "snapshot": {
+ "type": "string"
+ },
+ "sort": {
+ "type": "integer"
+ },
+ "sourceFilter": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/BacklinkSourceFilterInput"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "required": [
+ "containChildren",
+ "id",
+ "sort"
+ ],
+ "additionalProperties": false
+ },
"GlobalGraphConf": {
"type": "object",
"properties": {
@@ -36585,6 +36793,16 @@
}
]
},
+ "backlinkGlobalSort": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"backlinkHideReference": {
"anyOf": [
{
@@ -40033,6 +40251,9 @@
"backlinkExpandCount": {
"type": "integer"
},
+ "backlinkGlobalSort": {
+ "type": "integer"
+ },
"backlinkHideReference": {
"type": "boolean"
},
@@ -40319,6 +40540,7 @@
"backlinkBlockSort",
"backlinkContainChildren",
"backlinkExpandCount",
+ "backlinkGlobalSort",
"backlinkHideReference",
"backlinkMentionExclude",
"backlinkShowBottom",
@@ -139918,6 +140140,158 @@
]
}
},
+ {
+ "method": "POST",
+ "path": "/api/ref/getGlobalBacklinkContexts",
+ "handler": "getGlobalBacklinkContexts",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/GlobalBacklinkContextRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "$ref": "#/$defs/GlobalBacklinkContextData"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1,
+ 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/ref/getGlobalBacklinks",
+ "handler": "getGlobalBacklinks",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/GlobalBacklinkListRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "$ref": "#/$defs/GlobalBacklinkListData"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1,
+ 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/ref/refreshBacklink",
diff --git a/kernel/apicontract/setting.go b/kernel/apicontract/setting.go
index 45fad2ac55..a4b661fba1 100644
--- a/kernel/apicontract/setting.go
+++ b/kernel/apicontract/setting.go
@@ -220,6 +220,7 @@ type SettingEditor struct {
BacklinkHideReference bool `json:"backlinkHideReference" api:"optional,nullable"`
BacklinkShowBottom bool `json:"backlinkShowBottom" api:"optional,nullable"`
BacklinkSort *int `json:"backlinkSort" api:"optional,nullable"`
+ BacklinkGlobalSort int `json:"backlinkGlobalSort" api:"optional,nullable"`
BacklinkBlockSort int `json:"backlinkBlockSort" api:"optional,nullable"`
BackmentionSort *int `json:"backmentionSort" api:"optional,nullable"`
HeadingNumber bool `json:"headingNumber" api:"optional,nullable"`
diff --git a/kernel/conf/editor.go b/kernel/conf/editor.go
index 5300e5fcd7..7121197ce7 100644
--- a/kernel/conf/editor.go
+++ b/kernel/conf/editor.go
@@ -98,6 +98,7 @@ type Editor struct {
BacklinkHideReference bool `json:"backlinkHideReference"` // 反链面板是否隐藏传递型纯引用块
BacklinkShowBottom bool `json:"backlinkShowBottom"` // 是否在文档底部显示反向链接
BacklinkSort *int `json:"backlinkSort"` // 反向链接排序方式
+ BacklinkGlobalSort int `json:"backlinkGlobalSort"` // 0 文档分组,1 全局锚文本升序,2 全局锚文本降序
BacklinkBlockSort int `json:"backlinkBlockSort"` // 文档内引用排序:0 正文顺序,1 锚文本升序,2 锚文本降序
BackmentionSort *int `json:"backmentionSort"` // 反链提及排序方式
HeadingNumber bool `json:"headingNumber"` // 是否显示标题编号
diff --git a/kernel/model/backlink.go b/kernel/model/backlink.go
index b4d5f01a68..a6248063e7 100644
--- a/kernel/model/backlink.go
+++ b/kernel/model/backlink.go
@@ -602,11 +602,11 @@ func GetBacklink2InBox(id, keyword, mentionKeyword string, sortMode, mentionSort
}
func GetBacklink2InBoxWithFilter(id, keyword, mentionKeyword string, sortMode, mentionSortMode int, containChildren bool, boxID string, sourceFilter *BacklinkSourceFilter) (boxIDOut string, backlinks, backmentions []*Path, linkRefsCount, mentionsCount int) {
- return GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword, sortMode, mentionSortMode, containChildren, boxID, sourceFilter, true)
+ return GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword, sortMode, mentionSortMode, containChildren, boxID, sourceFilter, true, true)
}
-// GetBacklink2InBoxWithOptions 查询反链文档列表,并按需搜索提及。
-func GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword string, sortMode, mentionSortMode int, containChildren bool, boxID string, sourceFilter *BacklinkSourceFilter, includeMentions bool) (boxIDOut string, backlinks, backmentions []*Path, linkRefsCount, mentionsCount int) {
+// GetBacklink2InBoxWithOptions 按需查询反链文档分组与提及列表。
+func GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword string, sortMode, mentionSortMode int, containChildren bool, boxID string, sourceFilter *BacklinkSourceFilter, includeMentions, includeBacklinks bool) (boxIDOut string, backlinks, backmentions []*Path, linkRefsCount, mentionsCount int) {
keyword = strings.TrimSpace(keyword)
var keywords []string
if "" != keyword {
@@ -621,19 +621,26 @@ func GetBacklink2InBoxWithOptions(id, keyword, mentionKeyword string, sortMode,
}
rootID := sqlBlock.RootID
boxIDOut = sqlBlock.Box
+ if !includeMentions && !includeBacklinks {
+ return
+ }
refs := sql.QueryRefsByDefIDInBox(id, containChildren, boxID)
refs = removeDuplicatedRefs(refs)
linkRefs, linkRefsCount, excludeBacklinkIDs, _ := buildLinkRefsInBox(rootID, refs, keywords, boxID)
- filteredLinkRefs := filterBacklinkSourcesInBox(linkRefs, rootID, boxID, sourceFilter)
- if nil != NormalizeBacklinkSourceFilter(sourceFilter) {
- linkRefsCount = len(filteredLinkRefs)
- }
- tmpBacklinks := toFlatTree(filteredLinkRefs, 0, "backlink", nil)
- for _, l := range tmpBacklinks {
- l.Blocks = nil
- backlinks = append(backlinks, l)
+ if includeBacklinks {
+ filteredLinkRefs := filterBacklinkSourcesInBox(linkRefs, rootID, boxID, sourceFilter)
+ if nil != NormalizeBacklinkSourceFilter(sourceFilter) {
+ linkRefsCount = len(filteredLinkRefs)
+ }
+ tmpBacklinks := toFlatTree(filteredLinkRefs, 0, "backlink", nil)
+ for _, l := range tmpBacklinks {
+ l.Blocks = nil
+ backlinks = append(backlinks, l)
+ }
+ } else {
+ linkRefsCount = 0
}
sort.Slice(backlinks, func(i, j int) bool {
diff --git a/kernel/model/backlink_global.go b/kernel/model/backlink_global.go
new file mode 100644
index 0000000000..92c73c55f1
--- /dev/null
+++ b/kernel/model/backlink_global.go
@@ -0,0 +1,328 @@
+package model
+
+import (
+ "crypto/rand"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/parse"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+const GlobalBacklinkPageSize = 50
+const globalBacklinkSnapshotLimit = 16
+const globalBacklinkSnapshotTTL = 5 * time.Minute
+
+type GlobalBacklinkQuery struct {
+ ID, Notebook, Keyword string
+ Sort int
+ ContainChildren bool
+ SourceFilter *BacklinkSourceFilter
+}
+
+type GlobalBacklinkItem struct {
+ ID, RootID, Box, HPath, Anchor string
+ order int
+}
+
+// 快照只保存排序所需的轻量元数据,不保存正文;锁定笔记本时立即清除。
+type globalBacklinkLocation struct{ ID, RootID, Box, Anchor string }
+type globalBacklinkSnapshot struct {
+ key string
+ box string
+ created time.Time
+ items []globalBacklinkLocation
+ bytes int
+}
+
+var globalBacklinkSnapshots = struct {
+ sync.Mutex
+ values map[string]*globalBacklinkSnapshot
+}{values: map[string]*globalBacklinkSnapshot{}}
+
+func ClearGlobalBacklinkSnapshots(boxID string) {
+ globalBacklinkSnapshots.Lock()
+ defer globalBacklinkSnapshots.Unlock()
+ for token, snapshot := range globalBacklinkSnapshots.values {
+ if snapshot.box == boxID {
+ delete(globalBacklinkSnapshots.values, token)
+ continue
+ }
+ for _, item := range snapshot.items {
+ if item.Box == boxID {
+ delete(globalBacklinkSnapshots.values, token)
+ break
+ }
+ }
+ }
+}
+
+func globalBacklinkQueryKey(query GlobalBacklinkQuery) string {
+ query.Keyword = strings.TrimSpace(query.Keyword)
+ query.SourceFilter = NormalizeBacklinkSourceFilter(query.SourceFilter)
+ data, _ := json.Marshal(query)
+ return util.DataDir + ":" + string(data)
+}
+
+func globalBacklinkSnapshotGet(query GlobalBacklinkQuery, token string, accessible func(string) bool) *globalBacklinkSnapshot {
+ globalBacklinkSnapshots.Lock()
+ snapshot := globalBacklinkSnapshots.values[token]
+ if snapshot != nil && time.Since(snapshot.created) > globalBacklinkSnapshotTTL {
+ delete(globalBacklinkSnapshots.values, token)
+ snapshot = nil
+ }
+ globalBacklinkSnapshots.Unlock()
+ if snapshot == nil || snapshot.key != globalBacklinkQueryKey(query) {
+ return nil
+ }
+ checked := map[string]bool{}
+ for _, item := range snapshot.items {
+ if !checked[item.RootID] {
+ if !accessible(item.RootID) || treenode.GetBlockTreeInBox(item.RootID, query.Notebook) == nil {
+ return nil
+ }
+ checked[item.RootID] = true
+ }
+ }
+ return snapshot
+}
+
+func globalBacklinkSnapshotPut(query GlobalBacklinkQuery, items []*GlobalBacklinkItem) (string, *globalBacklinkSnapshot, error) {
+ var random [24]byte
+ if _, err := rand.Read(random[:]); err != nil {
+ panic(err)
+ }
+ token := hex.EncodeToString(random[:])
+ snapshot := &globalBacklinkSnapshot{key: globalBacklinkQueryKey(query), box: query.Notebook, created: time.Now()}
+ for _, item := range items {
+ snapshot.bytes += len(item.ID) + len(item.RootID) + len(item.Box) + len(item.Anchor) + 128
+ if snapshot.bytes > 64<<20 {
+ return "", nil, fmt.Errorf("backlink snapshot exceeds memory limit")
+ }
+ snapshot.items = append(snapshot.items, globalBacklinkLocation{item.ID, item.RootID, item.Box, item.Anchor})
+ }
+ globalBacklinkSnapshots.Lock()
+ defer globalBacklinkSnapshots.Unlock()
+ for key, value := range globalBacklinkSnapshots.values {
+ if time.Since(value.created) > globalBacklinkSnapshotTTL {
+ delete(globalBacklinkSnapshots.values, key)
+ }
+ }
+ for {
+ bytes := snapshot.bytes
+ for _, value := range globalBacklinkSnapshots.values {
+ bytes += value.bytes
+ }
+ if len(globalBacklinkSnapshots.values) < globalBacklinkSnapshotLimit && bytes <= 64<<20 {
+ break
+ }
+ oldest := ""
+ for key, value := range globalBacklinkSnapshots.values {
+ if oldest == "" || value.created.Before(globalBacklinkSnapshots.values[oldest].created) {
+ oldest = key
+ }
+ }
+ delete(globalBacklinkSnapshots.values, oldest)
+ }
+ globalBacklinkSnapshots.values[token] = snapshot
+ return token, snapshot, nil
+}
+
+// 同一引用块只产生一个条目,按正文遍历选择首个命中的行内引用。
+func globalBacklinkAnchor(node *ast.Node, targets map[string]bool) string {
+ text := ""
+ ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if !entering {
+ return ast.WalkContinue
+ }
+ if n != node && n.IsBlock() {
+ return ast.WalkSkipChildren
+ }
+ id, anchor, _ := treenode.GetBlockRef(n)
+ if id != "" && targets[id] {
+ text = strings.TrimSpace(anchor)
+ return ast.WalkStop
+ }
+ return ast.WalkContinue
+ })
+ return text
+}
+
+func collectGlobalBacklinks(query GlobalBacklinkQuery, accessible func(string) bool) ([]*GlobalBacklinkItem, error) {
+ definition := sql.GetBlockInBox(query.ID, query.Notebook)
+ if definition == nil {
+ return []*GlobalBacklinkItem{}, nil
+ }
+ refs := sql.QueryRefsByDefIDInBox(query.ID, query.ContainChildren, query.Notebook)
+ targets := map[string]map[string]bool{}
+ var ids []string
+ for _, ref := range refs {
+ if targets[ref.BlockID] == nil {
+ targets[ref.BlockID] = map[string]bool{}
+ ids = append(ids, ref.BlockID)
+ }
+ targets[ref.BlockID][ref.DefBlockID] = true
+ }
+ var blocks []*Block
+ for start := 0; start < len(ids); start += 512 {
+ for _, block := range sql.GetBlocksInBox(ids[start:min(start+512, len(ids))], query.Notebook) {
+ if block != nil && accessible(block.RootID) {
+ value := fromSQLBlock(block, "", 0)
+ if matchBacklinkKeyword(value, strings.Fields(query.Keyword)) {
+ blocks = append(blocks, value)
+ }
+ }
+ }
+ }
+ blocks = filterBacklinkSourcesInBox(blocks, definition.RootID, query.Notebook, query.SourceFilter)
+ byRoot := map[string]map[string]*Block{}
+ for _, block := range blocks {
+ if byRoot[block.RootID] == nil {
+ byRoot[block.RootID] = map[string]*Block{}
+ }
+ byRoot[block.RootID][block.ID] = block
+ }
+ items := []*GlobalBacklinkItem{}
+ for rootID, selected := range byRoot {
+ tree, err := loadTreeByBlockIDInBox(rootID, query.Notebook)
+ if err != nil {
+ return nil, err
+ }
+ order := 0
+ ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if !entering || !n.IsBlock() {
+ return ast.WalkContinue
+ }
+ order++
+ if block := selected[n.ID]; block != nil {
+ items = append(items, &GlobalBacklinkItem{ID: n.ID, RootID: rootID, Box: block.Box, HPath: block.HPath, Anchor: globalBacklinkAnchor(n, targets[n.ID]), order: order})
+ }
+ return ast.WalkContinue
+ })
+ }
+ sort.Slice(items, func(i, j int) bool {
+ a, b := items[i], items[j]
+ if a.Anchor == "" && b.Anchor != "" {
+ return false
+ }
+ if a.Anchor != "" && b.Anchor == "" {
+ return true
+ }
+ less, greater := util.NaturalCompare(a.Anchor, b.Anchor), util.NaturalCompare(b.Anchor, a.Anchor)
+ if less != greater {
+ if query.Sort == 2 {
+ return greater
+ }
+ return less
+ }
+ if a.RootID != b.RootID {
+ return a.RootID < b.RootID
+ }
+ if a.order != b.order {
+ return a.order < b.order
+ }
+ return a.ID < b.ID
+ })
+ return items, nil
+}
+
+func GetGlobalBacklinks(query GlobalBacklinkQuery, token string, offset int, anchorID string, accessible func(string) bool) (snapshotID string, items []*GlobalBacklinkItem, total, start int, expired bool, err error) {
+ items = []*GlobalBacklinkItem{}
+ var snapshot *globalBacklinkSnapshot
+ var initial []*GlobalBacklinkItem
+ if token == "" {
+ initial, err = collectGlobalBacklinks(query, accessible)
+ if err != nil {
+ return
+ }
+ token, snapshot, err = globalBacklinkSnapshotPut(query, initial)
+ if err != nil {
+ return
+ }
+ } else {
+ snapshot = globalBacklinkSnapshotGet(query, token, accessible)
+ if snapshot == nil {
+ expired = true
+ return
+ }
+ }
+ if anchorID != "" {
+ for i, item := range snapshot.items {
+ if item.ID == anchorID {
+ offset = i / GlobalBacklinkPageSize * GlobalBacklinkPageSize
+ break
+ }
+ }
+ }
+ total = len(snapshot.items)
+ start = min(max(offset, 0), max(total-1, 0)) / GlobalBacklinkPageSize * GlobalBacklinkPageSize
+ end := min(start+GlobalBacklinkPageSize, total)
+ snapshotID = token
+ if initial != nil {
+ items = initial[start:end]
+ return
+ }
+ for _, location := range snapshot.items[start:end] {
+ block := sql.GetBlockInBox(location.ID, query.Notebook)
+ if block == nil || block.RootID != location.RootID || block.Box != location.Box {
+ expired = true
+ items = []*GlobalBacklinkItem{}
+ return
+ }
+ items = append(items, &GlobalBacklinkItem{ID: location.ID, RootID: location.RootID, Box: location.Box, HPath: block.HPath, Anchor: location.Anchor})
+ }
+ return
+}
+
+func GetGlobalBacklinkContexts(query GlobalBacklinkQuery, token string, ids []string, accessible func(string) bool) (items []*Backlink, expired bool, err error) {
+ items = []*Backlink{}
+ snapshot := globalBacklinkSnapshotGet(query, token, accessible)
+ if snapshot == nil {
+ return items, true, nil
+ }
+ allowed := map[string]globalBacklinkLocation{}
+ for _, item := range snapshot.items {
+ allowed[item.ID] = item
+ }
+ trees := map[string]*parse.Tree{}
+ for _, id := range uniqueBacklinkStrings(ids) {
+ location, ok := allowed[id]
+ if !ok {
+ return nil, false, fmt.Errorf("block is outside backlink snapshot")
+ }
+ block := sql.GetBlockInBox(id, query.Notebook)
+ if block == nil || block.RootID != location.RootID || block.Box != location.Box {
+ return items, true, nil
+ }
+ tree := trees[location.RootID]
+ if tree == nil {
+ tree, err = loadTreeByBlockIDInBox(location.RootID, query.Notebook)
+ if err != nil {
+ return nil, false, err
+ }
+ trees[location.RootID] = tree
+ }
+ node := treenode.GetNodeInTree(tree, id)
+ if node == nil {
+ return items, true, nil
+ }
+ // 只渲染条目自身,父级通过面包屑按需展开,不将兄弟引用合并进当前条目。
+ nodes := []*ast.Node{node}
+ fillBlockRefCount(nodes, tree.Box)
+ item := &Backlink{ID: id, Type: node.Type.String(), node: node, Expand: true, BlockPaths: buildBlockBreadcrumb(node, nil, false), DOM: renderVisibleBlockDOMByNodes(nodes, util.NewLute())}
+ if node.Type == ast.NodeAttributeView {
+ refs := sql.QueryRefsByDefIDInBox(query.ID, query.ContainChildren, query.Notebook)
+ appendBacklinkAttributeViewTargets(item, nodes, backlinkAttributeViewTargets(tree, refs))
+ }
+ items = append(items, item)
+ }
+ return
+}
diff --git a/kernel/model/backlink_global_fts5_test.go b/kernel/model/backlink_global_fts5_test.go
new file mode 100644
index 0000000000..c544cd31c6
--- /dev/null
+++ b/kernel/model/backlink_global_fts5_test.go
@@ -0,0 +1,156 @@
+//go:build fts5
+
+package model
+
+import (
+ "fmt"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+)
+
+func TestGlobalBacklinkPagination(t *testing.T) {
+ fixture := setupStructureTransactionTest(t)
+ setupFoldTransactionDatabase(t, fixture)
+ Conf.Search = conf.NewSearch()
+ t.Cleanup(func() { ClearGlobalBacklinkSnapshots("") })
+ ids := map[int]string{}
+ for index, rootID := range []string{fixture.sourceID, fixture.targetID} {
+ tree, err := LoadTreeByBlockID(rootID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for tree.Root.FirstChild != nil {
+ tree.Root.FirstChild.Unlink()
+ }
+ for number := 120 - index; number > 0; number -= 2 {
+ id := ast.NewNodeID()
+ ids[number] = id
+ p := treenode.NewParagraph(id)
+ p.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "block-ref", TextMarkBlockRefID: fixture.sourceID, TextMarkBlockRefSubtype: "s", TextMarkTextContent: fmt.Sprintf("A%d", number)})
+ // 同块的第二个引用不能改变排序,也不能增加条目。
+ p.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "block-ref", TextMarkBlockRefID: fixture.sourceID, TextMarkBlockRefSubtype: "s", TextMarkTextContent: "A0"})
+ tree.Root.AppendChild(p)
+ }
+ if _, err = filesys.WriteTree(tree); err != nil {
+ t.Fatal(err)
+ }
+ treenode.UpsertBlockTree(tree)
+ sql.IndexTreeQueue(tree)
+ sql.UpdateRefsTreeQueue(tree)
+ }
+ sql.FlushQueue()
+ query := GlobalBacklinkQuery{ID: fixture.sourceID, Sort: 1}
+ allow := func(string) bool { return true }
+ token, first, total, start, expired, err := GetGlobalBacklinks(query, "", 0, "", allow)
+ if err != nil || expired || total != 120 || start != 0 || len(first) != 50 {
+ t.Fatalf("first page: %d %d %v %v", total, len(first), expired, err)
+ }
+ for offset := 0; offset < 120; offset += 50 {
+ _, items, count, page, expired, err := GetGlobalBacklinks(query, token, offset, "", allow)
+ if err != nil || expired || count != 120 || page != offset {
+ t.Fatalf("page %d: %v %v", offset, expired, err)
+ }
+ for i, item := range items {
+ if item.ID != ids[offset+i+1] || item.Anchor != fmt.Sprintf("A%d", offset+i+1) {
+ t.Fatalf("incorrect natural order at %d: %+v", offset+i, item)
+ }
+ }
+ }
+ _, _, _, start, expired, err = GetGlobalBacklinks(query, token, 0, ids[103], allow)
+ if err != nil || expired || start != 100 {
+ t.Fatalf("anchor lookup: %d %v %v", start, expired, err)
+ }
+ contexts, expired, err := GetGlobalBacklinkContexts(query, token, []string{ids[1], ids[2]}, allow)
+ if err != nil || expired || len(contexts) != 2 || contexts[0].ID != ids[1] || strings.Contains(contexts[0].DOM, `data-node-id="`+ids[3]+`"`) {
+ t.Fatalf("independent contexts: %+v %v %v", contexts, expired, err)
+ }
+ if _, _, err = GetGlobalBacklinkContexts(query, token, []string{fixture.targetID}, allow); err == nil {
+ t.Fatal("out-of-snapshot block accepted")
+ }
+ query.Sort = 2
+ if _, _, _, _, expired, _ = GetGlobalBacklinks(query, token, 50, "", allow); !expired {
+ t.Fatal("cursor reused with different sort")
+ }
+ _, items, _, _, _, err := GetGlobalBacklinks(query, "", 0, "", allow)
+ if err != nil || items[0].ID != ids[120] {
+ t.Fatalf("descending order: %v", err)
+ }
+ query.Sort = 1
+ tree, err := LoadTreeByBlockID(fixture.targetID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ treenode.GetNodeInTree(tree, ids[1]).FirstChild.TextMarkTextContent = "A1000"
+ if _, err = filesys.WriteTree(tree); err != nil {
+ t.Fatal(err)
+ }
+ treenode.UpsertBlockTree(tree)
+ sql.IndexTreeQueue(tree)
+ sql.UpdateRefsTreeQueue(tree)
+ sql.FlushQueue()
+ _, items, _, _, expired, err = GetGlobalBacklinks(query, token, 0, "", allow)
+ if err != nil || expired || items[0].ID != ids[1] || items[0].Anchor != "A1" {
+ t.Fatalf("editing changed the active snapshot: %+v %v %v", items, expired, err)
+ }
+ _, items, _, _, expired, err = GetGlobalBacklinks(query, "", 0, "", allow)
+ if err != nil || expired || items[0].ID != ids[2] {
+ t.Fatalf("refresh did not apply edited anchor: %+v %v %v", items, expired, err)
+ }
+ denySource := func(id string) bool { return id != fixture.sourceID }
+ if _, _, _, _, expired, _ = GetGlobalBacklinks(query, token, 50, "", denySource); !expired {
+ t.Fatal("revoked source accepted")
+ }
+ _, _, total, _, _, err = GetGlobalBacklinks(query, "", 0, "", denySource)
+ if err != nil || total != 60 {
+ t.Fatalf("permission filtered count: %d %v", total, err)
+ }
+ globalBacklinkSnapshots.Lock()
+ globalBacklinkSnapshots.values[token].created = time.Now().Add(-globalBacklinkSnapshotTTL - time.Second)
+ globalBacklinkSnapshots.Unlock()
+ if _, _, _, _, expired, _ = GetGlobalBacklinks(query, token, 50, "", allow); !expired {
+ t.Fatal("expired cursor accepted")
+ }
+}
+
+func TestGlobalBacklinkSnapshotBounds(t *testing.T) {
+ t.Cleanup(func() { ClearGlobalBacklinkSnapshots("") })
+ query := GlobalBacklinkQuery{ID: "id", Sort: 1}
+ first := ""
+ for i := 0; i < globalBacklinkSnapshotLimit+1; i++ {
+ token, _, err := globalBacklinkSnapshotPut(query, []*GlobalBacklinkItem{{ID: fmt.Sprint(i)}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if i == 0 {
+ first = token
+ }
+ }
+ if globalBacklinkSnapshotGet(query, first, func(string) bool { return true }) != nil {
+ t.Fatal("oldest snapshot was not evicted")
+ }
+ ClearGlobalBacklinkSnapshots("")
+ if len(globalBacklinkSnapshots.values) != 0 {
+ t.Fatal("snapshot purge left cached entries")
+ }
+ converted, _, err := globalBacklinkSnapshotPut(query, []*GlobalBacklinkItem{{ID: "id", Box: "locked"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ query.Notebook = "unrelated"
+ retained, _, err := globalBacklinkSnapshotPut(query, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { ClearGlobalBacklinkSnapshots("unrelated") })
+ ClearGlobalBacklinkSnapshots("locked")
+ if globalBacklinkSnapshots.values[converted] != nil || globalBacklinkSnapshots.values[retained] == nil {
+ t.Fatal("notebook purge did not isolate affected source snapshots")
+ }
+}
diff --git a/kernel/model/backlink_options_fts5_test.go b/kernel/model/backlink_options_fts5_test.go
index ce882303ac..f9816143a3 100644
--- a/kernel/model/backlink_options_fts5_test.go
+++ b/kernel/model/backlink_options_fts5_test.go
@@ -55,11 +55,19 @@ func TestBacklink2OptionalMentions(t *testing.T) {
if len(links) != 1 || linkCount != 1 || len(mentions) != 1 || mentionCount != 1 {
t.Fatalf("fixture should contain one backlink and one mention: %d/%d, %d/%d", len(links), linkCount, len(mentions), mentionCount)
}
- gotBox, gotLinks, gotMentions, gotLinkCount, gotMentionCount := GetBacklink2InBoxWithOptions(fixture.sourceID, "", "", 0, 0, false, "", nil, false)
+ gotBox, gotLinks, gotMentions, gotLinkCount, gotMentionCount := GetBacklink2InBoxWithOptions(fixture.sourceID, "", "", 0, 0, false, "", nil, false, true)
if gotBox != box || !reflect.DeepEqual(gotLinks, links) || gotLinkCount != linkCount {
t.Fatal("omitting mentions changed the backlink results")
}
if gotMentions == nil || len(gotMentions) != 0 || gotMentionCount != 0 {
t.Fatalf("omitted mentions must remain an empty array with zero count: %+v, %d", gotMentions, gotMentionCount)
}
+ gotBox, gotLinks, gotMentions, gotLinkCount, gotMentionCount = GetBacklink2InBoxWithOptions(fixture.sourceID, "", "", 0, 0, false, "", nil, true, false)
+ if gotBox != box || !reflect.DeepEqual(gotMentions, mentions) || gotMentionCount != mentionCount || gotLinks == nil || len(gotLinks) != 0 || gotLinkCount != 0 {
+ t.Fatal("omitting document groups changed mentions or retained backlink groups")
+ }
+ _, gotLinks, gotMentions, gotLinkCount, gotMentionCount = GetBacklink2InBoxWithOptions(fixture.sourceID, "", "", 0, 0, false, "", nil, false, false)
+ if len(gotLinks) != 0 || len(gotMentions) != 0 || gotLinkCount != 0 || gotMentionCount != 0 {
+ t.Fatal("omitted lists returned results")
+ }
}
diff --git a/kernel/model/backlink_ref_filter_fts5_test.go b/kernel/model/backlink_ref_filter_fts5_test.go
index 985a6f368c..b124dc4040 100644
--- a/kernel/model/backlink_ref_filter_fts5_test.go
+++ b/kernel/model/backlink_ref_filter_fts5_test.go
@@ -70,11 +70,11 @@ func TestBacklinkRefFilterListContextAndCandidates(t *testing.T) {
}
sql.FlushQueue()
filter := &BacklinkSourceFilter{ExcludedRefDefIDs: []string{archiveID}}
- _, all, mentions, allCount, mentionCount := GetBacklink2InBoxWithOptions(fixture.sourceID, "", "", 0, 0, false, "", nil, true)
+ _, all, mentions, allCount, mentionCount := GetBacklink2InBoxWithOptions(fixture.sourceID, "", "", 0, 0, false, "", nil, true, true)
if len(all) != 1 || allCount != 2 {
t.Fatalf("expected two entries in one source document: %d, %d", len(all), allCount)
}
- _, filtered, filteredMentions, count, filteredMentionCount := GetBacklink2InBoxWithOptions(fixture.sourceID, "", "", 0, 0, false, "", filter, true)
+ _, filtered, filteredMentions, count, filteredMentionCount := GetBacklink2InBoxWithOptions(fixture.sourceID, "", "", 0, 0, false, "", filter, true, true)
if len(filtered) != 1 || count != 1 || filtered[0].Count != 1 {
t.Fatalf("unexpected filtered list/count: %+v, %d", filtered, count)
}
diff --git a/kernel/model/backlink_sort_fts5_test.go b/kernel/model/backlink_sort_fts5_test.go
index 74859113d9..581567e93c 100644
--- a/kernel/model/backlink_sort_fts5_test.go
+++ b/kernel/model/backlink_sort_fts5_test.go
@@ -175,6 +175,20 @@ func TestBacklinkAnchorSortContext(t *testing.T) {
}
}
}
+ globalQuery := GlobalBacklinkQuery{ID: fixture.sourceID, Notebook: boxID, Sort: 1, ContainChildren: true}
+ allow := func(string) bool { return true }
+ token, globalItems, total, _, expired, err := GetGlobalBacklinks(globalQuery, "", 0, "", allow)
+ if err != nil || expired || total != 4 || globalItems[0].ID != ids[2] {
+ t.Fatalf("global sorting in %s notebook: %+v %v %v", name, globalItems, expired, err)
+ }
+ contexts, expired, err := GetGlobalBacklinkContexts(globalQuery, token, []string{ids[2], ids[0]}, allow)
+ if err != nil || expired || len(contexts) != 2 || contexts[0].ID != ids[2] {
+ t.Fatalf("global contexts in %s notebook: %+v %v %v", name, contexts, expired, err)
+ }
+ ClearGlobalBacklinkSnapshots(boxID)
+ if _, expired, _ = GetGlobalBacklinkContexts(globalQuery, token, []string{ids[0]}, allow); !expired {
+ t.Fatal("cleared notebook snapshot remained readable")
+ }
})
}
}
diff --git a/kernel/model/crypto.go b/kernel/model/crypto.go
index 2671326b54..65dd67684d 100644
--- a/kernel/model/crypto.go
+++ b/kernel/model/crypto.go
@@ -1548,6 +1548,7 @@ func lockBoxHeld(boxID string) {
heif.ClearMemoryCache(boxID)
RevokeManagedEncryptedExportsForBox(boxID)
ClearRichClipboardBox(boxID)
+ ClearGlobalBacklinkSnapshots(boxID)
cachedDEKsLock.Lock()
if dek, ok := cachedDEKs[boxID]; ok {