Skip to content

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

:bug: Keep automatic heading numbers up to date https://github.com/siyuan-note/siyuan/issues/522

Daniel66b22234abcf
diff --git a/app/src/config/tabs/editorRuntime.ts b/app/src/config/tabs/editorRuntime.ts
index b2bff6d348..640ad86b6b 100644
--- a/app/src/config/tabs/editorRuntime.ts
+++ b/app/src/config/tabs/editorRuntime.ts
@@ -1,6 +1,6 @@
import {Constants} from "../../constants";
import {getAllEditor, getAllModels} from "../../layout/getAll";
-import {setInlineStyle} from "../../util/assets";
+import {refreshHeadingNumberMeasurements, setInlineStyle} from "../../util/assets";
import {reloadProtyle} from "../../protyle/util/reload";
import {resize} from "../../protyle/util/resize";
import {createConfigNamespaceApi} from "../util/namespaceApi";
@@ -8,6 +8,9 @@ import {createConfigNamespaceApi} from "../util/namespaceApi";
const applyEditorConfig = (data: Config.IEditor) => {
const refreshHeadingNumbers = window.siyuan.config.editor.headingNumber !== data.headingNumber ||
window.siyuan.config.editor.headingNumberFormat !== data.headingNumberFormat;
+ const remeasureHeadingNumbers = window.siyuan.config.editor.fontSize !== data.fontSize ||
+ window.siyuan.config.editor.fontFamily !== data.fontFamily ||
+ window.siyuan.config.editor.fontWeight !== data.fontWeight;
window.siyuan.config.editor = data;
const models = getAllModels();
models.editor.forEach(item => item.updateBacklinkPanel());
@@ -37,7 +40,11 @@ const applyEditorConfig = (data: Config.IEditor) => {
/// #endif
}
- void setInlineStyle();
+ void setInlineStyle().then(() => {
+ if (remeasureHeadingNumbers && data.headingNumber) {
+ refreshHeadingNumberMeasurements();
+ }
+ });
};
/** 编辑器命名空间:设置面板注册项 save、设置面板外入口共用 */
diff --git a/app/src/config/util/snippets.ts b/app/src/config/util/snippets.ts
index 29195065ec..f6f901fabd 100644
--- a/app/src/config/util/snippets.ts
+++ b/app/src/config/util/snippets.ts
@@ -3,9 +3,11 @@ import {Dialog} from "../../dialog";
import {isMobile, objEquals} from "../../util/functions";
import {confirmDialog} from "../../dialog/confirmDialog";
import {Constants} from "../../constants";
+import {refreshHeadingNumberMeasurements} from "../../util/assets";
export const renderSnippet = () => {
fetchPost("/api/snippet/getSnippet", {type: "all", enabled: 2}, (response) => {
+ let cssChanged = false;
response.data.snippets.forEach((item: ISnippet) => {
const id = `snippet${item.type === "css" ? "CSS" : "JS"}${item.id}`;
let exitElement = document.getElementById(id) as HTMLScriptElement | HTMLStyleElement;
@@ -13,12 +15,14 @@ export const renderSnippet = () => {
(!window.siyuan.config.snippet.enabledJS && item.type === "js")) {
if (exitElement) {
exitElement.remove();
+ cssChanged = cssChanged || item.type === "css";
}
return;
}
if (!item.enabled) {
if (exitElement) {
exitElement.remove();
+ cssChanged = cssChanged || item.type === "css";
}
return;
}
@@ -27,12 +31,14 @@ export const renderSnippet = () => {
return;
}
exitElement.remove();
+ cssChanged = cssChanged || item.type === "css";
}
if (item.type === "css") {
const styleEl = document.createElement("style");
styleEl.id = id;
styleEl.textContent = item.content;
document.head.appendChild(styleEl);
+ cssChanged = true;
} else if (item.type === "js") {
exitElement = document.createElement("script");
exitElement.type = "text/javascript";
@@ -41,6 +47,9 @@ export const renderSnippet = () => {
document.head.appendChild(exitElement);
}
});
+ if (cssChanged) {
+ refreshHeadingNumberMeasurements();
+ }
});
};
@@ -212,12 +221,17 @@ const genSnippet = (options: ISnippet) => {
const setSnippetPost = (dialog: Dialog, snippets: ISnippet[], removeIds: string[]) => {
fetchPost("/api/snippet/setSnippet", {snippets}, () => {
+ let cssChanged = false;
removeIds.forEach(item => {
const rmElement = document.querySelector(item);
if (rmElement) {
rmElement.remove();
+ cssChanged = cssChanged || item.startsWith("#snippetCSS");
}
});
+ if (cssChanged) {
+ refreshHeadingNumberMeasurements();
+ }
window.siyuan.config.snippet.enabledCSS = (dialog.element.querySelector('.b3-switch[data-action="toggleCSS"]') as HTMLInputElement).checked;
window.siyuan.config.snippet.enabledJS = (dialog.element.querySelector('.b3-switch[data-action="toggleJS"]') as HTMLInputElement).checked;
fetchPost("/api/setting/setSnippet", window.siyuan.config.snippet);
diff --git a/app/src/layout/dock/Outline.ts b/app/src/layout/dock/Outline.ts
index 08b4aa3634..905ca8b38d 100644
--- a/app/src/layout/dock/Outline.ts
+++ b/app/src/layout/dock/Outline.ts
@@ -30,6 +30,7 @@ import {genEmptyElement} from "../../block/util";
import {focusBlock, focusByWbr} from "../../protyle/util/selection";
import {dragOverScroll, stopScrollAnimation} from "../../boot/globalEvent/dragover";
import {getDocDisplayName} from "../../util/pathName";
+import {operationsMayChangeOutline} from "../../protyle/util/headingNumberCore";
export class Outline extends Model {
public tree: Tree;
@@ -312,7 +313,12 @@ export class Outline extends Model {
if (isEncryptedBox(notebookId)) {
outlineParam.notebook = notebookId;
}
+ const refreshId = ++this.refreshId;
+ const blockId = this.blockId;
fetchPost("/api/outline/getDocOutline", outlineParam, response => {
+ if (refreshId !== this.refreshId || blockId !== this.blockId) {
+ return;
+ }
this.update(response);
if (this.blockId) {
this.updateDocTitle((options.tab.model as Editor)?.editor?.protyle?.background?.ial, response.data?.length || 0);
@@ -546,29 +552,12 @@ export class Outline extends Model {
if (data.data.rootID !== this.blockId) {
return;
}
- let needReload = false;
const ops = data.data.sources[0];
- ops.doOperations.find((item: IOperation) => {
- if (item.action === "update" &&
- (this.element.querySelector(`.b3-list-item[data-node-id="${item.id}"]`) || item.data.indexOf('data-type="NodeHeading"') > -1)) {
- needReload = true;
- return true;
- } else if (item.action === "insert" && item.data.indexOf('data-type="NodeHeading"') > -1) {
- needReload = true;
- return true;
- } else if (item.action === "delete" || item.action === "move") {
- needReload = true;
- return true;
- }
- });
- if (!needReload && ops.undoOperations) {
- ops.undoOperations.find((item: IOperation) => {
- if (item.action === "update" && item.data?.indexOf('data-type="NodeHeading"') > -1) {
- needReload = true;
- return true;
- }
- });
- }
+ const headingIDs = new Set(Array.from(this.element.querySelectorAll<HTMLElement>(
+ ".b3-list-item[data-node-id]"
+ )).map(item => item.dataset.nodeId!));
+ const needReload = operationsMayChangeOutline(ops.doOperations, headingIDs) ||
+ operationsMayChangeOutline(ops.undoOperations, headingIDs);
if (needReload) {
const outlineParam: IObject = {
id: this.blockId,
@@ -585,9 +574,10 @@ export class Outline extends Model {
if (isEncryptedBox(notebookId)) {
outlineParam.notebook = notebookId;
}
+ const refreshId = ++this.refreshId;
fetchPost("/api/outline/getDocOutline", outlineParam, response => {
// 文档切换后不再更新原有推送 https://github.com/siyuan-note/siyuan/issues/13409
- if (data.data.rootID !== this.blockId) {
+ if (refreshId !== this.refreshId || data.data.rootID !== this.blockId) {
return;
}
this.update(response);
diff --git a/app/src/mobile/dock/MobileOutline.ts b/app/src/mobile/dock/MobileOutline.ts
index fb7318ff7e..ccc5478d7f 100644
--- a/app/src/mobile/dock/MobileOutline.ts
+++ b/app/src/mobile/dock/MobileOutline.ts
@@ -19,6 +19,7 @@ import {dragOverScroll, stopScrollAnimation} from "../../boot/globalEvent/dragov
import {escapeHtml} from "../../util/escape";
import {unicode2Emoji} from "../../emoji";
import {bindMousePointerTouchBridge, isMousePointerTouchEvent} from "../util/mousePointerTouchBridge";
+import {operationsMayChangeOutline} from "../../protyle/util/headingNumberCore";
export class MobileOutline extends Model {
public tree: Tree;
@@ -789,29 +790,12 @@ export class MobileOutline extends Model {
if (data.data.rootID !== this.blockId) {
return;
}
- let needReload = false;
const ops = data.data.sources[0];
- ops.doOperations.find((item: IOperation) => {
- if (item.action === "update" &&
- (this.element.querySelector(`.b3-list-item[data-node-id="${item.id}"]`) || item.data.indexOf('data-type="NodeHeading"') > -1)) {
- needReload = true;
- return true;
- } else if (item.action === "insert" && item.data.indexOf('data-type="NodeHeading"') > -1) {
- needReload = true;
- return true;
- } else if (item.action === "delete" || item.action === "move") {
- needReload = true;
- return true;
- }
- });
- if (!needReload && ops.undoOperations) {
- ops.undoOperations.find((item: IOperation) => {
- if (item.action === "update" && item.data?.indexOf('data-type="NodeHeading"') > -1) {
- needReload = true;
- return true;
- }
- });
- }
+ const headingIDs = new Set(Array.from(this.element.querySelectorAll<HTMLElement>(
+ ".b3-list-item[data-node-id]"
+ )).map(item => item.dataset.nodeId!));
+ const needReload = operationsMayChangeOutline(ops.doOperations, headingIDs) ||
+ operationsMayChangeOutline(ops.undoOperations, headingIDs);
if (needReload) {
this.reload(() => {
// https://github.com/siyuan-note/siyuan/issues/8372
diff --git a/app/src/protyle/util/headingNumber.test.ts b/app/src/protyle/util/headingNumber.test.ts
index 51051d6300..cf03f54fe3 100644
--- a/app/src/protyle/util/headingNumber.test.ts
+++ b/app/src/protyle/util/headingNumber.test.ts
@@ -2,7 +2,9 @@ import {describe, it} from "node:test";
import * as assert from "node:assert/strict";
import {
buildHeadingNumberStyles,
+ invalidateHeadingNumberMeasurements,
operationsMayChangeHeadingNumbers,
+ operationsMayChangeOutline,
renderHeadingNumberElements
} from "./headingNumberCore";
@@ -114,6 +116,11 @@ describe("renderHeadingNumbers", () => {
assert.equal(heading.appendCount, 1);
+ invalidateHeadingNumberMeasurements();
+ renderHeadingNumberElements(root as unknown as Element, {heading: "1"});
+
+ assert.equal(heading.appendCount, 2);
+
const emptyResult = renderHeadingNumberElements(root as unknown as Element, {});
assert.equal(heading.getAttribute("data-heading-number"), null);
@@ -196,3 +203,35 @@ describe("operationsMayChangeHeadingNumbers", () => {
assert.equal(changed, true);
});
});
+
+describe("operationsMayChangeOutline", () => {
+ it("API 更新容器并移除标题时刷新大纲", () => {
+ const changed = operationsMayChangeOutline([{
+ action: "update",
+ id: "list-item",
+ data: '<div data-node-id="list-item" data-type="NodeListItem"></div>',
+ }]);
+
+ assert.equal(changed, true);
+ });
+
+ it("已有标题转换为普通块时刷新大纲", () => {
+ const changed = operationsMayChangeOutline([{
+ action: "update",
+ id: "heading",
+ data: '<div data-node-id="heading" data-type="NodeParagraph"></div>',
+ }], new Set(["heading"]));
+
+ assert.equal(changed, true);
+ });
+
+ it("普通块内容更新时不刷新大纲", () => {
+ const changed = operationsMayChangeOutline([{
+ action: "update",
+ id: "paragraph",
+ data: '<div data-node-id="paragraph" data-type="NodeParagraph"></div>',
+ }]);
+
+ assert.equal(changed, false);
+ });
+});
diff --git a/app/src/protyle/util/headingNumberCore.ts b/app/src/protyle/util/headingNumberCore.ts
index a6102f284a..25eb8623b2 100644
--- a/app/src/protyle/util/headingNumberCore.ts
+++ b/app/src/protyle/util/headingNumberCore.ts
@@ -6,7 +6,7 @@ const HEADING_NUMBER_WIDTH_PROPERTY = "--b3-protyle-heading-number-width";
const NUMBERED_HEADING_SELECTOR = `${HEADING_SELECTOR}[data-heading-number], ` +
`${HEADING_SELECTOR} > [contenteditable][data-heading-number]`;
const HEADING_CONTAINER_TYPES = new Set(["NodeDocument", "NodeList", "NodeListItem", "NodeSuperBlock"]);
-const headingNumberMeasurements = new WeakMap<Element, {key: string, offset: string}>();
+let headingNumberMeasurements = new WeakMap<Element, {key: string, offset: string}>();
export interface IHeadingNumberStyle {
id: string;
@@ -18,6 +18,10 @@ interface IHeadingNumberTarget extends IHeadingNumberStyle {
element: Element;
}
+export const invalidateHeadingNumberMeasurements = () => {
+ headingNumberMeasurements = new WeakMap<Element, {key: string, offset: string}>();
+};
+
export const clearHeadingNumberElements = (root: Element) => {
root.querySelectorAll(NUMBERED_HEADING_SELECTOR).forEach(item => {
item.removeAttribute("data-heading-number");
@@ -197,6 +201,20 @@ const operationDataIsHeadingContainer = (data: unknown) => {
return match ? HEADING_CONTAINER_TYPES.has(match[2]) : false;
};
+export const operationsMayChangeOutline = (operations: IOperation[] = [], headingIDs: Set<string> = new Set()) => {
+ return operations.some(operation => {
+ if (["append", "delete", "move", "moveOutlineHeading"].includes(operation.action)) {
+ return true;
+ }
+ if (operation.action === "update" && operation.id && headingIDs.has(operation.id)) {
+ return true;
+ }
+ return ["appendInsert", "insert", "prependInsert", "update"].includes(operation.action) &&
+ (operationDataHasHeading(operation.data) ||
+ (operation.action === "update" && operationDataIsHeadingContainer(operation.data)));
+ });
+};
+
export const operationsMayChangeHeadingNumbers = (
operations: IOperation[],
headingNumbers: Record<string, string> = {},
diff --git a/app/src/util/assets.ts b/app/src/util/assets.ts
index 925d25c968..7c617957e1 100644
--- a/app/src/util/assets.ts
+++ b/app/src/util/assets.ts
@@ -1,8 +1,10 @@
import {Constants} from "../constants";
import {addScript} from "../protyle/util/addScript";
import {addStyle} from "../protyle/util/addStyle";
+import {getAllEditor, getAllModels} from "../layout/getAll";
+import {invalidateHeadingNumberMeasurements} from "../protyle/util/headingNumberCore";
+import {renderHeadingNumbers} from "../protyle/util/headingNumber";
/// #if !MOBILE
-import {getAllModels} from "../layout/getAll";
import {exportLayout} from "../layout/util";
/// #endif
import {fetchPost} from "./fetch";
@@ -20,7 +22,31 @@ import {setCodeTheme} from "../protyle/render/util";
import {getBackend, getFrontend} from "./functions";
import {getWorkspaceName} from "./processTitle";
+let headingNumberMeasurementRefreshTimer: number;
+
+export const refreshHeadingNumberMeasurements = () => {
+ invalidateHeadingNumberMeasurements();
+ if (!window.siyuan.config.editor.headingNumber) {
+ return;
+ }
+ getAllEditor().forEach(item => renderHeadingNumbers(item.protyle));
+};
+
+const scheduleHeadingNumberMeasurementRefresh = (styleElements: HTMLLinkElement[]) => {
+ const schedule = (delay = 0) => {
+ window.clearTimeout(headingNumberMeasurementRefreshTimer);
+ headingNumberMeasurementRefreshTimer = window.setTimeout(refreshHeadingNumberMeasurements, delay);
+ };
+ styleElements.forEach(item => {
+ item.addEventListener("load", () => schedule(), {once: true});
+ item.addEventListener("error", () => schedule(), {once: true});
+ });
+ schedule(styleElements.length > 0 ? Constants.TIMEOUT_LOAD : 0);
+};
+
export const loadAssets = (data: Config.IAppearance) => {
+ const changedThemeStyleElements: HTMLLinkElement[] = [];
+ let themeStylesChanged = false;
const htmlElement = document.getElementsByTagName("html")[0];
htmlElement.setAttribute("lang", window.siyuan.config.appearance.lang);
htmlElement.setAttribute("data-frontend", getFrontend()); // https://github.com/siyuan-note/siyuan/issues/12549
@@ -41,6 +67,8 @@ export const loadAssets = (data: Config.IAppearance) => {
if (defaultStyleElement) {
if (!defaultStyleElement.getAttribute("href").startsWith(defaultThemeAddress)) {
const newStyleElement = document.createElement("link");
+ changedThemeStyleElements.push(newStyleElement);
+ themeStylesChanged = true;
// 等待新样式表加载完成再移除旧样式表
new Promise((resolve) => {
newStyleElement.rel = "stylesheet";
@@ -54,19 +82,29 @@ export const loadAssets = (data: Config.IAppearance) => {
}
} else {
addStyle(defaultThemeAddress, "themeDefaultStyle");
+ changedThemeStyleElements.push(document.getElementById("themeDefaultStyle") as HTMLLinkElement);
+ themeStylesChanged = true;
}
const styleElement = document.getElementById("themeStyle");
if ((data.mode === 1 && data.themeDark !== "midnight") || (data.mode === 0 && data.themeLight !== "daylight")) {
const themeAddress = `/appearance/themes/${data.mode === 1 ? data.themeDark : data.themeLight}/theme.css?v=${data.themeVer}`;
if (styleElement) {
if (!styleElement.getAttribute("href").startsWith(themeAddress)) {
+ changedThemeStyleElements.push(styleElement as HTMLLinkElement);
+ themeStylesChanged = true;
styleElement.setAttribute("href", themeAddress);
}
} else {
addStyle(themeAddress, "themeStyle");
+ changedThemeStyleElements.push(document.getElementById("themeStyle") as HTMLLinkElement);
+ themeStylesChanged = true;
}
} else if (styleElement) {
styleElement.remove();
+ themeStylesChanged = true;
+ }
+ if (themeStylesChanged) {
+ scheduleHeadingNumberMeasurementRefresh(changedThemeStyleElements);
}
/// #if !MOBILE
getAllModels().graph.forEach(item => {