Skip to content

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

:art: Improve mobile sidebar tab switching with swipe gestures https://github.com/siyuan-note/siyuan/issues/19645

Danielc7bdb0799a4c
diff --git a/app/src/mobile/util/sidebar.ts b/app/src/mobile/util/sidebar.ts
index 437404873a..eabb3bfac6 100644
--- a/app/src/mobile/util/sidebar.ts
+++ b/app/src/mobile/util/sidebar.ts
@@ -22,6 +22,20 @@ export const getSidebarDock = (sidebarElement: HTMLElement | null) => {
}
};
+export const switchToNextSidebarTab = (side: MobileSidebarSide) => {
+ const toolbarElement = getSidebarElement(side)?.querySelector(".toolbar--border");
+ const tabs = Array.from(toolbarElement?.querySelectorAll<HTMLElement>("[data-type$='-tab']") || [])
+ .filter(item => !item.classList.contains("fn__none"));
+ if (tabs.length < 2) {
+ return;
+ }
+ const activeIndex = tabs.findIndex(item => item.classList.contains("toolbar__icon--active"));
+ const nextTab = tabs[(activeIndex + 1) % tabs.length];
+ const type = nextTab.dataset.mobilePluginDockTab || nextTab.dataset.type.replace(/^sidebar-/, "").replace(/-tab$/, "");
+ toolbarElement.dispatchEvent(new CustomEvent("click", {detail: type}));
+ nextTab.scrollIntoView({block: "nearest", inline: "nearest"});
+};
+
export const popSidebar = (side: MobileSidebarSide, render = true) => {
activeBlur();
const sidebarElement = getSidebarElement(side);
diff --git a/app/src/mobile/util/sidebarSwipe.test.ts b/app/src/mobile/util/sidebarSwipe.test.ts
new file mode 100644
index 0000000000..e2dda39af1
--- /dev/null
+++ b/app/src/mobile/util/sidebarSwipe.test.ts
@@ -0,0 +1,184 @@
+import {test} from "node:test";
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {resolve} from "node:path";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, transpileModule} from "typescript";
+import * as gestures from "./touchPanelGesture";
+import {getTouchAxis} from "./touchGesture";
+
+const loadModule = (name: string, globals: Record<string, unknown>) => {
+ const exports: Record<string, (...args: unknown[]) => void> = {};
+ const source = readFileSync(resolve(process.cwd(), `src/mobile/util/${name}.ts`), "utf8");
+ runInNewContext(transpileModule(source, {compilerOptions: {module: ModuleKind.CommonJS}}).outputText,
+ {exports, ...globals});
+ return exports;
+};
+
+const classList = (...classes: string[]) => {
+ const values = new Set(classes);
+ return {
+ contains: (name: string) => values.has(name),
+ add: (name: string) => values.add(name),
+ remove: (name: string) => values.delete(name),
+ };
+};
+
+test("sidebar cycling follows visible tab order and dispatches plugin activation", () => {
+ const activated: string[] = [];
+ const revealed: string[] = [];
+ const tabs = ["file", "agent", "plugin-custom", "tag"].map(type => ({
+ dataset: {type: `sidebar-${type}-tab`, mobilePluginDockTab: type === "plugin-custom" ? type : undefined},
+ classList: classList(...(type === "file" ? ["toolbar__icon--active"] : type === "agent" ? ["fn__none"] : [])),
+ scrollIntoView: () => revealed.push(type),
+ }));
+ let currentTabs = tabs;
+ const toolbar = {
+ querySelectorAll: () => currentTabs,
+ dispatchEvent: (event: {detail: string}) => {
+ activated.push(event.detail);
+ tabs.forEach(tab => {
+ tab.classList.remove("toolbar__icon--active");
+ if (tab.dataset.type === `sidebar-${event.detail}-tab`) {
+ tab.classList.add("toolbar__icon--active");
+ }
+ });
+ },
+ };
+ const sidebar = loadModule("sidebar", {
+ require: () => ({}),
+ document: {getElementById: () => ({querySelector: () => toolbar})},
+ CustomEvent: class {
+ detail: string;
+ constructor(_type: string, options: {detail: string}) { this.detail = options.detail; }
+ },
+ });
+ sidebar.switchToNextSidebarTab("left");
+ sidebar.switchToNextSidebarTab("left");
+ sidebar.switchToNextSidebarTab("left");
+ assert.deepEqual(activated, ["plugin-custom", "tag", "file"]);
+ assert.deepEqual(revealed, activated);
+ currentTabs = [tabs[3], tabs[0], tabs[2]];
+ sidebar.switchToNextSidebarTab("right");
+ assert.equal(activated.at(-1), "plugin-custom");
+ currentTabs = [tabs[0], tabs[1]];
+ sidebar.switchToNextSidebarTab("left");
+ currentTabs = [];
+ sidebar.switchToNextSidebarTab("right");
+ assert.equal(activated.length, 4);
+});
+
+const createTouchHarness = (side: "left" | "right", options: {scrollable?: boolean, disabled?: boolean} = {}) => {
+ const actions: string[] = [];
+ const panel = {classList: classList(), style: {transform: "translateX(0px)"}, contains: () => false};
+ const mask = {classList: classList(), style: {}};
+ const target = {
+ id: side === "left" ? "sidebar" : "sidebarRight",
+ tagName: "DIV", dataset: {}, parentElement: null as HTMLElement | null,
+ closest: (): null => null,
+ scrollWidth: options.scrollable ? 600 : 300, clientWidth: 300, scrollLeft: 100,
+ };
+ let now = 1000;
+ const modules: Record<string, unknown> = {
+ "./sidebar": {
+ getSidebarElement: () => panel,
+ popSidebar: () => { panel.style.transform = "translateX(0px)"; actions.push("restore"); },
+ switchToNextSidebarTab: (value: string) => actions.push(`next:${value}`),
+ },
+ "./touchPanelGesture": gestures,
+ "./touchGesture": {getTouchAxis},
+ "./mobileBarsConfig": {getMobileSidebarConfig: () => ({sidebarSwipe: !options.disabled})},
+ "../../protyle/util/hasClosest": {
+ hasClosestByAttribute: (element: typeof target, key: string, value: string) =>
+ key === "id" && element.id === value ? element : undefined,
+ hasClosestByClassName: (): undefined => undefined,
+ hasTopClosestByClassName: (): undefined => undefined,
+ hasClosestBlock: (): undefined => undefined,
+ },
+ "./closePanel": {closePanel: () => actions.push("close"), showPanelMask: () => {}},
+ "./keyboardToolbar": {activeBlur: () => {}, resetAndroidBoundedSelectionGesture: () => {}},
+ "../../protyle/util/compatibility": {isInHarmony: () => false, isInAndroid: () => false, isIPhone: () => false},
+ "../editor": {getCurrentEditor: (): undefined => undefined},
+ "../../constants": {Constants: {SIZE_DRAG_THRESHOLD: 5, TIMEOUT_LONGPRESS: 500, TIMEOUT_MULTIPLE_SELECT: 500}},
+ };
+ const touch = loadModule("touch", {
+ require: (name: string) => modules[name] || {},
+ document: {
+ querySelector: (selector: string) => selector === ".side-mask" ? mask : {classList: classList("fn__none")},
+ getElementById: (): null => null,
+ },
+ window: {innerWidth: 360, siyuan: {mobile: {}, zIndex: 0}, getSelection: () => ({rangeCount: 0})},
+ getSelection: () => ({rangeCount: 0}),
+ getComputedStyle: () => ({overflowX: options.scrollable ? "auto" : "visible"}),
+ Date: {now: () => now},
+ });
+ const event = (x: number, y = 200, count = 1) => ({
+ target, touches: Array.from({length: count}, () => ({target, clientX: x, clientY: y})),
+ changedTouches: [{target, clientX: x, clientY: y}],
+ });
+ return {
+ actions, panel, target,
+ start: () => touch.handleTouchStart(event(180)),
+ move: (x: number, y = 200, count = 1) => touch.handleTouchMove(event(x, y, count)),
+ end: (x: number, y = 200) => { now += 100; touch.handleTouchEnd(event(x, y)); },
+ cancel: () => touch.handleTouchCancel(),
+ };
+};
+
+for (const side of ["left", "right"] as const) {
+ const nextX = side === "left" ? 240 : 120;
+ const closeX = side === "left" ? 120 : 240;
+ test(`${side} sidebar switches once on release and retains closing gestures`, () => {
+ const next = createTouchHarness(side, {disabled: true});
+ next.start();
+ next.move(nextX);
+ next.move(nextX);
+ assert.deepEqual(next.actions, []);
+ assert.equal(next.panel.style.transform, "translateX(0px)");
+ next.end(nextX);
+ assert.deepEqual(next.actions, ["restore", `next:${side}`]);
+ const close = createTouchHarness(side);
+ close.start();
+ close.move(closeX);
+ assert.notEqual(close.panel.style.transform, "translateX(0px)");
+ close.end(closeX);
+ assert.deepEqual(close.actions, ["close"]);
+ });
+
+ test(`${side} sidebar ignores short, vertical, canceled, reversed and multi-touch gestures`, () => {
+ for (const kind of ["short", "vertical", "cancel", "reverse", "multi"]) {
+ const harness = createTouchHarness(side);
+ harness.start();
+ if (kind === "short") {
+ harness.move(190);
+ harness.end(190);
+ } else if (kind === "vertical") {
+ harness.move(185, 240);
+ harness.move(nextX, 250);
+ harness.end(nextX, 250);
+ } else {
+ harness.move(nextX, 200, kind === "multi" ? 2 : 1);
+ if (kind === "cancel") {
+ harness.cancel();
+ } else {
+ harness.end(kind === "reverse" ? 180 : nextX);
+ }
+ }
+ assert.equal(harness.actions.some(action => action.startsWith("next:") || action === "close"), false, kind);
+ }
+ });
+
+ test(`${side} sidebar leaves horizontal scrolling to content until the next gesture`, () => {
+ const harness = createTouchHarness(side, {scrollable: true});
+ harness.start();
+ harness.move(nextX);
+ harness.target.scrollLeft = side === "left" ? 0 : 300;
+ harness.move(nextX);
+ harness.end(nextX);
+ assert.deepEqual(harness.actions, ["restore"]);
+ harness.start();
+ harness.move(nextX);
+ harness.end(nextX);
+ assert.deepEqual(harness.actions, ["restore", "restore", `next:${side}`]);
+ });
+}
diff --git a/app/src/mobile/util/touch.ts b/app/src/mobile/util/touch.ts
index 824b151848..f2e62ecdc9 100644
--- a/app/src/mobile/util/touch.ts
+++ b/app/src/mobile/util/touch.ts
@@ -1,4 +1,4 @@
-import {getSidebarDock, getSidebarElement, popSidebar} from "./sidebar";
+import {getSidebarDock, getSidebarElement, popSidebar, switchToNextSidebarTab} from "./sidebar";
import {getMobileSidebarConfig} from "./mobileBarsConfig";
import {
hasClosestBlock,
@@ -271,7 +271,7 @@ export const handleTouchEnd = (event: TouchEvent) => {
return;
}
- const commitSidebarSwipe = Math.abs(finalXDiff) > Math.abs(finalYDiff) && shouldCommitSidebarSwipe(
+ const commitSidebarSwipe = firstXY === "x" && Math.abs(finalXDiff) > Math.abs(finalYDiff) && shouldCommitSidebarSwipe(
firstDirection,
finalXDiff,
currentTime - time,
@@ -279,10 +279,13 @@ export const handleTouchEnd = (event: TouchEvent) => {
);
if (targetSidebar) {
- if (commitSidebarSwipe) {
+ if (commitSidebarSwipe && shouldDragOpenSidebar(targetSidebar, firstDirection)) {
closePanel();
} else {
popSidebar(targetSidebar, false);
+ if (commitSidebarSwipe) {
+ switchToNextSidebarTab(targetSidebar);
+ }
}
return;
}
@@ -467,8 +470,10 @@ export const handleTouchMove = (event: TouchEvent) => {
// 选中后扩选的情况
const range = getSelection().getRangeAt(0);
const currentEditor = getCurrentEditor();
+ const targetSidebar = getTargetSidebar(target);
if (hasVisibleSelectionText(stripSemanticMarkersFromRangeText(range)) &&
- currentEditor?.protyle.wysiwyg.element.contains(range.startContainer)) {
+ (currentEditor?.protyle.wysiwyg.element.contains(range.startContainer) ||
+ (targetSidebar && getSidebarElement(targetSidebar)?.contains(range.startContainer)))) {
return;
}
}
@@ -486,15 +491,16 @@ export const handleTouchMove = (event: TouchEvent) => {
}
firstDirection = xDiff > 0 ? "toLeft" : "toRight";
if (firstXY === "x") {
- const targetSidebar = getTargetSidebar(target);
const menuElement = hasClosestByAttribute(target, "id", "menu", true);
- if ((menuElement && !shouldCloseGlobalMenu(firstDirection, false)) ||
- (targetSidebar && !shouldDragOpenSidebar(targetSidebar, firstDirection))) {
+ if (menuElement && !shouldCloseGlobalMenu(firstDirection, false)) {
firstXY = "y";
yDiff = undefined;
}
}
}
+ if (firstXY === "y") {
+ return;
+ }
if (typeof previousClientX !== "undefined") {
if (firstDirection === "toRight") {
if (previousClientX > event.touches[0].clientX) {
@@ -525,8 +531,8 @@ export const handleTouchMove = (event: TouchEvent) => {
if (!getTargetSidebar(target) && !getMobileSidebarConfig().sidebarSwipe) {
return;
}
- if (hasClosestByClassName(target, "agent-chat__messages", true)) {
- // 消息内容可沿手势方向横向滚动时,本次手势持续交给内容,抵达边缘后可再次滑动返回。
+ if (getTargetSidebar(target) || hasClosestByClassName(target, "agent-chat__messages", true)) {
+ // 内容可沿手势方向横向滚动时,本次手势持续交给内容,抵达边缘后可再次滑动操作侧栏。
if (scrollBlock || isHorizontalScrollable(target, xDiff)) {
scrollBlock = true;
return;
@@ -573,6 +579,11 @@ export const handleTouchMove = (event: TouchEvent) => {
}
}
+ // 切换页签时保持侧栏展开,松手后按距离和速度判断是否切换。
+ const sidebar = getTargetSidebar(target);
+ if (sidebar && !shouldDragOpenSidebar(sidebar, firstDirection)) {
+ return;
+ }
if (isFirstMove) {
const openingSidebar = getOpeningSidebar(firstDirection);
if (!getTargetSidebar(target) && !getSidebarDock(getSidebarElement(openingSidebar))) {