Skip to content

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

:sparkles: Use SiYuan menus for mobile dropdown selectors https://github.com/siyuan-note/siyuan/issues/19981

Daniel101e57a9eea2
diff --git a/app/src/mobile/index.ts b/app/src/mobile/index.ts
index 25f71e6e3b..f4b34ce5e9 100644
--- a/app/src/mobile/index.ts
+++ b/app/src/mobile/index.ts
@@ -68,6 +68,7 @@ import {initTouchDragBridge} from "../util/touchDragBridge";
import {appearanceConfigApi} from "../config/tabs/appearanceRuntime";
import {openByMobile} from "../editor/openLink";
import {initHarmonyTextSelectionMenu} from "../util/harmonyTextSelectionMenu";
+import {initMobileSelect} from "./util/nativeSelect";
import {updateMobileTopBarLayout} from "./util/mobileTopBar";
import {showMobileBars} from "./util/mobileBars";
import {initializeEnglishCommandTranslations} from "../command/english";
@@ -205,6 +206,7 @@ class App {
Constants.SIYUAN_VERSION,
);
window.siyuan.menus = new Menus(this);
+ initMobileSelect();
document.title = window.siyuan.languages.siyuanNote;
bootSync();
appearanceConfigApi.apply(window.siyuan.config.appearance);
diff --git a/app/src/mobile/util/MobileBackFoward.test.ts b/app/src/mobile/util/MobileBackFoward.test.ts
index 0cf5bfe9ee..1c9dc96d06 100644
--- a/app/src/mobile/util/MobileBackFoward.test.ts
+++ b/app/src/mobile/util/MobileBackFoward.test.ts
@@ -30,6 +30,7 @@ test("mobile back saves the database text editor before leaving its owner", () =
saved++;
}},
"../../util/zIndex": {isAbove},
+ "./nativeSelect": {getMobileSelectMenuElement: (): undefined => undefined},
};
const api = {} as typeof import("./MobileBackFoward");
runInNewContext(source, {
@@ -46,3 +47,30 @@ test("mobile back saves the database text editor before leaving its owner", () =
assert.equal(navigated, 0);
}
});
+
+test("mobile back closes a select menu before its containing menu or dialog", () => {
+ const source = transpileModule(readFileSync(join(__dirname, "MobileBackFoward.ts"), "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2020},
+ }).outputText;
+ let closedSelect = 0;
+ let closedOwner = 0;
+ const selectMenu = {style: {zIndex: "3"}, dispatchEvent: () => closedSelect++};
+ const ownerMenu = {classList: {contains: (name: string) => name !== "fn__none"},
+ dispatchEvent: () => closedOwner++};
+ const api = {} as typeof import("./MobileBackFoward");
+ const modules: Record<string, unknown> = {
+ "../editor": {getCurrentEditor: (): undefined => undefined},
+ "../../util/zIndex": {isAbove},
+ "./nativeSelect": {getMobileSelectMenuElement: () => selectMenu},
+ };
+ runInNewContext(source, {
+ exports: api, require: (name: string) => modules[name] || {}, CustomEvent: class {},
+ document: {getElementById: () => ({style: {}}), querySelector: (): undefined => undefined},
+ window: {siyuan: {menus: {menu: {element: ownerMenu}}, dialogs: [{
+ element: {querySelector: () => ({style: {zIndex: "2"}})}, destroy: () => closedOwner++,
+ }]}},
+ });
+ api.goBack();
+ assert.equal(closedSelect, 1);
+ assert.equal(closedOwner, 0);
+});
diff --git a/app/src/mobile/util/MobileBackFoward.ts b/app/src/mobile/util/MobileBackFoward.ts
index 7c1dec1dad..ddd99d1ff0 100644
--- a/app/src/mobile/util/MobileBackFoward.ts
+++ b/app/src/mobile/util/MobileBackFoward.ts
@@ -5,6 +5,7 @@ import {closePanel} from "./closePanel";
import {backModel, destroyModel} from "../menu/model";
import {destroyAVRichTextEditor} from "../../protyle/render/av/richTextEditor";
import {isAbove} from "../../util/zIndex";
+import {getMobileSelectMenuElement} from "./nativeSelect";
export const clearMobileBackForward = (notebookId?: string) => {
if (notebookId) {
@@ -27,7 +28,12 @@ export const goBack = () => {
const menuElement = document.getElementById("menu");
const richTextElement = document.querySelector<HTMLElement>(".av__richtext-mask");
const topDialog = window.siyuan.dialogs[window.siyuan.dialogs.length - 1];
- if (window.siyuan.menus.menu.element.classList.contains("b3-menu--fullscreen") &&
+ const selectMenuElement = getMobileSelectMenuElement();
+ if (selectMenuElement && (!topDialog ||
+ isAbove(selectMenuElement, topDialog.element.querySelector(".b3-dialog")))) {
+ selectMenuElement.dispatchEvent(new CustomEvent("click", {detail: "back"}));
+ return;
+ } else if (window.siyuan.menus.menu.element.classList.contains("b3-menu--fullscreen") &&
!window.siyuan.menus.menu.element.classList.contains("fn__none")) {
window.siyuan.menus.menu.element.dispatchEvent(new CustomEvent("click", {detail: "back"}));
return;
diff --git a/app/src/mobile/util/nativeSelect.ts b/app/src/mobile/util/nativeSelect.ts
new file mode 100644
index 0000000000..ad5e0987da
--- /dev/null
+++ b/app/src/mobile/util/nativeSelect.ts
@@ -0,0 +1,80 @@
+import {Menu} from "../../plugin/Menu";
+import {escapeHtml} from "../../util/escape";
+
+let activeMenu: Menu | undefined;
+
+export const getMobileSelectMenuElement = () => activeMenu?.element;
+
+const getSelect = (target: EventTarget) => {
+ const select = target instanceof Element ? target.closest<HTMLSelectElement>("select.b3-select") : null;
+ return select && !select.matches(":disabled") && !select.multiple && select.size <= 1 ? select : undefined;
+};
+
+const openSelect = (select: HTMLSelectElement) => {
+ activeMenu?.close();
+ // 菜单内的选择器使用独立菜单,保留原表单节点及其保存事件。
+ const menu = new Menu(undefined, () => {
+ if (activeMenu === menu) {
+ activeMenu = undefined;
+ }
+ }, Boolean(select.closest(".b3-menu")));
+ const addOption = (option: HTMLOptionElement, groupDisabled = false) => {
+ if (option.hidden) {
+ return;
+ }
+ menu.addItem({
+ label: escapeHtml(option.label),
+ current: option.selected,
+ disabled: option.disabled || groupDisabled,
+ click: () => {
+ if (!select.isConnected || !select.contains(option) || select.matches(":disabled") ||
+ option.disabled || groupDisabled || option.selected) {
+ return;
+ }
+ select.selectedIndex = option.index;
+ select.dispatchEvent(new Event("input", {bubbles: true}));
+ select.dispatchEvent(new Event("change", {bubbles: true}));
+ },
+ });
+ };
+ Array.from(select.children).forEach(child => {
+ if (child instanceof HTMLOptGroupElement) {
+ if (child.hidden) {
+ return;
+ }
+ menu.addItem({type: "readonly", label: escapeHtml(child.label)});
+ Array.from(child.children).forEach(option => addOption(option as HTMLOptionElement, child.disabled));
+ } else if (child instanceof HTMLOptionElement) {
+ addOption(child);
+ }
+ });
+ activeMenu = menu;
+ const rect = select.getBoundingClientRect();
+ menu.open({x: rect.left, y: rect.bottom, h: rect.height, w: rect.width, target: select});
+};
+
+export const initMobileSelect = () => {
+ document.addEventListener("pointerdown", event => {
+ if (getSelect(event.target)) {
+ event.preventDefault();
+ }
+ }, true);
+ document.addEventListener("click", event => {
+ const select = getSelect(event.target);
+ if (!select) {
+ return;
+ }
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ openSelect(select);
+ }, true);
+ document.addEventListener("keydown", event => {
+ const select = getSelect(event.target);
+ if (!select || !["Enter", " ", "ArrowDown", "ArrowUp"].includes(event.key)) {
+ return;
+ }
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ openSelect(select);
+ }, true);
+};
diff --git a/app/tests/mobileNativeSelect.test.js b/app/tests/mobileNativeSelect.test.js
new file mode 100644
index 0000000000..03fde4fb69
--- /dev/null
+++ b/app/tests/mobileNativeSelect.test.js
@@ -0,0 +1,110 @@
+const assert = require("node:assert/strict");
+const {execFile} = require("node:child_process");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+const {test} = require("node:test");
+const {promisify} = require("node:util");
+const {ModuleKind, transpileModule} = require("typescript");
+
+const runCases = source => {
+ const check = require("node:assert/strict");
+ const state = {};
+ class Menu {
+ constructor(_id, onClose, independent) {
+ this.items = [];
+ this.element = document.createElement("div");
+ this.independent = independent;
+ this.onClose = onClose;
+ state.menu = this;
+ }
+ addItem(item) { this.items.push(item); }
+ open() { document.body.appendChild(this.element); }
+ close() { this.element.remove(); this.onClose(); }
+ }
+ const api = {};
+ new Function("require", "exports", source)(name => ({
+ "../../plugin/Menu": {Menu},
+ "../../util/escape": {escapeHtml: value => value.replace(/&/g, "&amp;").replace(/</g, "&lt;")},
+ })[name], api);
+ api.initMobileSelect();
+ const host = document.createElement("div");
+ host.innerHTML = `<select class="b3-select"><option value="same">First</option>
+ <option value="same">Second</option><optgroup label="Group" disabled><option>Disabled</option></optgroup>
+ <option hidden>Hidden</option></select>`;
+ document.body.appendChild(host);
+ const select = host.querySelector("select");
+ const changes = [];
+ for (const type of ["input", "change"]) {
+ host.addEventListener(type, event => changes.push([event.type, event.target.selectedIndex]));
+ }
+ const pointer = new PointerEvent("pointerdown", {bubbles: true, cancelable: true});
+ select.dispatchEvent(pointer);
+ check.equal(pointer.defaultPrevented, true);
+ select.click();
+ check.equal(state.menu.independent, false);
+ check.equal(api.getMobileSelectMenuElement(), state.menu.element);
+ check.deepEqual(state.menu.items.map(item => item.label), ["First", "Second", "Group", "Disabled"]);
+ check.equal(state.menu.items[0].current, true);
+ check.equal(state.menu.items[3].disabled, true);
+ state.menu.items[0].click();
+ check.equal(changes.length, 0);
+ state.menu.items[1].click();
+ check.equal(select.selectedIndex, 1);
+ check.deepEqual(changes, [["input", 1], ["change", 1]]);
+ state.menu.close();
+ check.equal(api.getMobileSelectMenuElement(), undefined);
+
+ host.className = "b3-menu";
+ select.dispatchEvent(new KeyboardEvent("keydown", {key: "Enter", bubbles: true, cancelable: true}));
+ check.equal(state.menu.independent, true);
+ check.equal(state.menu.items[1].current, true);
+ state.menu.items[3].click();
+ check.equal(select.selectedIndex, 1);
+ state.menu.close();
+ for (const attribute of ["disabled", "multiple", "size"]) {
+ select.setAttribute(attribute, attribute === "size" ? "3" : "");
+ select.click();
+ check.equal(api.getMobileSelectMenuElement(), undefined);
+ select.removeAttribute(attribute);
+ }
+ select.click();
+ host.remove();
+ state.menu.items[0].click();
+ check.equal(changes.length, 2);
+ state.menu.close();
+ return "Mobile native select cases passed";
+};
+
+test("mobile native select keeps form events, option groups and nested menu ownership", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
+ timeout: 45000,
+}, async () => {
+ const source = transpileModule(fs.readFileSync(path.join(__dirname, "../src/mobile/util/nativeSelect.ts"), "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS},
+ }).outputText;
+ const temporary = fs.mkdtempSync(path.join(os.tmpdir(), "siyuan-mobile-select-test-"));
+ const script = path.join(temporary, "run.cjs");
+ fs.writeFileSync(script, `const {app, BrowserWindow} = require("electron");
+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});
+app.commandLine.appendSwitch("disable-gpu");
+app.whenReady().then(async () => {
+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});
+ try {
+ await win.loadURL("data:text/html,<html><body></body></html>");
+ console.log(await win.webContents.executeJavaScript(${JSON.stringify("(" + runCases.toString() + ")(" + JSON.stringify(source) + ")")}));
+ win.destroy(); app.exit(0);
+ } catch (error) { console.error(error); win.destroy(); app.exit(1); }
+});`, "utf8");
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ try {
+ const result = await promisify(execFile)(require("electron"), [script], {env, timeout: 40000, windowsHide: true});
+ assert.match(result.stdout, /Mobile native select cases passed/);
+ } finally {
+ if (path.dirname(path.resolve(temporary)) === path.resolve(os.tmpdir()) &&
+ path.basename(temporary).startsWith("siyuan-mobile-select-test-")) {
+ fs.rmSync(temporary, {recursive: true, force: true});
+ }
+ }
+});