Skip to content

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

:bug: Move the cursor into activated tab content https://github.com/siyuan-note/siyuan/issues/19547

Danielef966052ba8e
diff --git a/app/src/layout/resizeSelection.test.ts b/app/src/layout/resizeSelection.test.ts
deleted file mode 100644
index 2ed7205caa..0000000000
--- a/app/src/layout/resizeSelection.test.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import * as assert from "node:assert/strict";
-import {readFileSync} from "node:fs";
-import {test} from "node:test";
-import {runInNewContext} from "node:vm";
-import {createSourceFile, isIfStatement, Node, ScriptTarget, transpileModule} from "typescript";
-
-const source = createSourceFile("util.ts", readFileSync("src/layout/util.ts", "utf8"), ScriptTarget.ES2021, true);
-let restoreSelection: string;
-const visit = (node: Node) => {
- if (isIfStatement(node) && node.expression.getText(source) === "range" &&
- node.thenStatement.getText(source).includes("focusByRange(range)")) {
- restoreSelection = node.getText(source);
- }
- node.forEachChild(visit);
-};
-visit(source);
-assert.ok(restoreSelection);
-const compiled = transpileModule(restoreSelection, {
- compilerOptions: {target: ScriptTarget.ES2021},
-}).outputText;
-
-const checkRestore = (startHidden: boolean, endHidden: boolean, textNode: boolean) => {
- const container = (hidden: boolean) => {
- const element = {
- nodeType: 1,
- closest(selector: string) {
- assert.equal(selector, '.tab-item[data-tabs-hidden="true"]');
- return hidden ? {} : null;
- },
- };
- return textNode ? {nodeType: 3, parentElement: element} : element;
- };
- const range = {startContainer: container(startHidden), endContainer: container(endHidden)};
- let restored = false;
- runInNewContext(compiled, {
- range, Node: {ELEMENT_NODE: 1},
- focusByRange(value: unknown) {
- assert.equal(value, range);
- restored = true;
- },
- });
- return restored;
-};
-
-test("resizing preserves the selected tab when the old selection is hidden", () => {
- for (const textNode of [false, true]) {
- assert.equal(checkRestore(true, true, textNode), false);
- assert.equal(checkRestore(true, false, textNode), false);
- assert.equal(checkRestore(false, true, textNode), false);
- }
-});
-
-test("resizing restores selections in visible content", () => {
- assert.equal(checkRestore(false, false, false), true);
- assert.equal(checkRestore(false, false, true), true);
-});
diff --git a/app/src/layout/util.ts b/app/src/layout/util.ts
index c92eda8e0d..c460576b33 100644
--- a/app/src/layout/util.ts
+++ b/app/src/layout/util.ts
@@ -1168,14 +1168,7 @@ export const addResize = (obj: Layout | Wnd, after = true) => {
window.siyuan.layout.rightDock.setSize();
}
if (range) {
- // 调整尺寸后仅恢复可见页签中的选区,避免旧光标重新展开已隐藏的页签。
- const inHiddenTab = [range.startContainer, range.endContainer].some(node => {
- const element = node.nodeType === Node.ELEMENT_NODE ? node as Element : node.parentElement;
- return element?.closest('.tab-item[data-tabs-hidden="true"]');
- });
- if (!inHiddenTab) {
- focusByRange(range);
- }
+ focusByRange(range);
}
nextElement.style.overflow = "";
previousElement.style.overflow = "";
diff --git a/app/src/protyle/render/tabsKeyboard.test.ts b/app/src/protyle/render/tabsKeyboard.test.ts
index 099dd259c3..bc598259f7 100644
--- a/app/src/protyle/render/tabsKeyboard.test.ts
+++ b/app/src/protyle/render/tabsKeyboard.test.ts
@@ -2,7 +2,7 @@ import * as assert from "node:assert/strict";
import {readFileSync} from "node:fs";
import {test} from "node:test";
import {runInNewContext} from "node:vm";
-import {createSourceFile, isArrowFunction, isCallExpression, ModuleKind, Node, ScriptTarget, transpileModule} from "typescript";
+import {createSourceFile, isArrowFunction, isCallExpression, isVariableDeclaration, ModuleKind, Node, ScriptTarget, transpileModule} from "typescript";
import {tabKeyboardTarget} from "./tabsState";
const source = createSourceFile("tabsRender.ts", readFileSync("src/protyle/render/tabsRender.ts", "utf8"),
@@ -10,7 +10,11 @@ const source = createSourceFile("tabsRender.ts", readFileSync("src/protyle/rende
const loadHandler = (element: "button" | "task", globals: Record<string, unknown>) => {
let handler: Node;
+ let selectTab: Node;
const visit = (node: Node) => {
+ if (isVariableDeclaration(node) && node.name.getText(source) === "selectTab") {
+ selectTab = node.initializer;
+ }
if (isCallExpression(node) && node.expression.getText(source) === `${element}.addEventListener` &&
node.arguments[0].getText(source) === (element === "button" ? '"keydown"' : "type") &&
isArrowFunction(node.arguments[1])) {
@@ -20,7 +24,7 @@ const loadHandler = (element: "button" | "task", globals: Record<string, unknown
};
visit(source);
assert.ok(handler);
- const compiled = transpileModule(`exports.handler = ${handler.getText(source)};`, {
+ const compiled = transpileModule(`const selectTab = ${selectTab.getText(source)}; exports.handler = ${handler.getText(source)};`, {
compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
}).outputText;
const exports: any = {};
@@ -31,8 +35,9 @@ const loadHandler = (element: "button" | "task", globals: Record<string, unknown
const fixture = (readonly: boolean, vertical = false) => {
const calls: string[] = [];
const globals = {
- ids: ["a", "b"], item: {}, itemID: () => "a", type: "keydown", readonly,
+ ids: ["a", "b"], items: [{}], item: {}, itemID: () => "a", type: "keydown", readonly,
tabs: {
+ getBoundingClientRect: () => ({top: -1}),
getAttribute: () => vertical ? "vertical" : "horizontal",
scrollIntoView: (options: ScrollIntoViewOptions) => {
assert.equal(options.block, "start");
@@ -46,7 +51,10 @@ const fixture = (readonly: boolean, vertical = false) => {
scrollIntoView: () => calls.push("scroll"),
focus: () => calls.push("focus"),
}]},
- controller: {select: () => calls.push("select"), options: {task: () => calls.push("task")}},
+ controller: {select: () => calls.push("select"), options: {
+ task: () => calls.push("task"),
+ activate: () => calls.push("activate"),
+ }},
};
const button = loadHandler("button", globals);
const task = loadHandler("task", globals);
@@ -104,5 +112,5 @@ test("readonly task activation cannot toggle the task or select the parent tab",
assert.deepEqual(editable.calls, ["task"]);
const tab = fixture(true);
assert.equal(tab.dispatch("Enter").propagationStopped, true);
- assert.deepEqual(tab.calls, ["select", "panel-start"]);
+ assert.deepEqual(tab.calls, ["select", "activate", "panel-start"]);
});
diff --git a/app/src/protyle/render/tabsRender.ts b/app/src/protyle/render/tabsRender.ts
index 054a60c13d..d8d5430ae6 100644
--- a/app/src/protyle/render/tabsRender.ts
+++ b/app/src/protyle/render/tabsRender.ts
@@ -7,6 +7,7 @@ export interface ITabsRenderOptions {
label?: string;
addLabel?: string;
select?: (tabs: HTMLElement, id: string) => void;
+ activate?: (item: HTMLElement) => void;
rename?: (item: HTMLElement) => void;
add?: (tabs: HTMLElement) => void;
menu?: (tabs: HTMLElement, item: HTMLElement, anchor: HTMLElement) => void;
@@ -244,6 +245,7 @@ export const tabsRender = (element: Element, options: ITabsRenderOptions = {}) =
}
}
controller.select(tabs, id, true);
+ controller.options.activate?.(items.find(item => itemID(item) === id));
if (top < visibleTop) {
tabs.scrollIntoView({block: "start", inline: "nearest"});
}
diff --git a/app/src/protyle/wysiwyg/tabs.ts b/app/src/protyle/wysiwyg/tabs.ts
index 5c714eeac7..0d8eee81d5 100644
--- a/app/src/protyle/wysiwyg/tabs.ts
+++ b/app/src/protyle/wysiwyg/tabs.ts
@@ -202,6 +202,21 @@ export const initEditorTabs = (protyle: IProtyle) => {
taskLabel: window.siyuan.languages.task,
task: item => setTabTask(protyle, item, nextTaskListMarker(getTabTask(item))),
endEdit: () => hideElements(["toolbar"], protyle),
+ activate: item => {
+ if (!canEdit(protyle, item)) {
+ return;
+ }
+ // 切换页签时同步正文光标和工具栏选区,后续操作沿用当前页签的位置。
+ const content = getTabContent(item);
+ const target = Array.from(content.querySelectorAll<HTMLElement>('[contenteditable="true"]'))
+ .find(element => !isHiddenTabContent(element) && element.getClientRects().length > 0);
+ const range = document.createRange();
+ range.selectNodeContents(target || content);
+ range.collapse(true);
+ hideElements(["toolbar"], protyle);
+ focusByRange(range);
+ protyle.toolbar.range = range.cloneRange();
+ },
select: (tabs, id) => {
if (!canEdit(protyle, tabs) || tabs.getAttribute("tabs-active-id") === id) {
return;
diff --git a/app/src/protyle/wysiwyg/tabsActivation.test.ts b/app/src/protyle/wysiwyg/tabsActivation.test.ts
new file mode 100644
index 0000000000..b923afbd94
--- /dev/null
+++ b/app/src/protyle/wysiwyg/tabsActivation.test.ts
@@ -0,0 +1,66 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {createSourceFile, isPropertyAssignment, Node, ScriptTarget, transpileModule} from "typescript";
+
+const source = createSourceFile("tabs.ts", readFileSync("src/protyle/wysiwyg/tabs.ts", "utf8"), ScriptTarget.ES2021, true);
+let activate: string;
+const visit = (node: Node) => {
+ if (isPropertyAssignment(node) && node.name.getText(source) === "activate") {
+ activate = node.initializer.getText(source);
+ }
+ node.forEachChild(visit);
+};
+visit(source);
+assert.ok(activate);
+const compiled = transpileModule(`(${activate})(item);`, {
+ compilerOptions: {target: ScriptTarget.ES2021},
+}).outputText;
+
+const fixture = (editable: boolean, hasText = true) => {
+ const hidden = {hidden: true, getClientRects: () => [1]};
+ const title = {hidden: false, getClientRects: (): number[] => []};
+ const visible = {hidden: false, getClientRects: () => [1]};
+ const content = {querySelectorAll: () => hasText ? [hidden, title, visible] : []};
+ const oldRange = {};
+ const protyle = {toolbar: {range: oldRange}};
+ let selected: unknown;
+ let focused: unknown;
+ let collapsed: boolean;
+ const savedRange = {};
+ const range = {
+ selectNodeContents(target: unknown) { selected = target; },
+ collapse(value: boolean) { collapsed = value; },
+ cloneRange: () => savedRange,
+ };
+ runInNewContext(compiled, {
+ item: {}, protyle, canEdit: () => editable,
+ getTabContent: () => content,
+ isHiddenTabContent: (element: typeof hidden) => element.hidden,
+ document: {createRange: () => range},
+ hideElements: () => {},
+ focusByRange(value: unknown) { focused = value; },
+ });
+ return {selected, focused, collapsed, range, protyle, oldRange, savedRange, visible, content};
+};
+
+test("tab activation moves the cursor and saved selection to visible content", () => {
+ const f = fixture(true);
+ assert.equal(f.selected, f.visible);
+ assert.equal(f.focused, f.range);
+ assert.equal(f.collapsed, true);
+ assert.equal(f.protyle.toolbar.range, f.savedRange);
+});
+
+test("tab activation uses the panel when no editable text is available", () => {
+ const f = fixture(true, false);
+ assert.equal(f.selected, f.content);
+ assert.equal(f.focused, f.range);
+});
+
+test("readonly tab activation preserves the selection", () => {
+ const f = fixture(false);
+ assert.equal(f.focused, undefined);
+ assert.equal(f.protyle.toolbar.range, f.oldRange);
+});