An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Sync outline heading when switching document tabs https://github.com/siyuan-note/siyuan/issues/20130
Daniel3c677c04433d
diff --git a/app/src/editor/outlineCurrent.test.ts b/app/src/editor/outlineCurrent.test.tsnew file mode 100644index 0000000000..b07980f9fb--- /dev/null+++ b/app/src/editor/outlineCurrent.test.ts@@ -0,0 +1,306 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {createSourceFile, isClassDeclaration, isVariableStatement, ScriptTarget, transpileModule} from "typescript";++const source = createSourceFile("util.ts", readFileSync("src/editor/util.ts", "utf8"), ScriptTarget.ES2021, true);+const declarations = source.statements.filter(statement => isVariableStatement(statement) &&+ statement.declarationList.declarations.some(item =>+ ["outlineRequests", "syncOutlineCurrent", "updateOutline"].includes(item.name.getText(source))));+const compiled = transpileModule(declarations.map(item => item.getText(source).replace(/^export /, "")).join("\n") ++ "\nglobalThis.update = updateOutline;", {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;++const makeProtyle = (rootID = "doc") => {+ const block = {id: rootID + "-heading"};+ const end = {id: "end"};+ const nodes = new Set([block, end]);+ const title = {id: "title"};+ return {+ block: {rootID},+ element: {isConnected: true, classList: {contains: () => false},+ contains: (node: unknown) => node === title || nodes.has(node as typeof block)},+ title: {editElement: title},+ notebookId: "box",+ background: {ial: {}},+ toolbar: {range: {startContainer: block, endContainer: end}},+ wysiwyg: {element: {contains: (node: unknown) => nodes.has(node as typeof block)}},+ preview: {element: {classList: {contains: () => true}}},+ };+};++const setup = () => {+ const requests: {params: any, callback: (response: any) => void}[] = [];+ const currents: unknown[] = [];+ const updates: string[] = [];+ let invalidations = 0;+ let selected: {startContainer: unknown, endContainer: unknown};+ const outline = {+ blockId: "doc", isPreview: false, type: "pin",+ invalidateCurrent: () => { invalidations++; },+ setCurrent: (block: unknown) => currents.push(block),+ update: (_response: unknown, id: string) => { outline.blockId = id; updates.push(id); },+ updateDocTitle: () => {},+ };+ const context: any = {+ getSelection: () => ({rangeCount: selected ? 1 : 0, getRangeAt: () => selected}),+ hasClosestByAttribute: (node: unknown) => node,+ isEncryptedBox: () => false,+ isCurrentEditor: () => true,+ fetchPost: (_url: string, params: unknown, callback: (response: unknown) => void) => requests.push({params, callback}),+ };+ runInNewContext(compiled, context);+ return {outline, requests, currents, updates, context,+ getInvalidations: () => invalidations,+ select: (range: typeof selected) => { selected = range; },+ update: (protyle?: ReturnType<typeof makeProtyle>, reload = false) => context.update({outline: [outline]}, protyle, reload),+ };+};++test("same-document tab switches sync each restored caret without refetching the outline", () => {+ const fixture = setup();+ const first = makeProtyle();+ const second = makeProtyle();+ for (const protyle of [first, second, first]) {+ fixture.select(protyle.toolbar.range);+ fixture.update(protyle);+ }+ assert.deepEqual(fixture.currents, [first.toolbar.range.startContainer, second.toolbar.range.startContainer,+ first.toolbar.range.startContainer]);+ assert.equal(fixture.requests.length, 0);+ assert.equal(fixture.getInvalidations(), 3);+});++test("a selection in another editor falls back to the target editor's saved range", () => {+ const fixture = setup();+ const target = makeProtyle();+ fixture.select(makeProtyle().toolbar.range);+ fixture.update(target);+ assert.equal(fixture.currents[0], target.toolbar.range.startContainer);+});++test("a cross-editor selection is rejected even when its start is inside the target", () => {+ const fixture = setup();+ const target = makeProtyle();+ fixture.select({startContainer: target.toolbar.range.startContainer, endContainer: {}});+ fixture.update(target);+ assert.equal(fixture.currents[0], target.toolbar.range.startContainer);+});++test("live target selection takes precedence over a different saved caret", () => {+ const fixture = setup();+ const target = makeProtyle();+ const end = target.toolbar.range.endContainer;+ fixture.select({startContainer: end, endContainer: end});+ fixture.update(target);+ assert.equal(fixture.currents[0], end);+});++test("an invalid saved range clears the current heading rather than using another editor", () => {+ const fixture = setup();+ const target = makeProtyle();+ target.toolbar.range = makeProtyle().toolbar.range;+ fixture.update(target);+ assert.deepEqual(fixture.currents, [undefined]);+ assert.equal(fixture.requests.length, 0);+});++test("a live selection in the document title clears the saved body heading", () => {+ const fixture = setup();+ const target = makeProtyle();+ fixture.select({startContainer: target.title.editElement, endContainer: target.title.editElement});+ fixture.update(target);+ assert.deepEqual(fixture.currents, [undefined]);+});++test("a new document refresh synchronizes its current heading after loading", () => {+ const fixture = setup();+ const target = makeProtyle("other");+ fixture.update(target);+ assert.equal(fixture.requests.length, 1);+ fixture.requests[0].callback({data: []});+ assert.deepEqual(fixture.updates, ["other"]);+ assert.equal(fixture.currents[0], target.toolbar.range.startContainer);+});++test("same-document switches invalidate a pending reload from another duplicate tab", () => {+ const fixture = setup();+ const first = makeProtyle();+ const second = makeProtyle();+ fixture.update(first, true);+ fixture.update(second);+ fixture.requests[0].callback({data: []});+ assert.equal(fixture.requests.length, 1);+ assert.deepEqual(fixture.updates, []);+ assert.deepEqual(fixture.currents, [second.toolbar.range.startContainer]);+});++test("returning to the original document rejects the intervening document's response", () => {+ const fixture = setup();+ fixture.update(makeProtyle("other"));+ const original = makeProtyle();+ fixture.update(original);+ fixture.requests[0].callback({data: []});+ assert.deepEqual(fixture.updates, []);+ assert.deepEqual(fixture.currents, [original.toolbar.range.startContainer]);+});++test("switching to preview invalidates pending editing responses without applying a caret highlight", () => {+ const fixture = setup();+ const target = makeProtyle();+ fixture.update(target, true);+ target.preview.element.classList.contains = () => false;+ fixture.update(target);+ fixture.requests[1].callback({data: []});+ fixture.requests[0].callback({data: []});+ assert.equal(fixture.outline.isPreview, true);+ assert.equal(fixture.updates.length, 1);+ assert.deepEqual(fixture.currents, []);+});++test("matching local outlines synchronize without requesting data for unrelated documents", () => {+ const fixture = setup();+ fixture.outline.type = "local";+ const target = makeProtyle();+ fixture.update(target);+ fixture.update(makeProtyle("other"));+ assert.deepEqual(fixture.currents, [target.toolbar.range.startContainer]);+ assert.equal(fixture.requests.length, 0);+ assert.equal(fixture.getInvalidations(), 1);+});++test("local editing outlines do not synchronize a preview tab's hidden saved body range", () => {+ const fixture = setup();+ fixture.outline.type = "local";+ const target = makeProtyle();+ target.preview.element.classList.contains = () => false;+ fixture.update(target);+ assert.deepEqual(fixture.currents, []);+ assert.equal(fixture.requests.length, 0);+});++for (const change of ["hidden", "detached", "non-editor", "mode"]) {+ test(`a pending pinned outline reload rejects a target that became ${change}`, () => {+ const fixture = setup();+ const target = makeProtyle();+ fixture.update(target, true);+ if (change === "hidden") {+ target.element.classList.contains = () => true;+ } else if (change === "detached") {+ target.element.isConnected = false;+ } else if (change === "non-editor") {+ fixture.context.isCurrentEditor = () => false;+ } else {+ target.preview.element.classList.contains = () => false;+ }+ fixture.requests[0].callback({data: []});+ assert.deepEqual(fixture.updates, []);+ assert.deepEqual(fixture.currents, []);+ });+}++test("closing the last editor clears outline data without accessing a missing editor", () => {+ const fixture = setup();+ fixture.update();+ fixture.context.isCurrentEditor = () => false;+ fixture.requests[0].callback({data: []});+ assert.deepEqual(fixture.updates, [""]);+});++const switchDeclaration = source.statements.find(statement => isVariableStatement(statement) &&+ statement.declarationList.declarations.some(item => item.name.getText(source) === "switchEditor"));+const switchCompiled = transpileModule(switchDeclaration.getText(source) + "\nglobalThis.switchEditor = switchEditor;", {+ compilerOptions: {target: ScriptTarget.ES2021},+}).outputText;++for (const action of ["focus", "highlight"]) {+ test(`outline navigation preserves the clicked heading after restoring the old caret (${action})`, () => {+ const fixture = setup();+ const protyle: any = makeProtyle();+ const clicked = {id: "clicked", clientHeight: 20};+ protyle.wysiwyg.element.querySelectorAll = () => [clicked];+ protyle.contentElement = {addEventListener() {}};+ protyle.element.addEventListener = () => {};+ const editor = {editor: {protyle}, parent: {headElement: {}, parent: {+ switchTab: () => fixture.update(protyle), showHeading() {},+ }}};+ Object.assign(fixture.context, {+ Constants: {CB_GET_FOCUS: "focus", CB_GET_HL: "highlight", CB_GET_OUTLINE: "outline"},+ isInEmbedBlock: () => false, revealTabsForTarget() {}, preventScroll() {}, highlightById() {},+ focusBlock: () => ({startContainer: clicked, endContainer: clicked}),+ scrollCenter() {}, ResizeObserver: class {observe() {} disconnect() {}}, AbortController,+ setTimeout() {}, isPhablet: () => action === "highlight", pushBackByEditor() {}, pushBack() {},+ hideElements() {}, updateOutlineCurrentBlock: (_protyle: unknown, node: unknown) => fixture.outline.setCurrent(node),+ });+ runInNewContext(switchCompiled, fixture.context);+ fixture.context.switchEditor(editor, {id: "clicked", rootID: "doc", action: [action, "outline"]}, {});+ assert.equal(fixture.currents.length, 2);+ assert.equal(fixture.currents[1], clicked);+ assert.equal(fixture.requests.length, 0);+ });+}++const outlineSource = createSourceFile("Outline.ts", readFileSync("src/layout/dock/Outline.ts", "utf8"), ScriptTarget.ES2021, true);+const outlineClass = outlineSource.statements.find(isClassDeclaration);+const methods = outlineClass.members.filter(member => ["setCurrent", "invalidateCurrent"].includes(member.name?.getText(outlineSource)));+const outlineCompiled = transpileModule(`class Harness {+ currentRequestID = 0; blockId = "doc"; highlights = [];+ getNotebookId() { return ""; }+ setCurrentById(id) { this.highlights.push(id); }+ ${methods.map(member => member.getText(outlineSource)).join("\n")}+}+globalThis.Harness = Harness;`, {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;++const outlineFixture = () => {+ const callbacks: ((response: any) => void)[] = [];+ const context: any = {+ hasClosestByClassName: () => false,+ getPreviousBlock: (): undefined => undefined,+ getAllModels: (): {editor: unknown[]} => ({editor: []}),+ fetchPost: (_url: string, _params: unknown, callback: (response: unknown) => void) => callbacks.push(callback),+ };+ runInNewContext(outlineCompiled, context);+ const node = (heading = false) => ({isConnected: true,+ getAttribute: (name: string) => name === "data-type" ? (heading ? "NodeHeading" : "NodeParagraph") : "heading"});+ return {outline: new context.Harness(), callbacks, node, context};+};++test("a new caret invalidates delayed breadcrumbs from a hidden but connected duplicate editor", async () => {+ const {outline, callbacks, node} = outlineFixture();+ await outline.setCurrent(node());+ outline.invalidateCurrent();+ await outline.setCurrent(node(true));+ callbacks[0]({data: [{type: "NodeHeading", id: "stale"}]});+ assert.deepEqual(Array.from(outline.highlights), ["heading"]);+});++test("clearing the caret cancels pending breadcrumbs and clears the old highlight", async () => {+ const {outline, callbacks, node} = outlineFixture();+ await outline.setCurrent(node());+ await outline.setCurrent(undefined);+ callbacks[0]({data: [{type: "NodeHeading", id: "stale"}]});+ assert.deepEqual(Array.from(outline.highlights), [""]);+});++test("a paragraph before any heading clears the previous heading highlight", async () => {+ const {outline, callbacks, node} = outlineFixture();+ await outline.setCurrent(node());+ callbacks[0]({data: [{type: "NodeDocument", id: "doc"}]});+ assert.deepEqual(Array.from(outline.highlights), [""]);+});++test("switching tabs while transactions settle cancels the old breadcrumb request before sending", async () => {+ const {outline, callbacks, node, context} = outlineFixture();+ let release: () => void;+ context.getAllModels = () => ({editor: [{editor: {protyle: {+ block: {rootID: "doc"}, wysiwyg: {element: {contains: () => true}},+ }}}]});+ context.waitForPendingTransactions = () => new Promise<void>(resolve => { release = resolve; });+ const pending = outline.setCurrent(node());+ outline.invalidateCurrent();+ await outline.setCurrent(node(true));+ release();+ await pending;+ assert.equal(callbacks.length, 0);+ assert.deepEqual(Array.from(outline.highlights), ["heading"]);+});diff --git a/app/src/editor/util.ts b/app/src/editor/util.tsindex 035aeb8c81..dcab7f4d39 100644--- a/app/src/editor/util.ts+++ b/app/src/editor/util.ts@@ -44,6 +44,8 @@ import {isHiddenTabContent} from "../protyle/render/tabsVisibility";import {confirmDialog} from "../dialog/confirmDialog";import {shouldCheckOtherWindows} from "./openFileWindow";import {getContenteditableElement} from "../protyle/wysiwyg/getBlock";+import type {Outline} from "../layout/dock/Outline";+import {updateOutlineCurrentBlock} from "../protyle/util/outlineBlock";const isSameCustomTab = (type: string, data: any, options: IOpenFileOptions) => {if (!options.custom || (options.custom.id && options.custom.id !== type)) {@@ -579,6 +581,9 @@ const switchEditor = (editor: Editor, options: IOpenFileOptions, allModels: IModscrollCenter(editor.editor.protyle, undefined, options.scrollPosition);}}+ if (nodeElement && options.action?.includes(Constants.CB_GET_OUTLINE)) {+ updateOutlineCurrentBlock(editor.editor.protyle, nodeElement as HTMLElement);+ }if (isPhablet()) {pushBackByEditor(editor.editor.protyle, nodeElement);} else {@@ -765,12 +770,36 @@ export const isCurrentEditor = (blockId: string) => {return false;};+const outlineRequests = new WeakMap<Outline, object>();++const syncOutlineCurrent = (outline: Outline, protyle: IProtyle) => {+ if (!protyle || outline.isPreview || !protyle.preview.element.classList.contains("fn__none") ||+ outline.blockId !== protyle.block?.rootID) {+ return;+ }+ const selection = getSelection();+ const selectedRange = selection.rangeCount > 0 ? selection.getRangeAt(0) : undefined;+ const range = selectedRange && protyle.element.contains(selectedRange.startContainer) &&+ protyle.element.contains(selectedRange.endContainer) ? selectedRange : protyle.toolbar.range;+ const currentElement = range && protyle.wysiwyg.element.contains(range.startContainer) &&+ protyle.wysiwyg.element.contains(range.endContainer) ?+ hasClosestByAttribute(range.startContainer, "data-node-id", null) : undefined;+ void outline.setCurrent(currentElement || undefined);+};+export const updateOutline = (models: IModels, protyle: IProtyle, reload = false) => {models.outline.find(item => {+ if (!reload && item.type === "local" && item.blockId !== protyle?.block?.rootID) {+ return;+ }+ const request = {};+ outlineRequests.set(item, request);+ item.invalidateCurrent();+ const isPreview = protyle ? !protyle.preview.element.classList.contains("fn__none") : false;if (reload ||(item.type === "pin" &&(!protyle || item.blockId !== protyle.block?.rootID ||- item.isPreview === protyle.preview.element.classList.contains("fn__none"))+ item.isPreview !== isPreview))) {let blockId = "";@@ -780,39 +809,33 @@ export const updateOutline = (models: IModels, protyle: IProtyle, reload = falseblockId = item.blockId;}}- if (blockId === item.blockId && !reload && item.isPreview !== protyle.preview.element.classList.contains("fn__none")) {- return;- }-const outlineParam: IObject = {id: blockId,- preview: !protyle.preview.element.classList.contains("fn__none")+ preview: isPreview};if (protyle && isEncryptedBox(protyle.notebookId)) {outlineParam.notebook = protyle.notebookId;}fetchPost("/api/outline/getDocOutline", outlineParam, response => {- if (!reload && (!isCurrentEditor(blockId) || item.blockId === blockId) &&- item.isPreview !== protyle.preview.element.classList.contains("fn__none")) {+ if (outlineRequests.get(item) !== request) {+ return;+ }+ if (protyle && (!protyle.element.isConnected ||+ isPreview === protyle.preview.element.classList.contains("fn__none") ||+ (item.type === "pin" && (protyle.element.classList.contains("fn__none") || !isCurrentEditor(blockId))))) {return;}- item.isPreview = !protyle.preview.element.classList.contains("fn__none");+ item.isPreview = isPreview;item.update(response, blockId, protyle?.notebookId || "");if (protyle) {item.updateDocTitle(protyle.background.ial, Array.isArray(response.data) ? response.data.length : 0);- if (getSelection().rangeCount > 0) {- const startContainer = getSelection().getRangeAt(0).startContainer;- if (protyle.wysiwyg.element.contains(startContainer)) {- const currentElement = hasClosestByAttribute(startContainer, "data-node-id", null);- if (currentElement) {- item.setCurrent(currentElement);- }- }- }+ syncOutlineCurrent(item, protyle);} else {item.updateDocTitle();}});+ } else {+ syncOutlineCurrent(item, protyle);}});};diff --git a/app/src/layout/dock/Outline.ts b/app/src/layout/dock/Outline.tsindex 6df3fc9e4e..4314b1232c 100644--- a/app/src/layout/dock/Outline.ts+++ b/app/src/layout/dock/Outline.ts@@ -572,9 +572,14 @@ export class Outline extends Model {}}+ public invalidateCurrent() {+ this.currentRequestID++;+ }+public async setCurrent(nodeElement: HTMLElement) {const requestID = ++this.currentRequestID;if (!nodeElement) {+ this.setCurrentById("");return;}if (nodeElement.getAttribute("data-type") === "NodeHeading" &&@@ -619,12 +624,8 @@ export class Outline extends Model {if (!isCurrent()) {return;}- response.data.reverse().find((item: IBreadcrumb) => {- if (item.type === "NodeHeading") {- this.setCurrentById(item.id);- return true;- }- });+ const heading = response.data.reverse().find((item: IBreadcrumb) => item.type === "NodeHeading");+ this.setCurrentById(heading?.id || "");});}}