Skip to content

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

:bug: Preserve outline selection during heading navigation https://github.com/siyuan-note/siyuan/issues/20541

101010zyl466df9917800
diff --git a/app/src/editor/outlineCurrent.test.ts b/app/src/editor/outlineCurrent.test.ts
index b07980f9fb..602773f1e0 100644
--- a/app/src/editor/outlineCurrent.test.ts
+++ b/app/src/editor/outlineCurrent.test.ts
@@ -16,10 +16,20 @@ const makeProtyle = (rootID = "doc") => {
const end = {id: "end"};
const nodes = new Set([block, end]);
const title = {id: "title"};
+ const listeners = new Map<string, Set<() => void>>();
return {
block: {rootID},
element: {isConnected: true, classList: {contains: () => false},
- contains: (node: unknown) => node === title || nodes.has(node as typeof block)},
+ contains: (node: unknown) => node === title || nodes.has(node as typeof block),
+ addEventListener: (type: string, callback: () => void, options?: {signal?: AbortSignal}) => {
+ if (!listeners.has(type)) {
+ listeners.set(type, new Set());
+ }
+ listeners.get(type).add(callback);
+ options?.signal?.addEventListener("abort", () => listeners.get(type).delete(callback));
+ }},
+ interact: (type: string) => listeners.get(type)?.forEach(callback => callback()),
+ activeListeners: () => Array.from(listeners.values()).reduce((count, callbacks) => count + callbacks.size, 0),
title: {editElement: title},
notebookId: "box",
background: {ial: {}},
@@ -32,6 +42,7 @@ const makeProtyle = (rootID = "doc") => {
const setup = () => {
const requests: {params: any, callback: (response: any) => void}[] = [];
const currents: unknown[] = [];
+ const explicitCurrents: {id: string, scroll: boolean}[] = [];
const updates: string[] = [];
let invalidations = 0;
let selected: {startContainer: unknown, endContainer: unknown};
@@ -39,21 +50,28 @@ const setup = () => {
blockId: "doc", isPreview: false, type: "pin",
invalidateCurrent: () => { invalidations++; },
setCurrent: (block: unknown) => currents.push(block),
+ setCurrentById: (id: string, scroll: boolean) => explicitCurrents.push({id, scroll}),
update: (_response: unknown, id: string) => { outline.blockId = id; updates.push(id); },
updateDocTitle: () => {},
};
const context: any = {
+ AbortController,
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}),
+ fetchPost: (_url: string, params: unknown, callback: (response: unknown) => void) =>
+ new Promise<void>(resolve => requests.push({params, callback: response => {
+ callback(response);
+ resolve();
+ }})),
};
runInNewContext(compiled, context);
- return {outline, requests, currents, updates, context,
+ return {outline, requests, currents, explicitCurrents, updates, context,
getInvalidations: () => invalidations,
select: (range: typeof selected) => { selected = range; },
- update: (protyle?: ReturnType<typeof makeProtyle>, reload = false) => context.update({outline: [outline]}, protyle, reload),
+ update: (protyle?: ReturnType<typeof makeProtyle>, reload = false, outlineId?: string) =>
+ context.update({outline: [outline]}, protyle, reload, outlineId),
};
};
@@ -71,6 +89,86 @@ test("same-document tab switches sync each restored caret without refetching the
assert.equal(fixture.getInvalidations(), 3);
});
+test("outline navigation selects an unloaded heading without following the old caret or scrolling", () => {
+ const fixture = setup();
+ const protyle = makeProtyle();
+ fixture.select(protyle.toolbar.range);
+ fixture.update(protyle, false, "unloaded-heading");
+ assert.deepEqual(fixture.currents, []);
+ assert.deepEqual(fixture.explicitCurrents, [{id: "unloaded-heading", scroll: false}]);
+ assert.equal(fixture.requests.length, 0);
+ assert.equal(fixture.getInvalidations(), 1);
+});
+
+test("a pinned outline reload retains the explicit navigation target instead of the restored caret", () => {
+ const fixture = setup();
+ const protyle = makeProtyle("other");
+ fixture.update(protyle, false, "unloaded-heading");
+ assert.equal(fixture.requests.length, 1);
+ fixture.requests[0].callback({data: []});
+ assert.deepEqual(fixture.updates, ["other"]);
+ assert.deepEqual(fixture.currents, []);
+ assert.deepEqual(fixture.explicitCurrents, [{id: "unloaded-heading", scroll: false}]);
+});
+
+for (const eventType of ["pointerdown", "keydown", "beforeinput"]) {
+ test(`interacting with the editor during a pinned outline reload follows the latest caret (${eventType})`, () => {
+ const fixture = setup();
+ const protyle = makeProtyle("other");
+ fixture.update(protyle, false, "clicked-heading");
+ const latest = protyle.toolbar.range.endContainer;
+ fixture.select({startContainer: latest, endContainer: latest});
+ protyle.interact(eventType);
+ fixture.requests[0].callback({data: []});
+ assert.deepEqual(fixture.updates, ["other"]);
+ assert.deepEqual(fixture.currents, [latest]);
+ assert.deepEqual(fixture.explicitCurrents, []);
+ });
+}
+
+test("restored focus preserves a pending outline target and completion removes input listeners", async () => {
+ const fixture = setup();
+ const protyle = makeProtyle("other");
+ fixture.update(protyle, false, "clicked-heading");
+ assert.equal(protyle.activeListeners(), 3);
+ protyle.interact("focusin");
+ assert.equal(protyle.activeListeners(), 3);
+ fixture.requests[0].callback({data: []});
+ await Promise.resolve();
+ assert.deepEqual(fixture.currents, []);
+ assert.deepEqual(fixture.explicitCurrents, [{id: "clicked-heading", scroll: false}]);
+ assert.equal(protyle.activeListeners(), 0);
+});
+
+test("a superseded outline request removes its listeners without removing the replacement's listeners", async () => {
+ const fixture = setup();
+ const first = makeProtyle("other");
+ const second = makeProtyle("other");
+ fixture.update(first, false, "first-heading");
+ fixture.update(second, false, "second-heading");
+ assert.equal(first.activeListeners(), 0);
+ assert.equal(second.activeListeners(), 3);
+ fixture.requests[0].callback({data: []});
+ await Promise.resolve();
+ assert.equal(second.activeListeners(), 3);
+ assert.deepEqual(fixture.explicitCurrents, []);
+ fixture.requests[1].callback({data: []});
+ await Promise.resolve();
+ assert.equal(second.activeListeners(), 0);
+ assert.deepEqual(fixture.explicitCurrents, [{id: "second-heading", scroll: false}]);
+});
+
+test("a newer outline navigation invalidates a pending reload's target", () => {
+ const fixture = setup();
+ const protyle = makeProtyle();
+ fixture.update(protyle, true, "first-heading");
+ fixture.update(protyle, false, "latest-heading");
+ fixture.requests[0].callback({data: []});
+ assert.deepEqual(fixture.updates, []);
+ assert.deepEqual(fixture.currents, []);
+ assert.deepEqual(fixture.explicitCurrents, [{id: "latest-heading", scroll: false}]);
+});
+
test("a selection in another editor falls back to the target editor's saved range", () => {
const fixture = setup();
const target = makeProtyle();
@@ -207,39 +305,6 @@ test("closing the last editor clears outline data without accessing a missing ed
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)));
diff --git a/app/src/editor/outlineNavigation.test.ts b/app/src/editor/outlineNavigation.test.ts
new file mode 100644
index 0000000000..cdbe122486
--- /dev/null
+++ b/app/src/editor/outlineNavigation.test.ts
@@ -0,0 +1,184 @@
+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 getDeclarations = (path: string, names: string[]) => {
+ const source = createSourceFile(path, readFileSync(path, "utf8"), ScriptTarget.ES2021, true);
+ return source.statements.filter(statement => isVariableStatement(statement) &&
+ statement.declarationList.declarations.some(item => names.includes(item.name.getText(source))))
+ .map(statement => statement.getText(source).replace(/^export /, "")).join("\n");
+};
+const outlineSource = createSourceFile("Outline.ts", readFileSync("src/layout/dock/Outline.ts", "utf8"), ScriptTarget.ES2021, true);
+const methods = outlineSource.statements.find(isClassDeclaration).members.filter(member =>
+ ["setCurrent", "setCurrentById", "invalidateCurrent"].includes(member.name?.getText(outlineSource)));
+const protyleSource = createSourceFile("Protyle.ts", readFileSync("src/protyle/index.ts", "utf8"), ScriptTarget.ES2021, true);
+const afterOnGet = protyleSource.statements.find(isClassDeclaration).members.find(member =>
+ member.name?.getText(protyleSource) === "afterOnGet");
+const compiled = transpileModule(getDeclarations("src/editor/util.ts", [
+ "outlineRequests", "syncOutlineCurrent", "updateOutline", "switchEditor", "updatePanelByEditor",
+]) + "\n" + getDeclarations("src/protyle/util/onGet.ts", ["focusElementById"]) + `
+class OutlineHarness {
+ currentRequestID = 0; blockId = "doc"; type = "pin"; isPreview = false;
+ getNotebookId() { return ""; }
+ ${methods.map(method => method.getText(outlineSource)).join("\n")}
+}
+class ProtyleHarness { ${afterOnGet.getText(protyleSource)} }
+Object.assign(globalThis, {switchEditor, updatePanelByEditor, focusElementById, OutlineHarness, ProtyleHarness});`, {
+ compilerOptions: {target: ScriptTarget.ES2021},
+}).outputText;
+
+const classList = (initial: string[] = []) => {
+ const values = new Set(initial);
+ return {contains: (value: string) => values.has(value), add: (value: string) => values.add(value),
+ remove: (value: string) => values.delete(value)};
+};
+
+const setupNavigation = (loaded: boolean, action: "focus" | "highlight") => {
+ const timers: (() => void)[] = [];
+ const requests: {url: string, callback: (response: unknown) => void}[] = [];
+ const heading = (id: string) => ({id, clientHeight: 20, isConnected: true, classList: classList(),
+ getAttribute: (name: string) => name === "data-type" ? "NodeHeading" : id});
+ const old = heading("old-heading");
+ const clicked = heading("clicked-heading");
+ const visible = new Set([old]);
+ if (loaded) {
+ visible.add(clicked);
+ }
+ let selected = {startContainer: old, endContainer: old};
+ let bodyTarget: string;
+ const protyle = {
+ block: {id: "doc", rootID: "doc"}, notebookId: "box", toolbar: {range: selected},
+ element: {isConnected: true, classList: classList(), contains: (node: typeof old) => visible.has(node), addEventListener() {}},
+ contentElement: {scrollTop: 0, classList: classList(), addEventListener() {}},
+ preview: {element: {classList: classList(["fn__none"])}},
+ wysiwyg: {element: {contains: (node: typeof old) => visible.has(node), firstElementChild: old,
+ ownerDocument: {activeElement: null as HTMLElement | null}, addEventListener() {},
+ querySelectorAll: () => visible.has(clicked) ? [clicked] : []}},
+ observer: {observe() {}, unobserve() {}},
+ model: {element: {parentElement: {parentElement: {}}}},
+ };
+ const scrollWrites: number[] = [];
+ let scrollTop = 320;
+ const panel = {
+ get scrollTop() { return scrollTop; },
+ set scrollTop(value: number) { scrollWrites.push(value); scrollTop = value; },
+ getBoundingClientRect: () => ({top: 0, height: 100}),
+ querySelectorAll: () => rows,
+ querySelector: (query: string) => rows.find(row => query.includes(`data-node-id="${row.id}"`)),
+ };
+ const rows = [old, clicked].map((node, index) => ({
+ id: node.id, clientHeight: 20, classList: classList(index === 1 ? ["b3-list-item--focus"] : []),
+ getBoundingClientRect: () => ({top: (index ? 900 : 100) - panel.scrollTop}),
+ }));
+ const context: any = {
+ Constants: {CB_GET_FOCUS: "focus", CB_GET_HL: "highlight", CB_GET_OUTLINE: "outline",
+ CB_GET_CONTEXT: "context", LOCAL_OUTLINE: "outlineStorage"}, AbortController,
+ window: {siyuan: {config: {editor: {dynamicLoadBlocks: 64}}, storage: {outlineStorage: {keepCurrentExpand: false}}}},
+ getSelection: () => ({rangeCount: 1, getRangeAt: () => selected}),
+ hasClosestByAttribute: (node: typeof old, name: string) => name === "data-node-id" ? node : undefined,
+ hasClosestByClassName: (): undefined => undefined, getPreviousBlock: (): undefined => undefined,
+ isEncryptedBox: () => false, isCurrentEditor: () => true, isInEmbedBlock: () => false,
+ revealTabsForTarget() {}, preventScroll() {}, hideElements() {}, updateBacklinkGraph() {},
+ initMirror() {}, setPanelFocus() {}, resize() {},
+ isPhablet: () => action === "highlight", resolveVisibleListMindmapBlock: (): undefined => undefined,
+ hasFocusOffsets: () => false, recordRestoredSpellcheckFocus() {},
+ focusBlock: (node: typeof old) => {selected = {startContainer: node, endContainer: node}; return selected;},
+ pushBack() {}, pushBackByEditor() {},
+ scrollCenter: (_protyle: unknown, node: typeof old) => { bodyTarget = node.id; },
+ highlightById: (_protyle: unknown, id: string) => { bodyTarget = id; },
+ bgFade() {}, getContenteditableElement: (node: typeof old) => node,
+ document: {createRange: () => ({selectNodeContents() {}, collapse() {}})},
+ ResizeObserver: class {observe() {} disconnect() {}},
+ setTimeout: (callback: () => void, delay: number) => {if (!delay) { timers.push(callback); }},
+ fetchPost: (url: string, _params: unknown, callback: (response: unknown) => void) => requests.push({url, callback}),
+ onGet: (options: {action: string[], scrollPosition: string}) => {
+ // 模拟文档响应完成渲染,再执行实际定位逻辑。
+ visible.clear();
+ visible.add(clicked);
+ protyle.block.id = clicked.id;
+ context.focusElementById(protyle, options.action, undefined, options.scrollPosition);
+ },
+ getAllModels: () => ({outline: [context.outline], editor: [] as unknown[]}),
+ };
+ runInNewContext(compiled, context);
+ context.outline = new context.OutlineHarness();
+ context.outline.element = panel;
+ const initialized = new context.ProtyleHarness();
+ initialized.protyle = protyle;
+ const syncPanel = () => context.updatePanelByEditor({
+ protyle, focus: false, pushBackStack: false, reload: false, resize: false,
+ });
+ const editor = {editor: {protyle}, parent: {headElement: {}, parent: {
+ switchTab: (_head: unknown, _pushBack: boolean, update = true) => {if (update) { syncPanel(); }},
+ showHeading() {},
+ }}};
+ return {
+ panel, scrollWrites, requests, syncPanel,
+ highlight: () => rows.find(row => row.classList.contains("b3-list-item--focus"))?.id,
+ bodyTarget: () => bodyTarget,
+ caret: () => selected.startContainer.id,
+ navigate: () => context.switchEditor(editor, {id: clicked.id, rootID: "doc", scrollPosition: "start",
+ action: [action, "outline", "context"]}, {}),
+ initialize: () => initialized.afterOnGet({blockId: clicked.id, action: [action, "outline"]}),
+ requestBreadcrumb: () => context.outline.setCurrent({isConnected: true,
+ getAttribute: (name: string) => name === "data-type" ? "NodeParagraph" : "old-paragraph"}),
+ selectHeading: () => context.outline.setCurrentById(clicked.id, false),
+ flushFocus: () => timers.splice(0).forEach(callback => callback()),
+ };
+};
+
+for (const loaded of [true, false]) {
+ for (const action of ["focus", "highlight"] as const) {
+ test(`outline navigation preserves the selected heading and scroll position (${loaded ? "loaded" : "unloaded"}, ${action})`, () => {
+ const fixture = setupNavigation(loaded, action);
+ fixture.navigate();
+ assert.equal(fixture.highlight(), "clicked-heading");
+ assert.equal(fixture.panel.scrollTop, 320);
+ assert.deepEqual(fixture.scrollWrites, []);
+ if (!loaded) {
+ assert.equal(fixture.requests.length, 1);
+ assert.equal(fixture.requests[0].url, "/api/filetree/getDoc");
+ fixture.requests[0].callback({data: {}});
+ }
+ fixture.flushFocus();
+ assert.equal(fixture.bodyTarget(), "clicked-heading");
+ if (action === "focus") {
+ assert.equal(fixture.caret(), "clicked-heading");
+ }
+ assert.equal(fixture.highlight(), "clicked-heading");
+ assert.equal(fixture.panel.scrollTop, 320);
+ assert.deepEqual(fixture.scrollWrites, []);
+ });
+ }
+}
+
+test("ordinary editor panel updates still follow and reveal the caret heading", () => {
+ const fixture = setupNavigation(true, "focus");
+ fixture.syncPanel();
+ assert.equal(fixture.highlight(), "old-heading");
+ assert.equal(fixture.panel.scrollTop, 50);
+ assert.deepEqual(fixture.scrollWrites, [50]);
+});
+
+for (const action of ["focus", "highlight"] as const) {
+ test(`newly initialized editors retain the requested outline heading before focus settles (${action})`, () => {
+ const fixture = setupNavigation(false, action);
+ fixture.initialize();
+ assert.equal(fixture.highlight(), "clicked-heading");
+ assert.equal(fixture.panel.scrollTop, 320);
+ assert.deepEqual(fixture.scrollWrites, []);
+ });
+}
+
+test("selecting an outline heading cancels an older paragraph breadcrumb response", async () => {
+ const fixture = setupNavigation(true, "focus");
+ await fixture.requestBreadcrumb();
+ assert.equal(fixture.requests[0].url, "/api/block/getBlockBreadcrumb");
+ fixture.selectHeading();
+ fixture.requests[0].callback({data: [{type: "NodeHeading", id: "old-heading"}]});
+ assert.equal(fixture.highlight(), "clicked-heading");
+ assert.equal(fixture.panel.scrollTop, 320);
+ assert.deepEqual(fixture.scrollWrites, []);
+});
diff --git a/app/src/editor/util.ts b/app/src/editor/util.ts
index e1f4a4f44e..4ddd3d12dd 100644
--- a/app/src/editor/util.ts
+++ b/app/src/editor/util.ts
@@ -46,7 +46,6 @@ 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)) {
@@ -457,7 +456,20 @@ const switchEditor = (editor: Editor, options: IOpenFileOptions, allModels: IMod
editor.parent.headElement.setAttribute("keep-cursor", options.id);
return true;
}
- editor.parent.parent.switchTab(editor.parent.headElement);
+ if (options.action?.includes(Constants.CB_GET_OUTLINE)) {
+ // 大纲导航使用点击的标题,避免恢复旧光标时覆盖高亮并滚动大纲。
+ editor.parent.parent.switchTab(editor.parent.headElement, false, false);
+ updatePanelByEditor({
+ protyle: editor.editor.protyle,
+ focus: false,
+ pushBackStack: false,
+ reload: false,
+ resize: true,
+ outlineId: options.id,
+ });
+ } else {
+ editor.parent.parent.switchTab(editor.parent.headElement);
+ }
editor.parent.parent.showHeading();
if (options.mode !== "preview" && !editor.editor.protyle.preview.element.classList.contains("fn__none")) {
return true;
@@ -582,9 +594,6 @@ const switchEditor = (editor: Editor, options: IOpenFileOptions, allModels: IMod
scrollCenter(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 {
@@ -710,7 +719,9 @@ export const updatePanelByEditor = (options: {
focus: boolean,
pushBackStack: boolean,
reload: boolean,
- resize: boolean
+ resize: boolean,
+ // 手动大纲导航按目标标题同步高亮,并保留大纲滚动位置。
+ outlineId?: string,
}) => {
if (options.protyle && options.protyle.path) {
// https://ld246.com/article/1637636106054/comment/1641485541929#comments
@@ -757,7 +768,7 @@ export const updatePanelByEditor = (options: {
}
// 切换页签或关闭所有页签时,需更新对应的面板
const models = getAllModels();
- updateOutline(models, options.protyle, options.reload);
+ updateOutline(models, options.protyle, options.reload, options.outlineId);
updateBacklinkGraph(models, options.protyle);
};
@@ -776,13 +787,17 @@ export const isCurrentEditor = (blockId: string) => {
return false;
};
-const outlineRequests = new WeakMap<Outline, object>();
+const outlineRequests = new WeakMap<Outline, AbortController>();
-const syncOutlineCurrent = (outline: Outline, protyle: IProtyle) => {
+const syncOutlineCurrent = (outline: Outline, protyle: IProtyle, outlineId?: string) => {
if (!protyle || outline.isPreview || !protyle.preview.element.classList.contains("fn__none") ||
outline.blockId !== protyle.block?.rootID) {
return;
}
+ if (outlineId !== undefined) {
+ outline.setCurrentById(outlineId, false);
+ return;
+ }
const selection = getSelection();
const selectedRange = selection.rangeCount > 0 ? selection.getRangeAt(0) : undefined;
const range = selectedRange && protyle.element.contains(selectedRange.startContainer) &&
@@ -793,12 +808,13 @@ const syncOutlineCurrent = (outline: Outline, protyle: IProtyle) => {
void outline.setCurrent(currentElement || undefined);
};
-export const updateOutline = (models: IModels, protyle: IProtyle, reload = false) => {
+export const updateOutline = (models: IModels, protyle: IProtyle, reload = false, outlineId?: string) => {
models.outline.find(item => {
if (!reload && item.type === "local" && item.blockId !== protyle?.block?.rootID) {
return;
}
- const request = {};
+ outlineRequests.get(item)?.abort();
+ const request = new AbortController();
outlineRequests.set(item, request);
item.invalidateCurrent();
const isPreview = protyle ? !protyle.preview.element.classList.contains("fn__none") : false;
@@ -822,6 +838,17 @@ export const updateOutline = (models: IModels, protyle: IProtyle, reload = false
if (protyle && isEncryptedBox(protyle.notebookId)) {
outlineParam.notebook = protyle.notebookId;
}
+ let currentOutlineId = outlineId;
+ if (protyle && outlineId !== undefined) {
+ // 等待大纲加载时,用户在正文中的新操作优先于此前点击的标题。
+ const followCaret = () => {
+ currentOutlineId = undefined;
+ request.abort();
+ };
+ ["pointerdown", "keydown", "beforeinput"].forEach(type => {
+ protyle.element.addEventListener(type, followCaret, {capture: true, signal: request.signal});
+ });
+ }
fetchPost("/api/outline/getDocOutline", outlineParam, response => {
if (outlineRequests.get(item) !== request) {
return;
@@ -835,13 +862,13 @@ export const updateOutline = (models: IModels, protyle: IProtyle, reload = false
item.update(response, blockId, protyle?.notebookId || "");
if (protyle) {
item.updateDocTitle(protyle.background.ial, Array.isArray(response.data) ? response.data.length : 0);
- syncOutlineCurrent(item, protyle);
+ syncOutlineCurrent(item, protyle, currentOutlineId);
} else {
item.updateDocTitle();
}
- });
+ }).finally(() => request.abort());
} else {
- syncOutlineCurrent(item, protyle);
+ syncOutlineCurrent(item, protyle, outlineId);
}
});
};
diff --git a/app/src/layout/dock/Outline.ts b/app/src/layout/dock/Outline.ts
index 1aa62b94b0..48d70f64e2 100644
--- a/app/src/layout/dock/Outline.ts
+++ b/app/src/layout/dock/Outline.ts
@@ -134,6 +134,7 @@ export class Outline extends Model {
});
}
} else {
+ this.invalidateCurrent();
checkFold(id, (zoomIn) => {
const action = isPhablet() ? Constants.CB_GET_HL : Constants.CB_GET_FOCUS;
openFileById({
@@ -652,7 +653,8 @@ export class Outline extends Model {
}
}
- private setCurrentById(id: string, scroll = true) {
+ public setCurrentById(id: string, scroll = true) {
+ this.invalidateCurrent();
this.element.querySelectorAll(".b3-list-item.b3-list-item--focus").forEach(item => {
item.classList.remove("b3-list-item--focus");
});
diff --git a/app/src/protyle/index.ts b/app/src/protyle/index.ts
index c2928d6807..8137d6f985 100644
--- a/app/src/protyle/index.ts
+++ b/app/src/protyle/index.ts
@@ -594,7 +594,8 @@ export class Protyle {
focus: false,
pushBackStack: false,
reload: false,
- resize: false
+ resize: false,
+ outlineId: mergedOptions.action?.includes(Constants.CB_GET_OUTLINE) ? mergedOptions.blockId : undefined,
});
/// #endif
}