Skip to content

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

:sparkles: Improve document statistics to include embed block content https://github.com/siyuan-note/siyuan/issues/18681

Daniel1d9107a8a8c9
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index fc77ff85a4..5757e28f34 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,7 @@
{
+ "runeCountWithEmbed": "عدد الأحرف مع الكتل المضمنة",
+ "wordCountWithEmbed": "عدد الكلمات مع الكتل المضمنة",
+ "embedStatIncomplete": "الإحصاءات غير مكتملة لتعذر احتساب بعض الكتل المضمنة",
"mergeDocHeadingMode": "مستويات عناوين المستندات",
"mergeDocHeadingFlat": "استخدام العنوان 1 لجميع عناوين المستندات",
"mergeDocHeadingTree": "اتباع التسلسل الهرمي للمستندات",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index af84289645..4f33a125a1 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,7 @@
{
+ "runeCountWithEmbed": "Zeichen einschließlich eingebetteter Blöcke",
+ "wordCountWithEmbed": "Wörter einschließlich eingebetteter Blöcke",
+ "embedStatIncomplete": "Die Statistik ist unvollständig, da einige eingebettete Blöcke nicht gezählt werden konnten",
"mergeDocHeadingMode": "Ebenen der Dokumenttitel",
"mergeDocHeadingFlat": "Alle Dokumenttitel als Überschrift 1",
"mergeDocHeadingTree": "Der Dokumenthierarchie folgen",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index b3da09f811..0da08e1f7d 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,7 @@
{
+ "runeCountWithEmbed": "Characters with embed blocks",
+ "wordCountWithEmbed": "Words with embed blocks",
+ "embedStatIncomplete": "The statistics are incomplete because some embed blocks could not be counted",
"mergeDocHeadingMode": "Document title levels",
"mergeDocHeadingFlat": "Use heading 1 for all document titles",
"mergeDocHeadingTree": "Follow the document hierarchy",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 5d7f776c37..eae05efba4 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,7 @@
{
+ "runeCountWithEmbed": "Caracteres con bloques incrustados",
+ "wordCountWithEmbed": "Palabras con bloques incrustados",
+ "embedStatIncomplete": "Las estadísticas están incompletas porque no se pudieron contar algunos bloques incrustados",
"mergeDocHeadingMode": "Niveles de títulos de documentos",
"mergeDocHeadingFlat": "Usar encabezado 1 para todos los títulos de documentos",
"mergeDocHeadingTree": "Seguir la jerarquía de documentos",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 9d3cc178dd..3893d152b9 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,7 @@
{
+ "runeCountWithEmbed": "Caractères avec blocs intégrés",
+ "wordCountWithEmbed": "Mots avec blocs intégrés",
+ "embedStatIncomplete": "Les statistiques sont incomplètes, car certains blocs intégrés n’ont pas pu être comptés",
"mergeDocHeadingMode": "Niveaux des titres de documents",
"mergeDocHeadingFlat": "Utiliser le titre 1 pour tous les titres de documents",
"mergeDocHeadingTree": "Suivre la hiérarchie des documents",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index e3caea33b0..cf0106309c 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,7 @@
{
+ "runeCountWithEmbed": "תווים כולל בלוקים מוטמעים",
+ "wordCountWithEmbed": "מילים כולל בלוקים מוטמעים",
+ "embedStatIncomplete": "הסטטיסטיקה חלקית מכיוון שלא ניתן היה לספור חלק מהבלוקים המוטמעים",
"mergeDocHeadingMode": "רמות כותרות המסמכים",
"mergeDocHeadingFlat": "השתמש בכותרת 1 לכל כותרות המסמכים",
"mergeDocHeadingTree": "פעל לפי היררכיית המסמכים",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 5356429879..4e4663eeb8 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,7 @@
{
+ "runeCountWithEmbed": "एम्बेड ब्लॉक सहित वर्ण",
+ "wordCountWithEmbed": "एम्बेड ब्लॉक सहित शब्द",
+ "embedStatIncomplete": "कुछ एम्बेड ब्लॉक की गणना नहीं हो सकी, इसलिए आँकड़े अपूर्ण हैं",
"mergeDocHeadingMode": "दस्तावेज़ शीर्षक स्तर",
"mergeDocHeadingFlat": "सभी दस्तावेज़ शीर्षकों के लिए शीर्षक 1 का उपयोग करें",
"mergeDocHeadingTree": "दस्तावेज़ पदानुक्रम का अनुसरण करें",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index c7f38246ba..79c94a6736 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,7 @@
{
+ "runeCountWithEmbed": "Karakter termasuk blok sematan",
+ "wordCountWithEmbed": "Kata termasuk blok sematan",
+ "embedStatIncomplete": "Statistik tidak lengkap karena beberapa blok sematan tidak dapat dihitung",
"mergeDocHeadingMode": "Tingkat judul dokumen",
"mergeDocHeadingFlat": "Gunakan heading 1 untuk semua judul dokumen",
"mergeDocHeadingTree": "Ikuti hierarki dokumen",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 504c0e83bf..8f420a714d 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,7 @@
{
+ "runeCountWithEmbed": "Caratteri con blocchi incorporati",
+ "wordCountWithEmbed": "Parole con blocchi incorporati",
+ "embedStatIncomplete": "Le statistiche sono incomplete perché non è stato possibile conteggiare alcuni blocchi incorporati",
"mergeDocHeadingMode": "Livelli dei titoli dei documenti",
"mergeDocHeadingFlat": "Usa titolo 1 per tutti i titoli dei documenti",
"mergeDocHeadingTree": "Segui la gerarchia dei documenti",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 8739905abe..c3704a9d62 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,7 @@
{
+ "runeCountWithEmbed": "埋め込みブロックを含む文字数",
+ "wordCountWithEmbed": "埋め込みブロックを含む単語数",
+ "embedStatIncomplete": "一部の埋め込みブロックを集計できないため、統計は不完全です",
"mergeDocHeadingMode": "文書タイトルの見出しレベル",
"mergeDocHeadingFlat": "すべての文書タイトルを見出し1にする",
"mergeDocHeadingTree": "文書の階層に従う",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 1e96349be1..fe3802b470 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,7 @@
{
+ "runeCountWithEmbed": "임베드 블록 포함 글자 수",
+ "wordCountWithEmbed": "임베드 블록 포함 단어 수",
+ "embedStatIncomplete": "일부 임베드 블록을 계산할 수 없어 통계가 완전하지 않습니다",
"mergeDocHeadingMode": "문서 제목 수준",
"mergeDocHeadingFlat": "모든 문서 제목에 제목 1 사용",
"mergeDocHeadingTree": "문서 계층 구조 따르기",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index c24ad33fd4..8afa839205 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,7 @@
{
+ "runeCountWithEmbed": "Tekens inclusief ingesloten blokken",
+ "wordCountWithEmbed": "Woorden inclusief ingesloten blokken",
+ "embedStatIncomplete": "De statistieken zijn onvolledig omdat sommige ingesloten blokken niet konden worden geteld",
"mergeDocHeadingMode": "Niveaus van documenttitels",
"mergeDocHeadingFlat": "Gebruik kop 1 voor alle documenttitels",
"mergeDocHeadingTree": "Volg de documenthiërarchie",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index baabc6a057..62fcf693f2 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,7 @@
{
+ "runeCountWithEmbed": "Znaki z osadzonymi blokami",
+ "wordCountWithEmbed": "Słowa z osadzonymi blokami",
+ "embedStatIncomplete": "Statystyki są niepełne, ponieważ nie udało się policzyć niektórych osadzonych bloków",
"mergeDocHeadingMode": "Poziomy tytułów dokumentów",
"mergeDocHeadingFlat": "Użyj nagłówka 1 dla wszystkich tytułów dokumentów",
"mergeDocHeadingTree": "Zachowaj hierarchię dokumentów",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index de5c25d254..4f55d766da 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,7 @@
{
+ "runeCountWithEmbed": "Caracteres com blocos incorporados",
+ "wordCountWithEmbed": "Palavras com blocos incorporados",
+ "embedStatIncomplete": "As estatísticas estão incompletas porque alguns blocos incorporados não puderam ser contados",
"mergeDocHeadingMode": "Níveis dos títulos dos documentos",
"mergeDocHeadingFlat": "Usar cabeçalho 1 para todos os títulos dos documentos",
"mergeDocHeadingTree": "Seguir a hierarquia dos documentos",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index f2fe897a09..88968657d4 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,7 @@
{
+ "runeCountWithEmbed": "Символы с учётом встроенных блоков",
+ "wordCountWithEmbed": "Слова с учётом встроенных блоков",
+ "embedStatIncomplete": "Статистика неполна, поскольку некоторые встроенные блоки не удалось учесть",
"mergeDocHeadingMode": "Уровни заголовков документов",
"mergeDocHeadingFlat": "Использовать заголовок 1 для всех названий документов",
"mergeDocHeadingTree": "Следовать иерархии документов",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index cc0b36041c..0c6ec95c44 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,7 @@
{
+ "runeCountWithEmbed": "Znaky vrátane vložených blokov",
+ "wordCountWithEmbed": "Slová vrátane vložených blokov",
+ "embedStatIncomplete": "Štatistika nie je úplná, pretože niektoré vložené bloky nebolo možné spočítať",
"mergeDocHeadingMode": "Úrovne názvov dokumentov",
"mergeDocHeadingFlat": "Použiť nadpis 1 pre všetky názvy dokumentov",
"mergeDocHeadingTree": "Riadiť sa hierarchiou dokumentov",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 13f68c0324..11d59aa7e9 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,7 @@
{
+ "runeCountWithEmbed": "อักขระรวมบล็อกฝัง",
+ "wordCountWithEmbed": "คำรวมบล็อกฝัง",
+ "embedStatIncomplete": "สถิติไม่สมบูรณ์เนื่องจากไม่สามารถนับบล็อกฝังบางรายการได้",
"mergeDocHeadingMode": "ระดับชื่อเอกสาร",
"mergeDocHeadingFlat": "ใช้หัวข้อ 1 สำหรับชื่อเอกสารทั้งหมด",
"mergeDocHeadingTree": "เรียงตามลำดับชั้นของเอกสาร",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 51893bc5e4..33a7a53ef2 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,7 @@
{
+ "runeCountWithEmbed": "Gömülü bloklarla karakterler",
+ "wordCountWithEmbed": "Gömülü bloklarla kelimeler",
+ "embedStatIncomplete": "Bazı gömülü bloklar sayılamadığı için istatistikler eksik",
"mergeDocHeadingMode": "Belge başlığı düzeyleri",
"mergeDocHeadingFlat": "Tüm belge başlıkları için başlık 1 kullan",
"mergeDocHeadingTree": "Belge hiyerarşisini izle",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 16d784afa6..616749a08c 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,7 @@
{
+ "runeCountWithEmbed": "Символи з урахуванням вбудованих блоків",
+ "wordCountWithEmbed": "Слова з урахуванням вбудованих блоків",
+ "embedStatIncomplete": "Статистика неповна, оскільки деякі вбудовані блоки не вдалося врахувати",
"mergeDocHeadingMode": "Рівні заголовків документів",
"mergeDocHeadingFlat": "Використовувати заголовок 1 для всіх назв документів",
"mergeDocHeadingTree": "Дотримуватися ієрархії документів",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index ac698374cf..bb411ecdbc 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,7 @@
{
+ "runeCountWithEmbed": "含嵌入块字符数",
+ "wordCountWithEmbed": "含嵌入块字数",
+ "embedStatIncomplete": "部分嵌入块无法统计,结果不完整",
"mergeDocHeadingMode": "文档标题层级",
"mergeDocHeadingFlat": "文档标题都为一级标题",
"mergeDocHeadingTree": "遵循文档层级关系",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index c43ccca13d..806f16df4e 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,7 @@
{
+ "runeCountWithEmbed": "含嵌入區塊字元數",
+ "wordCountWithEmbed": "含嵌入區塊字數",
+ "embedStatIncomplete": "部分嵌入區塊無法統計,結果不完整",
"mergeDocHeadingMode": "文件標題層級",
"mergeDocHeadingFlat": "文件標題都為一級標題",
"mergeDocHeadingTree": "遵循文件層級關係",
diff --git a/app/src/layout/status.ts b/app/src/layout/status.ts
index 04f5e62bd7..f5100dfd04 100644
--- a/app/src/layout/status.ts
+++ b/app/src/layout/status.ts
@@ -11,6 +11,7 @@ import {ipcRenderer} from "electron";
import {MenuItem} from "../menus/Menu";
import {Constants} from "../constants";
import {updateHotkeyTip} from "../protyle/util/compatibility";
+import {escapeAriaLabel} from "../util/escape";
export const initStatus = (isWindow = false) => {
/// #if !MOBILE
@@ -139,23 +140,26 @@ let lastRootId: string;
const scheduleStatusStat = (rootID: string, content?: string, ids?: string[]) => {
clearTimeout(countTimeout);
+ if (countAbortController) {
+ countAbortController.abort();
+ countAbortController = null;
+ }
countTimeout = window.setTimeout(() => {
- if (countAbortController) {
- countAbortController.abort();
- countAbortController = null;
- }
countAbortController = new AbortController();
const signal = countAbortController.signal;
const capturedController = countAbortController;
+ const finishRequest = () => {
+ if (countAbortController === capturedController) {
+ countAbortController = null;
+ }
+ };
const onFetched = (response: IWebSocketData) => {
if (signal.aborted) {
return;
}
renderStatusbarCounter(response.data.stat);
- if (countAbortController === capturedController) {
- countAbortController = null;
- }
+ finishRequest();
};
if (content) {
@@ -166,9 +170,30 @@ const scheduleStatusStat = (rootID: string, content?: string, ids?: string[]) =>
lastRootId = null;
} else if (rootID && lastRootId !== rootID) {
lastRootId = rootID;
- fetchPost("/api/block/getTreeStat", {id: rootID}, onFetched, undefined, undefined, signal);
+ fetchPost("/api/block/getTreeStat", {id: rootID}, (response) => {
+ if (signal.aborted) {
+ return;
+ }
+ renderStatusbarCounter(response.data.stat);
+ if (!response.data.containsEmbed) {
+ finishRequest();
+ return;
+ }
+ fetchPost("/api/block/getTreeStat", {id: rootID, includeEmbed: true}, (embedResponse) => {
+ if (signal.aborted) {
+ return;
+ }
+ renderStatusbarCounter(
+ embedResponse.data.stat,
+ embedResponse.data.statWithEmbed,
+ embedResponse.data.embedStat
+ );
+ finishRequest();
+ }, undefined, undefined, signal);
+ }, undefined, undefined, signal);
} else {
lastRootId = null;
+ finishRequest();
}
}, Constants.TIMEOUT_COUNT);
};
@@ -213,14 +238,28 @@ export const clearCounter = () => {
document.querySelector("#status .status__counter").innerHTML = "";
};
-export const renderStatusbarCounter = (stat: {
- runeCount: number,
- wordCount: number,
- linkCount: number,
- imageCount: number,
- refCount: number,
- blockCount: number,
-}) => {
+export interface IBlockStat {
+ runeCount: number;
+ wordCount: number;
+ linkCount: number;
+ imageCount: number;
+ refCount: number;
+ blockCount: number;
+}
+
+export interface IEmbedStat {
+ complete: boolean;
+ queryEmbedCount: number;
+ jsEmbedCount: number;
+ resultCount: number;
+ failedQueryCount: number;
+ failedResultCount: number;
+ truncatedQueryCount: number;
+ cycleCount: number;
+ depthLimitCount: number;
+}
+
+export const renderStatusbarCounter = (stat: IBlockStat, statWithEmbed?: IBlockStat, embedStat?: IEmbedStat) => {
if (!stat) {
return;
}
@@ -238,5 +277,13 @@ export const renderStatusbarCounter = (stat: {
if (0 < stat.blockCount) {
html += `<span class="ft__on-surface">${window.siyuan.languages.blockCount}</span>&nbsp;${stat.blockCount}<span class="fn__space"></span>`;
}
+ if (statWithEmbed) {
+ const incompleteClass = embedStat && !embedStat.complete ? " ariaLabel" : "";
+ const incompleteAttrs = embedStat && !embedStat.complete ?
+ ` data-position="north" aria-label="${escapeAriaLabel(window.siyuan.languages.embedStatIncomplete)}"` : "";
+ const prefix = embedStat && !embedStat.complete ? "≈" : "";
+ html += `<span class="ft__on-surface${incompleteClass}"${incompleteAttrs}>${prefix}${window.siyuan.languages.runeCountWithEmbed}</span>&nbsp;${statWithEmbed.runeCount}<span class="fn__space"></span>
+<span class="ft__on-surface${incompleteClass}"${incompleteAttrs}>${prefix}${window.siyuan.languages.wordCountWithEmbed}</span>&nbsp;${statWithEmbed.wordCount}<span class="fn__space"></span>`;
+ }
document.querySelector("#status .status__counter").innerHTML = html;
};
diff --git a/app/src/protyle/breadcrumb/index.ts b/app/src/protyle/breadcrumb/index.ts
index feec259522..633d0e4ae1 100644
--- a/app/src/protyle/breadcrumb/index.ts
+++ b/app/src/protyle/breadcrumb/index.ts
@@ -38,6 +38,18 @@ import {getCloudURL} from "../../config/util/about";
import {escapeAriaLabel} from "../../util/escape";
import {refreshUndoButtons} from "../undo/globalUndo";
import {getAllEditor} from "../../layout/getAll";
+import type {IBlockStat, IEmbedStat} from "../../layout/status";
+
+const genDocumentStatLabel = (stat: IBlockStat, statWithEmbed?: IBlockStat, embedStat?: IEmbedStat) => {
+ let html = `<div class="fn__flex">${window.siyuan.languages.runeCount}<span class="fn__space fn__flex-1"></span>${stat.runeCount}</div><div class="fn__flex">${window.siyuan.languages.wordCount}<span class="fn__space fn__flex-1"></span>${stat.wordCount}</div><div class="fn__flex">${window.siyuan.languages.linkCount}<span class="fn__space fn__flex-1"></span>${stat.linkCount}</div><div class="fn__flex">${window.siyuan.languages.imgCount}<span class="fn__space fn__flex-1"></span>${stat.imageCount}</div><div class="fn__flex">${window.siyuan.languages.refCount}<span class="fn__space fn__flex-1"></span>${stat.refCount}</div><div class="fn__flex">${window.siyuan.languages.blockCount}<span class="fn__space fn__flex-1"></span>${stat.blockCount}</div>`;
+ if (statWithEmbed) {
+ const incompleteAttrs = embedStat && !embedStat.complete ?
+ ` class="ariaLabel" data-position="north" aria-label="${escapeAriaLabel(window.siyuan.languages.embedStatIncomplete)}"` : "";
+ const prefix = embedStat && !embedStat.complete ? "≈" : "";
+ html += `<div class="fn__flex"><span${incompleteAttrs}>${prefix}${window.siyuan.languages.runeCountWithEmbed}</span><span class="fn__space fn__flex-1"></span>${statWithEmbed.runeCount}</div><div class="fn__flex"><span${incompleteAttrs}>${prefix}${window.siyuan.languages.wordCountWithEmbed}</span><span class="fn__space fn__flex-1"></span>${statWithEmbed.wordCount}</div>`;
+ }
+ return html;
+};
export class Breadcrumb {
public element: HTMLElement;
@@ -644,7 +656,13 @@ ${padHTML}
if (cursorNodeElement) {
id = cursorNodeElement.getAttribute("data-node-id");
}
- fetchPost("/api/block/getTreeStat", {id: id || (protyle.block.showAll ? protyle.block.id : protyle.block.rootID)}, (response) => {
+ const statRequest: IObject = {
+ id: id || (protyle.block.showAll ? protyle.block.id : protyle.block.rootID)
+ };
+ if (isEncryptedBox(protyle.notebookId)) {
+ statRequest.notebook = protyle.notebookId;
+ }
+ fetchPost("/api/block/getTreeStat", statRequest, (response) => {
window.siyuan.menus.menu.remove();
window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_BREADCRUMB_MORE);
if (!protyle.contentElement.classList.contains("fn__none") && !protyle.disabled) {
@@ -1025,13 +1043,27 @@ ${padHTML}
});
}
window.siyuan.menus.menu.append(new MenuItem({id: "separator_2", type: "separator"}).element);
- window.siyuan.menus.menu.append(new MenuItem({
+ const docInfoElement = new MenuItem({
id: "docInfo",
iconHTML: "",
type: "readonly",
// 不能换行,否则移动端间距过大
- label: `<div class="fn__flex">${window.siyuan.languages.runeCount}<span class="fn__space fn__flex-1"></span>${response.data.stat.runeCount}</div><div class="fn__flex">${window.siyuan.languages.wordCount}<span class="fn__space fn__flex-1"></span>${response.data.stat.wordCount}</div><div class="fn__flex">${window.siyuan.languages.linkCount}<span class="fn__space fn__flex-1"></span>${response.data.stat.linkCount}</div><div class="fn__flex">${window.siyuan.languages.imgCount}<span class="fn__space fn__flex-1"></span>${response.data.stat.imageCount}</div><div class="fn__flex">${window.siyuan.languages.refCount}<span class="fn__space fn__flex-1"></span>${response.data.stat.refCount}</div><div class="fn__flex">${window.siyuan.languages.blockCount}<span class="fn__space fn__flex-1"></span>${response.data.stat.blockCount}</div>`,
- }).element);
+ label: genDocumentStatLabel(response.data.stat),
+ }).element;
+ window.siyuan.menus.menu.append(docInfoElement);
+ if (response.data.containsEmbed) {
+ fetchPost("/api/block/getTreeStat", {...statRequest, includeEmbed: true}, (embedResponse) => {
+ if (!docInfoElement.isConnected ||
+ window.siyuan.menus.menu.element.getAttribute("data-name") !== Constants.MENU_BREADCRUMB_MORE) {
+ return;
+ }
+ docInfoElement.querySelector(".b3-menu__label").innerHTML = genDocumentStatLabel(
+ embedResponse.data.stat,
+ embedResponse.data.statWithEmbed,
+ embedResponse.data.embedStat
+ );
+ });
+ }
/// #if MOBILE
window.siyuan.menus.menu.fullscreen();
/// #else
diff --git a/kernel/api/block.go b/kernel/api/block.go
index 86a5e5e5c7..af2e86567f 100644
--- a/kernel/api/block.go
+++ b/kernel/api/block.go
@@ -799,7 +799,14 @@ func getTreeStat(c *gin.Context) {
return
}
- id := arg["id"].(string)
+ var id string
+ var includeEmbed bool
+ if !util.ParseJsonArgs(arg, ret,
+ util.BindJsonArg("id", &id, true, true),
+ util.BindJsonArg("includeEmbed", &includeEmbed, false, false),
+ ) || util.InvalidIDPattern(id, ret) {
+ return
+ }
boxID := encryptedNotebookFromArg(arg)
if !holdBlockRequest(c, ret, boxID) {
return
@@ -811,10 +818,29 @@ func getTreeStat(c *gin.Context) {
}
return
}
- ret.Data = map[string]any{
- "reqId": arg["reqId"],
- "stat": filesys.StatTree(id),
+
+ var accessChecker model.EmbedBlockAccessChecker
+ if model.IsReadOnlyRoleContext(c) {
+ publishAccess := model.GetPublishAccess()
+ accessChecker = func(blockID string) bool {
+ return model.CheckBlockIdAccessableByPublishAccessInBox(c, publishAccess, blockID, boxID)
+ }
+ }
+ stat := model.GetDocumentStat(c.Request.Context(), id, boxID, includeEmbed, accessChecker)
+ data := map[string]any{
+ "reqId": arg["reqId"],
+ "stat": nil,
+ "containsEmbed": false,
+ }
+ if nil != stat {
+ data["stat"] = stat.Stat
+ data["containsEmbed"] = stat.ContainsEmbed
+ if includeEmbed {
+ data["statWithEmbed"] = stat.StatWithEmbed
+ data["embedStat"] = stat.EmbedStat
+ }
}
+ ret.Data = data
}
func getDOMText(c *gin.Context) {
diff --git a/kernel/filesys/stat.go b/kernel/filesys/stat.go
index 5ff53f3ed3..b00064d80d 100644
--- a/kernel/filesys/stat.go
+++ b/kernel/filesys/stat.go
@@ -103,25 +103,45 @@ func StatTreeInBox(id, boxID string) (ret *util.BlockStatResult) {
return statTree(tree)
}
+// StatTreeFromTree 统计整棵文档树。
+func StatTreeFromTree(tree *parse.Tree) (ret *util.BlockStatResult) {
+ if nil == tree || nil == tree.Root {
+ return
+ }
+ return StatNodes(tree, []*ast.Node{tree.Root})
+}
+
func statTree(tree *parse.Tree) (ret *util.BlockStatResult) {
+ return StatTreeFromTree(tree)
+}
+
+// StatNodes 统计指定节点及其子节点。
+func StatNodes(tree *parse.Tree, nodes []*ast.Node) (ret *util.BlockStatResult) {
+ if nil == tree {
+ return
+ }
+
blockCount := 0
var databaseBlockNodes []*ast.Node
- ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
- if !entering || tree.Root == n {
- return ast.WalkContinue
+ for _, node := range nodes {
+ if nil == node {
+ continue
}
+ ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if !entering {
+ return ast.WalkContinue
+ }
- if n.IsBlock() {
- blockCount++
- }
+ if n.IsBlock() && ast.NodeDocument != n.Type {
+ blockCount++
+ }
- if ast.NodeAttributeView != n.Type {
+ if ast.NodeAttributeView == n.Type {
+ databaseBlockNodes = append(databaseBlockNodes, n)
+ }
return ast.WalkContinue
- }
-
- databaseBlockNodes = append(databaseBlockNodes, n)
- return ast.WalkContinue
- })
+ })
+ }
luteEngine := util.NewLute()
var dbRuneCnt, dbWordCnt, dbLinkCnt, dbImgCnt, dbRefCnt int
@@ -200,7 +220,18 @@ func statTree(tree *parse.Tree) (ret *util.BlockStatResult) {
dbWordCnt += dbStat.WordCount
}
- runeCnt, wordCnt, linkCnt, imgCnt, refCnt := tree.Root.Stat()
+ var runeCnt, wordCnt, linkCnt, imgCnt, refCnt int
+ for _, node := range nodes {
+ if nil == node {
+ continue
+ }
+ nodeRuneCnt, nodeWordCnt, nodeLinkCnt, nodeImgCnt, nodeRefCnt := node.Stat()
+ runeCnt += nodeRuneCnt
+ wordCnt += nodeWordCnt
+ linkCnt += nodeLinkCnt
+ imgCnt += nodeImgCnt
+ refCnt += nodeRefCnt
+ }
runeCnt += dbRuneCnt
wordCnt += dbWordCnt
linkCnt += dbLinkCnt
diff --git a/kernel/model/block.go b/kernel/model/block.go
index c2b794641f..3f1e2e5c5f 100644
--- a/kernel/model/block.go
+++ b/kernel/model/block.go
@@ -1770,26 +1770,7 @@ func getEmbeddedBlock(trees map[string]*parse.Tree, sqlBlock *sql.Block, heading
return
}
- var nodes []*ast.Node
- // headingMode: 0=显示标题与下方的块,1=仅显示标题,2=仅显示标题下方的块
- if ast.NodeHeading == def.Type {
- if 1 == headingMode {
- // 仅显示标题
- nodes = append(nodes, def)
- } else if 2 == headingMode {
- // 仅显示标题下方的块(去除标题)
- if !treenode.IsSelfFolded(def) {
- nodes = append(nodes, treenode.HeadingChildren(def)...)
- }
- } else {
- // 0: 显示标题与下方的块
- nodes = append(nodes, def)
- nodes = append(nodes, treenode.HeadingChildren(def)...)
- }
- } else {
- // 非标题块,直接添加
- nodes = append(nodes, def)
- }
+ nodes := embeddedBlockNodes(def, headingMode)
var b *treenode.BlockTree
if IsEncryptedBox(sqlBlock.Box) {
@@ -1838,6 +1819,30 @@ func getEmbeddedBlock(trees map[string]*parse.Tree, sqlBlock *sql.Block, heading
return
}
+func embeddedBlockNodes(def *ast.Node, headingMode int) (ret []*ast.Node) {
+ if nil == def {
+ return
+ }
+ if ast.NodeHeading != def.Type {
+ return []*ast.Node{def}
+ }
+
+ // headingMode:0 表示显示标题与下方的块,1 表示仅显示标题,2 表示仅显示标题下方的块。
+ if 1 == headingMode {
+ return []*ast.Node{def}
+ }
+ if 2 == headingMode {
+ if !treenode.IsSelfFolded(def) {
+ ret = append(ret, treenode.HeadingChildren(def)...)
+ }
+ return
+ }
+
+ ret = append(ret, def)
+ ret = append(ret, treenode.HeadingChildren(def)...)
+ return
+}
+
func newEmbeddedBlock(def *ast.Node, blockTree *treenode.BlockTree, dom, content string) *Block {
return &Block{
Box: def.Box,
diff --git a/kernel/model/document_stat.go b/kernel/model/document_stat.go
new file mode 100644
index 0000000000..72c4ad303b
--- /dev/null
+++ b/kernel/model/document_stat.go
@@ -0,0 +1,350 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import (
+ "context"
+ "errors"
+ stdhtml "html"
+ "strconv"
+ "strings"
+
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/editor"
+ "github.com/88250/lute/parse"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+const (
+ maxDocumentStatEmbedDepth = 4
+ maxDocumentStatEmbedResults = 1024
+)
+
+// DocumentStat 表示文档本身及包含嵌入块后的统计结果。
+type DocumentStat struct {
+ Stat *util.BlockStatResult `json:"stat"`
+ ContainsEmbed bool `json:"containsEmbed"`
+ StatWithEmbed *util.BlockStatResult `json:"statWithEmbed,omitempty"`
+ EmbedStat *EmbedStat `json:"embedStat,omitempty"`
+}
+
+// EmbedStat 表示嵌入块解析的完整性和处理数量。
+type EmbedStat struct {
+ Complete bool `json:"complete"`
+ QueryEmbedCount int `json:"queryEmbedCount"`
+ JSEmbedCount int `json:"jsEmbedCount"`
+ ResultCount int `json:"resultCount"`
+ FailedQueryCount int `json:"failedQueryCount"`
+ FailedResultCount int `json:"failedResultCount"`
+ TruncatedQueryCount int `json:"truncatedQueryCount"`
+ CycleCount int `json:"cycleCount"`
+ DepthLimitCount int `json:"depthLimitCount"`
+}
+
+type documentEmbedStatResolver struct {
+ ctx context.Context
+ hostRootID string
+ accessChecker EmbedBlockAccessChecker
+ queryLimit int
+ treeCache map[string]*parse.Tree
+ path map[string]bool
+ stat *util.BlockStatResult
+ info *EmbedStat
+ queryBlocks func(context.Context, string, int, string) ([]*sql.Block, bool, error)
+ loadTree func(*sql.Block) *parse.Tree
+ validate func(string, string) error
+}
+
+// GetDocumentStat 统计文档,并按需解析查询嵌入块。
+func GetDocumentStat(ctx context.Context, id, boxID string, includeEmbed bool, accessChecker EmbedBlockAccessChecker) (ret *DocumentStat) {
+ tree := loadDocumentStatTree(id, boxID)
+ if nil == tree {
+ return
+ }
+
+ ret = &DocumentStat{
+ Stat: filesys.StatTreeFromTree(tree),
+ ContainsEmbed: containsQueryEmbed([]*ast.Node{tree.Root}),
+ }
+ if !includeEmbed {
+ return
+ }
+
+ statWithEmbed := *ret.Stat
+ ret.StatWithEmbed = &statWithEmbed
+ ret.EmbedStat = &EmbedStat{Complete: true}
+ if !ret.ContainsEmbed {
+ return
+ }
+
+ queryLimit := 64
+ if nil != Conf && nil != Conf.Search && 0 < Conf.Search.Limit {
+ queryLimit = Conf.Search.Limit
+ }
+ resolver := &documentEmbedStatResolver{
+ ctx: ctx,
+ hostRootID: tree.Root.ID,
+ accessChecker: accessChecker,
+ queryLimit: queryLimit,
+ treeCache: map[string]*parse.Tree{documentStatTreeCacheKey(tree.Box, tree.Root.ID): tree},
+ path: map[string]bool{},
+ stat: ret.StatWithEmbed,
+ info: ret.EmbedStat,
+ queryBlocks: sql.SelectBlocksRawStmtBoundedInBoxContext,
+ loadTree: loadDocumentStatResultTree,
+ validate: validateDocumentStatQuery,
+ }
+ resolver.resolveNodes(tree, []*ast.Node{tree.Root}, 0)
+ return
+}
+
+func loadDocumentStatTree(id, boxID string) (ret *parse.Tree) {
+ var err error
+ if "" != boxID {
+ ret, err = LoadTreeByBlockIDInExactBox(id, boxID)
+ } else {
+ ret, err = LoadTreeByBlockID(id)
+ }
+ if nil != err {
+ return nil
+ }
+ return
+}
+
+func loadDocumentStatResultTree(block *sql.Block) (ret *parse.Tree) {
+ if nil == block {
+ return
+ }
+ var err error
+ if IsEncryptedBox(block.Box) {
+ ret, err = LoadTreeByBlockIDInExactBox(block.RootID, block.Box)
+ } else {
+ ret, err = LoadTreeByBlockID(block.RootID)
+ }
+ if nil != err {
+ return nil
+ }
+ return
+}
+
+func validateDocumentStatQuery(stmt, boxID string) (err error) {
+ if err = sql.CheckSingleStatement(stmt); nil != err {
+ return
+ }
+ return sql.CheckReadonlyStatementInBox(stmt, boxID)
+}
+
+func (resolver *documentEmbedStatResolver) resolveNodes(tree *parse.Tree, nodes []*ast.Node, depth int) {
+ var embeds []*ast.Node
+ for _, node := range nodes {
+ if nil == node {
+ continue
+ }
+ ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if !entering {
+ return ast.WalkContinue
+ }
+ if ast.NodeBlockQueryEmbed == n.Type {
+ embeds = append(embeds, n)
+ return ast.WalkSkipChildren
+ }
+ return ast.WalkContinue
+ })
+ }
+
+ for _, embed := range embeds {
+ if nil != resolver.ctx.Err() {
+ resolver.info.Complete = false
+ return
+ }
+ resolver.resolveEmbed(tree, embed, depth)
+ }
+}
+
+func (resolver *documentEmbedStatResolver) resolveEmbed(sourceTree *parse.Tree, embed *ast.Node, depth int) {
+ stmt, ok := documentStatEmbedStatement(embed)
+ if !ok {
+ resolver.info.QueryEmbedCount++
+ resolver.info.FailedQueryCount++
+ resolver.info.Complete = false
+ return
+ }
+ if strings.HasPrefix(stmt, "//!js") {
+ resolver.info.JSEmbedCount++
+ resolver.info.Complete = false
+ return
+ }
+
+ resolver.info.QueryEmbedCount++
+ if maxDocumentStatEmbedDepth <= depth {
+ resolver.info.DepthLimitCount++
+ resolver.info.Complete = false
+ return
+ }
+ if resolver.path[embed.ID] {
+ resolver.info.CycleCount++
+ resolver.info.Complete = false
+ return
+ }
+
+ remaining := maxDocumentStatEmbedResults - resolver.info.ResultCount
+ if 1 > remaining {
+ resolver.info.TruncatedQueryCount++
+ resolver.info.Complete = false
+ return
+ }
+ queryLimit := min(resolver.queryLimit, remaining)
+ queryBoxID := ""
+ if IsEncryptedBox(sourceTree.Box) {
+ queryBoxID = sourceTree.Box
+ }
+ if err := resolver.validate(stmt, queryBoxID); nil != err {
+ resolver.info.FailedQueryCount++
+ resolver.info.Complete = false
+ return
+ }
+
+ blocks, truncated, err := resolver.queryBlocks(resolver.ctx, stmt, queryLimit, queryBoxID)
+ if nil != err {
+ if !errors.Is(err, context.Canceled) {
+ resolver.info.FailedQueryCount++
+ }
+ resolver.info.Complete = false
+ return
+ }
+ if truncated {
+ resolver.info.TruncatedQueryCount++
+ resolver.info.Complete = false
+ }
+
+ resolver.path[embed.ID] = true
+ defer delete(resolver.path, embed.ID)
+ for _, block := range blocks {
+ if nil != resolver.ctx.Err() {
+ resolver.info.Complete = false
+ return
+ }
+ if maxDocumentStatEmbedResults <= resolver.info.ResultCount {
+ resolver.info.TruncatedQueryCount++
+ resolver.info.Complete = false
+ break
+ }
+ if nil == block || "query_embed" == block.Type || block.ID == embed.ID || block.ID == resolver.hostRootID {
+ continue
+ }
+ if nil != resolver.accessChecker && !resolver.accessChecker(block.ID) {
+ continue
+ }
+ resultTree := resolver.getResultTree(block)
+ if nil == resultTree {
+ resolver.info.FailedResultCount++
+ resolver.info.Complete = false
+ continue
+ }
+ def := treenode.GetNodeInTree(resultTree, block.ID)
+ if nil == def {
+ resolver.info.FailedResultCount++
+ resolver.info.Complete = false
+ continue
+ }
+
+ headingMode := documentStatHeadingMode(embed)
+ visibleNodes := cleanRenderNodes(embeddedBlockNodes(def, headingMode), true)
+ addBlockStat(resolver.stat, filesys.StatNodes(resultTree, visibleNodes))
+ resolver.info.ResultCount++
+ resolver.resolveNodes(resultTree, visibleNodes, depth+1)
+ }
+}
+
+func (resolver *documentEmbedStatResolver) getResultTree(block *sql.Block) (ret *parse.Tree) {
+ key := documentStatTreeCacheKey(block.Box, block.RootID)
+ if ret = resolver.treeCache[key]; nil != ret {
+ return
+ }
+ ret = resolver.loadTree(block)
+ if nil != ret {
+ resolver.treeCache[key] = ret
+ }
+ return
+}
+
+func documentStatEmbedStatement(embed *ast.Node) (stmt string, ok bool) {
+ if nil == embed {
+ return
+ }
+ script := embed.ChildByType(ast.NodeBlockQueryEmbedScript)
+ if nil == script {
+ return
+ }
+ stmt = stdhtml.UnescapeString(script.TokensStr())
+ stmt = strings.ReplaceAll(stmt, editor.IALValEscNewLine, "\n")
+ ok = true
+ return
+}
+
+func documentStatHeadingMode(embed *ast.Node) (ret int) {
+ if nil != Conf && nil != Conf.Editor {
+ ret = Conf.Editor.HeadingEmbedMode
+ }
+ if nil == embed {
+ return
+ }
+ if customMode := embed.IALAttr("custom-heading-mode"); "" != customMode {
+ if mode, err := strconv.Atoi(customMode); nil == err && 0 <= mode && mode <= 2 {
+ ret = mode
+ }
+ }
+ return
+}
+
+func containsQueryEmbed(nodes []*ast.Node) (ret bool) {
+ for _, node := range nodes {
+ if nil == node {
+ continue
+ }
+ ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if entering && ast.NodeBlockQueryEmbed == n.Type {
+ ret = true
+ return ast.WalkStop
+ }
+ return ast.WalkContinue
+ })
+ if ret {
+ return
+ }
+ }
+ return
+}
+
+func addBlockStat(target, addition *util.BlockStatResult) {
+ if nil == target || nil == addition {
+ return
+ }
+ target.RuneCount += addition.RuneCount
+ target.WordCount += addition.WordCount
+ target.LinkCount += addition.LinkCount
+ target.ImageCount += addition.ImageCount
+ target.RefCount += addition.RefCount
+ target.BlockCount += addition.BlockCount
+}
+
+func documentStatTreeCacheKey(boxID, rootID string) string {
+ return boxID + "\x00" + rootID
+}
diff --git a/kernel/model/document_stat_test.go b/kernel/model/document_stat_test.go
new file mode 100644
index 0000000000..5e95c46768
--- /dev/null
+++ b/kernel/model/document_stat_test.go
@@ -0,0 +1,248 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import (
+ "context"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/parse"
+ "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/util"
+)
+
+func TestDocumentEmbedStatCountsRepeatedResults(t *testing.T) {
+ setDocumentStatTestConf(t)
+
+ embed := documentStatTestEmbed("20260813120000-embed01", "query")
+ hostTree := documentStatTestTree("20260813120000-host001", embed)
+ paragraph := documentStatTestParagraph("20260813120000-para001", "hello world")
+ resultTree := documentStatTestTree("20260813120000-doc0001", paragraph)
+ loadCount := 0
+ info := &EmbedStat{Complete: true}
+ stat := filesys.StatTreeFromTree(hostTree)
+ resolver := documentStatTestResolver(hostTree, stat, info)
+ resolver.queryBlocks = func(_ context.Context, stmt string, limit int, boxID string) ([]*sql.Block, bool, error) {
+ if "query" != stmt || 64 != limit || "" != boxID {
+ t.Fatalf("查询参数不正确:stmt=%q limit=%d boxID=%q", stmt, limit, boxID)
+ }
+ block := &sql.Block{ID: paragraph.ID, RootID: resultTree.Root.ID, Box: resultTree.Box, Type: "p"}
+ return []*sql.Block{block, block}, false, nil
+ }
+ resolver.loadTree = func(_ *sql.Block) *parse.Tree {
+ loadCount++
+ return resultTree
+ }
+
+ resolver.resolveNodes(hostTree, []*ast.Node{hostTree.Root}, 0)
+
+ if 4 != stat.WordCount || 20 != stat.RuneCount {
+ t.Fatalf("重复显示的结果应重复统计:%+v", stat)
+ }
+ if 3 != stat.BlockCount {
+ t.Fatalf("块数量不正确:%d", stat.BlockCount)
+ }
+ if 1 != info.QueryEmbedCount || 2 != info.ResultCount || !info.Complete {
+ t.Fatalf("嵌入统计元数据不正确:%+v", info)
+ }
+ if 1 != loadCount {
+ t.Fatalf("同一文档应仅加载一次,实际加载 %d 次", loadCount)
+ }
+}
+
+func TestDocumentEmbedStatMarksJSEmbedIncomplete(t *testing.T) {
+ setDocumentStatTestConf(t)
+
+ embed := documentStatTestEmbed("20260813120001-embed02", "//!js\nreturn [];")
+ hostTree := documentStatTestTree("20260813120001-host002", embed)
+ info := &EmbedStat{Complete: true}
+ stat := filesys.StatTreeFromTree(hostTree)
+ resolver := documentStatTestResolver(hostTree, stat, info)
+ resolver.queryBlocks = func(context.Context, string, int, string) ([]*sql.Block, bool, error) {
+ t.Fatal("JavaScript 嵌入不应执行 SQL 查询")
+ return nil, false, nil
+ }
+
+ resolver.resolveNodes(hostTree, []*ast.Node{hostTree.Root}, 0)
+
+ if info.Complete || 1 != info.JSEmbedCount || 0 != info.QueryEmbedCount {
+ t.Fatalf("JavaScript 嵌入应标记为部分统计:%+v", info)
+ }
+}
+
+func TestDocumentEmbedStatFiltersInaccessibleResults(t *testing.T) {
+ setDocumentStatTestConf(t)
+
+ embed := documentStatTestEmbed("20260813120005-embed05", "query")
+ hostTree := documentStatTestTree("20260813120005-host004", embed)
+ paragraph := documentStatTestParagraph("20260813120005-para003", "hidden content")
+ resultTree := documentStatTestTree("20260813120005-doc0003", paragraph)
+ info := &EmbedStat{Complete: true}
+ stat := filesys.StatTreeFromTree(hostTree)
+ resolver := documentStatTestResolver(hostTree, stat, info)
+ resolver.accessChecker = func(string) bool {
+ return false
+ }
+ resolver.queryBlocks = func(context.Context, string, int, string) ([]*sql.Block, bool, error) {
+ return []*sql.Block{{ID: paragraph.ID, RootID: resultTree.Root.ID, Type: "p"}}, false, nil
+ }
+ resolver.loadTree = func(*sql.Block) *parse.Tree {
+ t.Fatal("无权限的查询结果不应加载文档树")
+ return nil
+ }
+
+ resolver.resolveNodes(hostTree, []*ast.Node{hostTree.Root}, 0)
+
+ if 0 != stat.WordCount || 0 != info.ResultCount || !info.Complete {
+ t.Fatalf("无权限的查询结果不应计入统计:stat=%+v info=%+v", stat, info)
+ }
+}
+
+func TestDocumentEmbedStatMarksTruncatedQueryIncomplete(t *testing.T) {
+ setDocumentStatTestConf(t)
+
+ embed := documentStatTestEmbed("20260813120006-embed06", "query")
+ hostTree := documentStatTestTree("20260813120006-host005", embed)
+ paragraph := documentStatTestParagraph("20260813120006-para004", "visible content")
+ resultTree := documentStatTestTree("20260813120006-doc0004", paragraph)
+ info := &EmbedStat{Complete: true}
+ stat := filesys.StatTreeFromTree(hostTree)
+ resolver := documentStatTestResolver(hostTree, stat, info)
+ resolver.queryBlocks = func(context.Context, string, int, string) ([]*sql.Block, bool, error) {
+ return []*sql.Block{{ID: paragraph.ID, RootID: resultTree.Root.ID, Type: "p"}}, true, nil
+ }
+ resolver.loadTree = func(*sql.Block) *parse.Tree {
+ return resultTree
+ }
+
+ resolver.resolveNodes(hostTree, []*ast.Node{hostTree.Root}, 0)
+
+ if info.Complete || 1 != info.TruncatedQueryCount || 1 != info.ResultCount {
+ t.Fatalf("截断查询应保留已计结果并标记为部分统计:%+v", info)
+ }
+}
+
+func TestDocumentEmbedStatDetectsCycles(t *testing.T) {
+ setDocumentStatTestConf(t)
+
+ firstEmbed := documentStatTestEmbed("20260813120002-embed03", "to-b")
+ hostContainer := &ast.Node{Type: ast.NodeSuperBlock, ID: "20260813120002-super01"}
+ hostContainer.AppendChild(firstEmbed)
+ hostTree := documentStatTestTree("20260813120002-host003", hostContainer)
+
+ secondEmbed := documentStatTestEmbed("20260813120003-embed04", "to-a")
+ resultTree := documentStatTestTree("20260813120003-doc0002", secondEmbed)
+ info := &EmbedStat{Complete: true}
+ stat := filesys.StatTreeFromTree(hostTree)
+ resolver := documentStatTestResolver(hostTree, stat, info)
+ resolver.queryBlocks = func(_ context.Context, stmt string, _ int, _ string) ([]*sql.Block, bool, error) {
+ if "to-b" == stmt {
+ return []*sql.Block{{ID: resultTree.Root.ID, RootID: resultTree.Root.ID, Type: "d"}}, false, nil
+ }
+ return []*sql.Block{{ID: hostContainer.ID, RootID: hostTree.Root.ID, Type: "s"}}, false, nil
+ }
+ resolver.loadTree = func(block *sql.Block) *parse.Tree {
+ if block.RootID == resultTree.Root.ID {
+ return resultTree
+ }
+ return hostTree
+ }
+
+ resolver.resolveNodes(hostTree, []*ast.Node{hostTree.Root}, 0)
+
+ if info.Complete || 1 != info.CycleCount {
+ t.Fatalf("循环嵌入应终止并标记为部分统计:%+v", info)
+ }
+ if 3 != info.QueryEmbedCount || 2 != info.ResultCount {
+ t.Fatalf("循环前的结果统计不正确:%+v", info)
+ }
+}
+
+func TestEmbeddedBlockNodesUsesHeadingMode(t *testing.T) {
+ heading := &ast.Node{Type: ast.NodeHeading, ID: "20260813120004-heading", HeadingLevel: 2}
+ paragraph := documentStatTestParagraph("20260813120004-para002", "content")
+ nextHeading := &ast.Node{Type: ast.NodeHeading, ID: "20260813120004-heading2", HeadingLevel: 2}
+ root := &ast.Node{Type: ast.NodeDocument}
+ root.AppendChild(heading)
+ root.AppendChild(paragraph)
+ root.AppendChild(nextHeading)
+
+ if nodes := embeddedBlockNodes(heading, 0); 2 != len(nodes) || nodes[0] != heading || nodes[1] != paragraph {
+ t.Fatalf("标题及下方块模式不正确:%v", nodes)
+ }
+ if nodes := embeddedBlockNodes(heading, 1); 1 != len(nodes) || nodes[0] != heading {
+ t.Fatalf("仅标题模式不正确:%v", nodes)
+ }
+ if nodes := embeddedBlockNodes(heading, 2); 1 != len(nodes) || nodes[0] != paragraph {
+ t.Fatalf("仅标题下方块模式不正确:%v", nodes)
+ }
+
+ heading.SetIALAttr("fold", "1")
+ if nodes := embeddedBlockNodes(heading, 2); 0 != len(nodes) {
+ t.Fatalf("折叠标题不应返回下方块:%v", nodes)
+ }
+}
+
+func documentStatTestResolver(tree *parse.Tree, stat *util.BlockStatResult, info *EmbedStat) *documentEmbedStatResolver {
+ return &documentEmbedStatResolver{
+ ctx: context.Background(),
+ hostRootID: tree.Root.ID,
+ queryLimit: 64,
+ treeCache: map[string]*parse.Tree{
+ documentStatTreeCacheKey(tree.Box, tree.Root.ID): tree,
+ },
+ path: map[string]bool{},
+ stat: stat,
+ info: info,
+ validate: func(string, string) error {
+ return nil
+ },
+ }
+}
+
+func setDocumentStatTestConf(t *testing.T) {
+ previousConf := Conf
+ Conf = NewAppConf()
+ Conf.Editor = conf.NewEditor()
+ Conf.Search = conf.NewSearch()
+ t.Cleanup(func() {
+ Conf = previousConf
+ })
+}
+
+func documentStatTestTree(rootID string, blocks ...*ast.Node) *parse.Tree {
+ root := &ast.Node{Type: ast.NodeDocument, ID: rootID}
+ for _, block := range blocks {
+ root.AppendChild(block)
+ }
+ return &parse.Tree{Root: root, Box: "20260813120000-box0001"}
+}
+
+func documentStatTestEmbed(id, stmt string) *ast.Node {
+ embed := &ast.Node{Type: ast.NodeBlockQueryEmbed, ID: id}
+ embed.AppendChild(&ast.Node{Type: ast.NodeBlockQueryEmbedScript, Tokens: []byte(stmt)})
+ return embed
+}
+
+func documentStatTestParagraph(id, content string) *ast.Node {
+ paragraph := &ast.Node{Type: ast.NodeParagraph, ID: id}
+ paragraph.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(content)})
+ return paragraph
+}
diff --git a/kernel/sql/encrypted_query.go b/kernel/sql/encrypted_query.go
index ee199a26bc..e45aa76031 100644
--- a/kernel/sql/encrypted_query.go
+++ b/kernel/sql/encrypted_query.go
@@ -20,6 +20,7 @@ import (
"bytes"
"context"
"database/sql"
+ "errors"
"math"
"regexp"
"strconv"
@@ -176,6 +177,31 @@ func SelectBlocksRawStmtInBoxContext(ctx context.Context, stmt string, page, lim
return
}
+// SelectBlocksRawStmtBoundedInBoxContext 执行原始块查询,并无条件限制返回行数。
+func SelectBlocksRawStmtBoundedInBoxContext(ctx context.Context, stmt string, limit int, boxID string) (ret []*Block, truncated bool, err error) {
+ rows, err := queryForBoxContext(ctx, boxID, stmt)
+ if nil != err {
+ return nil, false, err
+ }
+ defer rows.Close()
+
+ for rows.Next() {
+ if limit <= len(ret) {
+ truncated = true
+ break
+ }
+ block := scanBlockRows(rows)
+ if nil == block {
+ return nil, false, errors.New("query result columns do not match blocks")
+ }
+ ret = append(ret, block)
+ }
+ if err = rows.Err(); nil != err {
+ return nil, false, err
+ }
+ return
+}
+
// QueryRefCountInBox 按 defBlockIDs 在指定 box 的 db 里查引用计数。
func QueryRefCountInBox(defIDs []string, boxID string) (ret map[string]int) {
ret = map[string]int{}
diff --git a/kernel/sql/encrypted_query_test.go b/kernel/sql/encrypted_query_test.go
index 30fb403d0c..bcff5d2457 100644
--- a/kernel/sql/encrypted_query_test.go
+++ b/kernel/sql/encrypted_query_test.go
@@ -204,6 +204,29 @@ func TestSelectBlocksRawStmtInBoxPaginatesExistingLimit(t *testing.T) {
}
}
+func TestSelectBlocksRawStmtBoundedInBoxContext(t *testing.T) {
+ testDB, boxID := useEncryptedQueryTestDB(t)
+ for i := 1; i <= 3; i++ {
+ id := fmt.Sprintf("block-%02d", i)
+ insertEncryptedQueryTestBlock(t, testDB, id, "", id, "d")
+ }
+
+ blocks, truncated, err := SelectBlocksRawStmtBoundedInBoxContext(
+ context.Background(), "SELECT * FROM blocks ORDER BY id", 2, boxID)
+ if nil != err {
+ t.Fatalf("bounded block query failed: %s", err)
+ }
+ if !truncated || 2 != len(blocks) || "block-01" != blocks[0].ID || "block-02" != blocks[1].ID {
+ t.Fatalf("unexpected bounded query result: blocks=%#v truncated=%v", blocks, truncated)
+ }
+
+ blocks, truncated, err = SelectBlocksRawStmtBoundedInBoxContext(
+ context.Background(), "SELECT * FROM blocks ORDER BY id", 3, boxID)
+ if nil != err || truncated || 3 != len(blocks) {
+ t.Fatalf("exactly bounded query should not be truncated: blocks=%#v truncated=%v err=%v", blocks, truncated, err)
+ }
+}
+
func TestQueryNoLimitInBoxContextCancellation(t *testing.T) {
testDB, boxID := useEncryptedQueryTestDB(t)
previousDB := db