An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Improve mobile database editing panels https://github.com/siyuan-note/siyuan/issues/20665
Daniel222a87c344af
diff --git a/app/src/assets/scss/component/_menu.scss b/app/src/assets/scss/component/_menu.scssindex ac12640821..4d19a758ee 100644--- a/app/src/assets/scss/component/_menu.scss+++ b/app/src/assets/scss/component/_menu.scss@@ -220,6 +220,12 @@transition: transform .15s cubic-bezier(0, 0, .2, 1), height .15s cubic-bezier(0, 0, .2, 1);will-change: transform;+ &.b3-menu--expanded {+ max-height: calc(100vh - env(safe-area-inset-top));+ max-height: calc(100dvh - env(safe-area-inset-top));+ border-radius: 0;+ }+.b3-menu {&__title {background-color: var(--b3-theme-surface);@@ -257,6 +263,26 @@display: none;}}++ &--actions {+ height: 56px;+ padding: 8px 16px 0;+ align-items: center;++ > .b3-menu__label {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ }+ }++ &__actions {+ display: flex;+ align-items: center;+ gap: 8px;+ margin-left: auto;}&__items {diff --git a/app/src/assets/scss/main/_mobile.scss b/app/src/assets/scss/main/_mobile.scssindex 75b02d55c4..8c705ba2fe 100644--- a/app/src/assets/scss/main/_mobile.scss+++ b/app/src/assets/scss/main/_mobile.scss@@ -1590,7 +1590,6 @@ body.mobile-topbar--merged {&--sheet {// 菜单入口可能指定宽度,移动端底部菜单始终铺满视口top: auto !important;- bottom: 0 !important;left: 0 !important;right: 0 !important;width: auto !important;@@ -1619,14 +1618,12 @@ body.mobile-topbar--merged {> .b3-menu {// 数据库面板切换内容时会重新写入锚点坐标,底部布局不随锚点变化top: auto !important;- bottom: 0 !important;+ bottom: var(--b3-menu-sheet-bottom, 0px);left: 0 !important;right: 0 !important;width: auto !important;min-width: 0 !important;max-width: none !important;- max-height: 90vh !important;- max-height: 90dvh !important;box-sizing: border-box;border: 0;border-radius: var(--b3-border-radius-b) var(--b3-border-radius-b) 0 0;@@ -1637,6 +1634,10 @@ body.mobile-topbar--merged {transform: none;will-change: auto;+ &.b3-menu--expanded {+ border-radius: 0;+ }+> .b3-menu__items {max-height: none;min-height: 0;@@ -1723,6 +1724,12 @@ body.mobile-topbar--merged {padding: 0;}+ &--actions {+ height: 56px;+ min-height: 56px;+ padding: 8px 16px 0;+ }+> .b3-menu__label {text-align: left;color: var(--b3-theme-on-surface-light);@@ -1733,6 +1740,10 @@ body.mobile-topbar--merged {color: var(--b3-theme-on-surface-light);}+ > .block__icon--menu-back {+ display: none;+ }+> [data-type="go-config"] {padding: 0 !important;margin: 0 12px 0 0 !important;diff --git a/app/src/menus/Menu.ts b/app/src/menus/Menu.tsindex eb78f5ae3f..7b086d1081 100644--- a/app/src/menus/Menu.ts+++ b/app/src/menus/Menu.ts@@ -5,6 +5,7 @@ import {getAnchoredMenuPosition} from "./menuPosition";import {bindMenuMouseScroll} from "./menuMouseScroll";import {updateMenuGroupsOnMutation, updateMenuItemGroupClasses} from "./menuGroup";import {getVisibleSheetViewport, waitForSheetViewport} from "./sheetOpen";+import {getSheetActionsHTML, setSheetExpanded} from "./sheetActions";import {hasClosestByClassName} from "../protyle/util/hasClosest";import {isMobile} from "../util/functions";import {Constants} from "../constants";@@ -42,6 +43,8 @@ export class Menu {private sheetTouchStartTime: number | undefined;private sheetCanDrag = false;private sheetDragging = false;+ private sheetCanExpand = false;+ private sheetStartHeight = 0;private suppressSheetClick = false;private targetPositionFrame: number | undefined;private cancelSheetOpen: (() => void) | undefined;@@ -115,6 +118,18 @@ export class Menu {}const target = event.target as Element;if (isMobile()) {+ const sheetAction = target.closest<HTMLElement>(".b3-menu__actions [data-type]")?.dataset.type;+ if (sheetAction) {+ event.preventDefault();+ event.stopPropagation();+ if (sheetAction === "sheet-expand") {+ setSheetExpanded(this.element, !this.element.classList.contains("b3-menu--expanded"));+ this.setSheetHeight();+ } else {+ this.closeSheet();+ }+ return;+ }const titleElement = hasClosestByClassName(target, "b3-menu__title");const isSystemBack = typeof event.detail === "string" && event.detail === "back";if ((titleElement && !titleElement.classList.contains("b3-menu__title--root")) || isSystemBack) {@@ -214,6 +229,9 @@ export class Menu {}private canDragSheet(target: HTMLElement) {+ if (target.closest(".b3-menu__actions")) {+ return false;+ }// 文件选择框覆盖上传菜单项,允许从该区域开始下拉关闭菜单。if (target.closest("input:not([type=\"file\"]), textarea, select, [contenteditable=\"true\"]")) {return false;@@ -250,6 +268,10 @@ export class Menu {this.sheetTouchStartTime = performance.now();this.sheetCanDrag = this.canDragSheet(event.target as HTMLElement);this.sheetDragging = false;+ this.sheetStartHeight = this.element.clientHeight;+ this.sheetCanExpand = this.element.getAttribute("data-sheet-expandable") === "true" &&+ !this.element.classList.contains("b3-menu--expanded") &&+ !!(event.target as HTMLElement).closest(".b3-menu__title");};private handleSheetTouchMove = (event: TouchEvent) => {@@ -260,13 +282,18 @@ export class Menu {const touch = event.touches[0];const xDiff = touch.clientX - this.sheetTouchStartX;const yDiff = touch.clientY - this.sheetTouchStartY;- if (!this.sheetDragging && (yDiff <= 0 || Math.abs(xDiff) > Math.abs(yDiff))) {+ if (!this.sheetDragging && ((yDiff <= 0 && !this.sheetCanExpand) || Math.abs(xDiff) > Math.abs(yDiff))) {return;}const offset = Math.max(0, yDiff);this.sheetDragging = true;this.element.style.transition = "none";- this.element.style.transform = `translateY(${offset}px)`;+ if (yDiff < 0) {+ this.element.style.height = Math.min(window.innerHeight, this.sheetStartHeight - yDiff) + "px";+ this.element.style.transform = "translateY(0px)";+ } else {+ this.element.style.transform = `translateY(${offset}px)`;+ }const scrimElement = this.getFullscreenScrim();if (scrimElement) {scrimElement.style.opacity = Math.max(0, .2 * (1 - offset / this.element.clientHeight)).toString();@@ -281,6 +308,7 @@ export class Menu {this.sheetTouchStartY = undefined;this.sheetTouchStartTime = undefined;this.sheetCanDrag = false;+ this.sheetCanExpand = false;this.sheetDragging = false;}@@ -291,14 +319,26 @@ export class Menu {return;}const touch = event.changedTouches[0];- const offset = Math.max(0, touch.clientY - this.sheetTouchStartY);+ const offset = touch.clientY - this.sheetTouchStartY;const duration = Math.max(performance.now() - this.sheetTouchStartTime, 1);- const velocity = offset / duration;+ const velocity = Math.abs(offset) / duration;+ const shouldExpand = this.sheetCanExpand && (offset < -40 || (offset < -20 && velocity > .6));const shouldClose = offset > Math.min(120, this.element.clientHeight * .25) ||(offset > 20 && velocity > .6);this.element.style.transition = "";void this.element.offsetHeight;- if (shouldClose) {+ if (shouldExpand) {+ setSheetExpanded(this.element, true);+ this.setSheetHeight();+ } else if (shouldClose && this.element.classList.contains("b3-menu--expanded")) {+ setSheetExpanded(this.element, false);+ this.setSheetHeight();+ this.element.style.transform = "translateY(0px)";+ const scrimElement = this.getFullscreenScrim();+ if (scrimElement) {+ scrimElement.style.opacity = "";+ }+ } else if (shouldClose) {this.closeSheet();} else {this.element.style.transform = "translateY(0px)";@@ -306,6 +346,9 @@ export class Menu {if (scrimElement) {scrimElement.style.opacity = "";}+ if (this.sheetCanExpand) {+ this.setSheetHeight();+ }}this.suppressSheetClick = true;window.setTimeout(() => {@@ -323,6 +366,9 @@ export class Menu {if (scrimElement) {scrimElement.style.opacity = "";}+ if (this.sheetCanExpand) {+ this.setSheetHeight();+ }}this.finishSheetTouch();};@@ -383,17 +429,20 @@ export class Menu {this.updateSheetTitle();const mobileSize = window.siyuan.mobile.size;const orientationSize = mobileSize.isLandscape ? mobileSize.landscape : mobileSize.portrait;+ const expanded = this.element.classList.contains("b3-menu--expanded");+ const expandable = this.element.getAttribute("data-sheet-expandable") === "true";let maxHeight: number;- if (this.preserveSheetKeyboard) {+ if (this.preserveSheetKeyboard || expanded || expandable) {const viewport = getVisibleSheetViewport(window.innerHeight, window.visualViewport);this.element.style.bottom = viewport.bottomOffset + "px";- maxHeight = viewport.height * .9;+ maxHeight = expanded ? viewport.height : this.preserveSheetKeyboard ? viewport.height * .9 :+ Math.min(Math.max(window.innerHeight, orientationSize?.height1 || 0) * .56, viewport.height);} else {// 使用当前方向记录的完整视口高度,避免软键盘收起期间菜单高度被压缩this.element.style.bottom = "";maxHeight = Math.max(window.innerHeight, orientationSize?.height1 || 0) * .56;}- if (this.element.classList.contains("b3-menu--fit")) {+ if (!expanded && this.element.classList.contains("b3-menu--fit")) {// 内容不足时收缩面板,避免列表下方留白;测量时取消弹性拉伸,否则 scrollHeight 会包含被撑大的空白this.element.style.height = "";const itemsElement = this.element.lastElementChild as HTMLElement;@@ -562,6 +611,8 @@ export class Menu {this.removeScrollEvent();this.element.firstElementChild.classList.add("fn__none");this.element.firstElementChild.classList.remove("b3-menu__title--root");+ this.element.firstElementChild.classList.remove("b3-menu__title--actions");+ this.element.firstElementChild.querySelector(".b3-menu__actions")?.remove();(this.element.firstElementChild.querySelector(".b3-menu__label") as HTMLElement).innerHTML =window.siyuan.languages.back;this.element.lastElementChild.innerHTML = "";@@ -569,7 +620,8 @@ export class Menu {this.element.lastElementChild.removeAttribute("style"); // 输入框 focus 后 boxShadow 显示不全this.element.classList.add("fn__none");setPopoverMenuOpen(this.element, false);- this.element.classList.remove("b3-menu--list", "b3-menu--fullscreen", "b3-menu--sheet", "b3-menu--fit");+ this.element.classList.remove("b3-menu--list", "b3-menu--fullscreen", "b3-menu--sheet", "b3-menu--fit", "b3-menu--expanded");+ this.element.removeAttribute("data-sheet-expandable");this.element.removeAttribute("style"); // zIndexthis.element.removeAttribute("data-name"); // 标识再次点击不消失this.element.removeAttribute("data-from"); // 标识菜单入口@@ -737,7 +789,14 @@ export class Menu {this.element.querySelectorAll(":scope > .b3-menu__items, .b3-menu__submenu > .b3-menu__items").forEach(updateMenuItemGroupClasses);this.element.classList.add("b3-menu--fullscreen", "b3-menu--sheet");- if (this.preserveSheetKeyboard || this.element.classList.contains("b3-menu--fit")) {+ if (this.element.getAttribute("data-sheet-expandable") === "true") {+ this.element.firstElementChild.classList.add("b3-menu__title--actions");+ if (!this.element.firstElementChild.querySelector(".b3-menu__actions")) {+ this.element.firstElementChild.insertAdjacentHTML("beforeend", getSheetActionsHTML());+ }+ }+ if (this.preserveSheetKeyboard || this.element.classList.contains("b3-menu--fit") ||+ this.element.getAttribute("data-sheet-expandable") === "true") {// 输入法弹出后视口会异步收缩,持续跟踪视口才能按最终可用高度重新适配内容this.startTrackingSheetViewport();}diff --git a/app/src/menus/databaseSheet.dom.test.ts b/app/src/menus/databaseSheet.dom.test.tsnew file mode 100644index 0000000000..da04c5a7f4--- /dev/null+++ b/app/src/menus/databaseSheet.dom.test.ts@@ -0,0 +1,254 @@+import * as assert from "node:assert/strict";+import {execFile} from "node:child_process";+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";+import {tmpdir} from "node:os";+import * as path from "node:path";+import {test} from "node:test";+import {promisify} from "node:util";+import {compile, Logger} from "sass";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";++const browserCases = async (sources: Record<string, string>, languages: Record<string, string>) => {+ const check: typeof assert = require("node:assert/strict");+ let saves = 0;+ let backs = 0;+ const modules: Record<string, {exports: any}> = {};+ const content = () => '<div class="b3-menu__items"><input class="b3-text-field" value="Draft">' ++ '<div style="height:1600px">Database settings</div></div>';+ const externals = {+ "protyle/util/compatibility": {getEventName: () => "click", isInMobileApp: () => true},+ "util/functions": {isMobile: () => true},+ "util/zIndex": {isScrollAboveMenu: () => true},+ "layout/getTopBarHeight": {getTopBarHeight: () => 0},+ constants: {Constants: {TIMEOUT_DBLCLICK: 10, TIMEOUT_TRANSITION: 0}},+ "protyle/undo": {}, "menus/menuKeyboard": {}, "menus/menuMouseScroll": {},+ "plugin/EventBusCore": {forEachPluginSubscriber() {}},+ "mobile/util/keyboardToolbar": {activeBlur() {}},+ "block/popoverLifecycle": {setPopoverMenuOpen() {}},+ "config/entryVisibility/runtime": {applyMenuEntryVisibility() {}},+ "protyle/render/av/panels/registry": {+ getAVPanelDescriptor: () => ({+ render: (context: {html: string}) => {+ context.html = '<div class="b3-menu__items"><button class="b3-menu__item" data-type="nobg">' ++ '<span class="block__icon block__icon--menu-back" data-type="go-config"><svg><use xlink:href="#iconLeft"></use></svg></span>' ++ '<span class="b3-menu__label ft__center">Fields</span></button>' ++ '<input class="b3-text-field" value="Draft"><div style="height:1600px">Fields</div></div>';+ return true;+ },+ bind: (context: {closeCB: () => void}) => { context.closeCB = () => saves++; },+ }),+ dispatchAVPanelAction: (context: {menuElement: HTMLElement}, action: {type: string}) => {+ check.equal(action.type, "go-config");+ backs++;+ context.menuElement.innerHTML = content();+ return "handled";+ },+ },+ "protyle/render/av/panels/drag": {bindAVPanelDrag() {}},+ "protyle/render/av/panels/inputs": {bindAVPanelInputs() {}},+ "protyle/render/av/viewType": {}, "protyle/wysiwyg/transaction": {}, "util/fetch": {},+ "protyle/render/av/automationPosition": {}, "protyle/render/av/select": {}, "protyle/render/av/filter": {},+ "protyle/ui/hideElements": {}, "protyle/render/av/view": {getFieldsByData: (): IAVColumn[] => []},+ "protyle/util/selection": {focusBlock() {}}, "protyle/render/av/row": {},+ "protyle/render/av/groups": {getPageSize: () => ({})},+ "protyle/render/av/color": {applyAVColorPalette() {}, getAVCustomColors: (): string[] => []},+ "protyle/render/av/panelTarget": {}, "protyle/render/av/selectPosition": {},+ };+ const load = (name: string): any => {+ if (name in externals) {+ return externals[name as keyof typeof externals];+ }+ if (modules[name]) {+ return modules[name].exports;+ }+ check.ok(sources[name], `Unexpected sheet dependency: ${name}`);+ const module = {exports: {}};+ modules[name] = module;+ new Function("require", "module", "exports", sources[name])((dependency: string) => {+ const parts = name.split("/");+ parts.pop();+ dependency.split("/").forEach(part => {+ if (part === "..") {+ parts.pop();+ } else if (part !== ".") {+ parts.push(part);+ }+ });+ return load(parts.join("/"));+ }, module, module.exports);+ return module.exports;+ };+ Object.assign(window, {siyuan: {languages, zIndex: 0, storage: {}, menus: {},+ mobile: {size: {portrait: {height1: innerHeight}, landscape: {height1: innerHeight}}}}});+ const viewport = new EventTarget();+ Object.assign(viewport, {height: innerHeight, offsetTop: 0});+ Object.defineProperty(window, "visualViewport", {configurable: true, value: viewport});+ const settle = async () => {+ await new Promise(resolve => setTimeout(resolve, 180));+ await new Promise(resolve => requestAnimationFrame(resolve));+ };+ const {Menu}: typeof import("./Menu") = load("menus/Menu");+ const {openMenuPanel}: typeof import("../protyle/render/av/openMenuPanel") = load("protyle/render/av/openMenuPanel");+ const common = document.createElement("div");+ common.id = "commonMenu";+ common.className = "b3-menu fn__none";+ common.innerHTML = '<div class="b3-menu__title"><span class="b3-menu__label"></span></div>' ++ '<div class="b3-menu__items"><button class="b3-menu__item">Database</button></div>';+ common.dataset.sheetExpandable = "true";+ document.body.append(common);+ const parent = new Menu(common);+ parent.addItem({label: "A long database property label that needs more than one line", submenu: [{label: "Option"}]});+ window.siyuan.menus.menu = parent;+ parent.fullscreen();+ await settle();+ check.ok(Math.abs(common.getBoundingClientRect().height - innerHeight * .56) < 1);+ (common.lastElementChild.lastElementChild as HTMLElement).click();+ await settle();+ const title = common.firstElementChild;+ const titleLabel = title.querySelector(".b3-menu__label").getBoundingClientRect();+ const titleActions = title.querySelector(".b3-menu__actions").getBoundingClientRect();+ check.ok(titleLabel.right <= titleActions.left);+ check.ok(titleActions.right <= innerWidth);+ common.dispatchEvent(new CustomEvent("click", {detail: "back"}));+ await settle();+ const expand = common.querySelector<HTMLButtonElement>('[data-type="sheet-expand"]');+ expand.click();+ await settle();+ check.ok(Math.abs(common.getBoundingClientRect().height - innerHeight) < 1);+ check.equal(expand.getAttribute("aria-expanded"), "true");+ check.ok(expand.getBoundingClientRect().width > 20);+ expand.click();+ await settle();+ check.ok(Math.abs(common.getBoundingClientRect().height - innerHeight * .56) < 1);++ const block = document.createElement("div");+ block.className = "av";+ block.dataset.nodeId = "block";+ block.dataset.avId = "database";+ block.innerHTML = '<div class="av__views"></div>';+ document.body.append(block);+ const subElement = document.createElement("div");+ subElement.classList.add("fn__none");+ // 数据库面板关闭时不应误判为正在搜索资源。+ const protyle = {toolbar: {subElement}} as unknown as IProtyle;+ openMenuPanel({type: "config", data: {} as IAV, blockElement: block, keepMenuOpen: true, protyle});+ await settle();+ const panel = document.querySelector<HTMLElement>(".av__panel");+ const menu = panel.lastElementChild as HTMLElement;+ const back = menu.querySelector<HTMLButtonElement>('[data-type="sheet-back"]');+ check.equal(back.classList.contains("fn__none"), false);+ check.ok(Math.abs(menu.getBoundingClientRect().height - innerHeight * .56) < 1);+ menu.querySelector<HTMLButtonElement>('[data-type="sheet-expand"]').click();+ await settle();+ check.ok(Math.abs(menu.getBoundingClientRect().height - innerHeight) < 1);+ const input = menu.querySelector("input");+ input.focus();+ input.value = "Changed";+ back.click();+ await settle();+ check.equal(backs, 1);+ check.equal(saves, 0);+ check.equal(panel.isConnected, true);+ check.equal(menu.classList.contains("b3-menu--expanded"), true);+ check.ok(Math.abs(menu.getBoundingClientRect().height - innerHeight) < 1);+ check.equal(menu.querySelector('[data-type="sheet-back"]').classList.contains("fn__none"), true);+ const items = menu.querySelector<HTMLElement>(".b3-menu__items");+ check.ok(items.clientHeight > 200 && items.scrollHeight > items.clientHeight);+ check.equal(common.classList.contains("fn__none"), false);++ Object.assign(viewport, {height: innerHeight - 260, offsetTop: 0});+ viewport.dispatchEvent(new Event("resize"));+ await settle();+ check.ok(Math.abs(menu.getBoundingClientRect().bottom - (innerHeight - 260)) < 1);+ check.ok(Math.abs(menu.getBoundingClientRect().top) < 1);+ Object.assign(viewport, {height: innerHeight});+ viewport.dispatchEvent(new Event("resize"));+ await settle();+ check.ok(Math.abs(menu.getBoundingClientRect().height - innerHeight) < 1);+ const touch = (type: string, y: number) => {+ const event = new Event(type, {bubbles: true, cancelable: true});+ Object.assign(event, {touches: [{clientX: 80, clientY: y}], changedTouches: [{clientX: 80, clientY: y}]});+ menu.firstElementChild.dispatchEvent(event);+ };+ touch("touchstart", 100);+ touch("touchmove", 280);+ touch("touchend", 280);+ await settle();+ check.ok(Math.abs(menu.getBoundingClientRect().height - innerHeight * .56) < 1);+ touch("touchstart", 200);+ touch("touchmove", 60);+ touch("touchend", 60);+ await settle();+ check.ok(Math.abs(menu.getBoundingClientRect().height - innerHeight) < 1);+ await new Promise(resolve => setTimeout(resolve, 310));+ menu.querySelector<HTMLButtonElement>('[data-type="sheet-close"]').click();+ await settle();+ check.equal(saves, 1);+ check.equal(panel.isConnected, false);+ check.equal(common.classList.contains("fn__none"), false);+ common.querySelector<HTMLButtonElement>('[data-type="sheet-close"]').click();+ await settle();+ check.equal(common.classList.contains("fn__none"), true);+ check.equal(common.hasAttribute("data-sheet-expandable"), false);+ check.equal(common.querySelector(".b3-menu__actions"), null);+ parent.append(document.createElement("button"));+ parent.fullscreen();+ await settle();+ check.equal(common.querySelector(".b3-menu__actions"), null);+ parent.remove();+ return "Database sheets passed";+};++test("mobile database sheets expand, preserve navigation and edits, and fit the keyboard viewport", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 30000,+}, async () => {+ const sources = Object.fromEntries(["menus/Menu", "menus/menuGroup", "menus/menuPosition", "menus/sheetOpen", "menus/sheetActions",+ "util/escape", "util/setPosition", "protyle/util/hasClosest", "protyle/render/av/openMenuPanel",+ "protyle/render/av/mobilePanel"].map(name => [name, transpileModule(readFileSync(path.join(__dirname, "..", name + ".ts"), "utf8"), {+ compilerOptions: {target: ScriptTarget.ES2021, module: ModuleKind.CommonJS},+ }).outputText]));+ const css = compile(path.join(__dirname, "../assets/scss/mobile.scss"), {logger: Logger.silent}).css;+ const languages = JSON.parse(readFileSync("appearance/langs/en.json", "utf8"));+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-database-sheet-test-"));+ const script = path.join(temporary, "run.cjs");+ const source = `const __name = value => value; (${browserCases.toString()})(${JSON.stringify(sources)}, ${JSON.stringify(languages)})`;+ 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, width: 390, height: 844, useContentSize: true,+ webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});+ try {+ await win.loadURL("about:blank");+ await win.webContents.insertCSS(${JSON.stringify(css)});+ await win.webContents.insertCSS(require("node:fs").readFileSync(${JSON.stringify(path.resolve("appearance/themes/daylight/theme.css"))}, "utf8"));+ await win.webContents.executeJavaScript(require("node:fs").readFileSync(${JSON.stringify(path.resolve("appearance/icons/litheness/icon.js"))}, "utf8"));+ console.log(await win.webContents.executeJavaScript(${JSON.stringify(source)}));+ win.setContentSize(320, 640);+ await win.loadURL("about:blank");+ await win.webContents.insertCSS(${JSON.stringify(css)});+ await win.webContents.insertCSS(require("node:fs").readFileSync(${JSON.stringify(path.resolve("appearance/themes/midnight/theme.css"))}, "utf8"));+ await win.webContents.insertCSS("body {font-size: 20px; --b3-font-size-editor: 24px;}");+ await win.webContents.executeJavaScript(require("node:fs").readFileSync(${JSON.stringify(path.resolve("appearance/icons/litheness/icon.js"))}, "utf8"));+ console.log(await win.webContents.executeJavaScript(${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") as unknown as string, [script],+ {env, timeout: 25000, windowsHide: true});+ assert.match(result.stdout, /Database sheets passed/);+ } finally {+ assert.equal(path.dirname(path.resolve(temporary)), path.resolve(tmpdir()));+ assert.ok(path.basename(temporary).startsWith("siyuan-database-sheet-test-"));+ rmSync(temporary, {recursive: true, force: true});+ }+});diff --git a/app/src/menus/menuKeyboardRestore.test.ts b/app/src/menus/menuKeyboardRestore.test.tsindex e6ce9e800e..a0a83b2b10 100644--- a/app/src/menus/menuKeyboardRestore.test.ts+++ b/app/src/menus/menuKeyboardRestore.test.ts@@ -37,7 +37,8 @@ const setup = () => {const timers = new Map<number, () => void>();const frames = new Map<number, () => void>();const events: string[] = [];- const first = {...createElement(), querySelector: () => ({innerHTML: ""})};+ const first = {...createElement(), querySelector: (selector: string) =>+ selector === ".b3-menu__label" ? {innerHTML: ""} : null};const element = {...createElement(),firstElementChild: first,diff --git a/app/src/menus/menuLayout.dom.test.ts b/app/src/menus/menuLayout.dom.test.tsindex 74a2b90fc0..de85ae4945 100644--- a/app/src/menus/menuLayout.dom.test.ts+++ b/app/src/menus/menuLayout.dom.test.ts@@ -690,7 +690,7 @@ test("menus adapt to layout changes and optional whole-menu mouse scrolling", {skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,timeout: 45000,}, async () => {- const sources = Object.fromEntries(["menus/Menu", "menus/menuPosition", "menus/menuMouseScroll", "menus/menuGroup", "menus/sheetOpen",+ const sources = Object.fromEntries(["menus/Menu", "menus/menuPosition", "menus/menuMouseScroll", "menus/menuGroup", "menus/sheetOpen", "menus/sheetActions","util/setPosition", "protyle/util/hasClosest", "plugin/Menu", "protyle/render/av/openMenuPanel","asset/pdf/viewerTemplate", "asset/pdf/secondary_toolbar.js", "protyle/render/av/calendar/undated","layout/dock/agent/AgentSessionPanel"].map(name => [name,diff --git a/app/src/menus/menuSheetDrag.test.ts b/app/src/menus/menuSheetDrag.test.tsindex 2f94ca0b7b..972200a051 100644--- a/app/src/menus/menuSheetDrag.test.ts+++ b/app/src/menus/menuSheetDrag.test.ts@@ -11,13 +11,15 @@ const compiled = transpileModule(declaration.getText(source), {compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},}).outputText;-const createSheet = () => {+const createSheet = (expandable = false) => {let closes = 0;const listeners = new Map<string, (event: object) => void>();+ const classes = new Set(["b3-menu--sheet"]);const element = {id: "testMenu",- style: {transform: "", transition: ""},- classList: {contains: (name: string) => name === "b3-menu--sheet"},+ style: {transform: "", transition: "", height: "448px"},+ classList: {contains: (name: string) => classes.has(name)},+ getAttribute: () => expandable ? "true" : null,clientHeight: 400,querySelector: () => ({innerHTML: ""}),addEventListener: (type: string, listener: (event: object) => void) => listeners.set(type, listener),@@ -26,15 +28,25 @@ const createSheet = () => {runInNewContext(compiled, {exports,isMobile: () => true,+ setSheetExpanded: (_element: unknown, expanded: boolean) => {+ if (expanded) {+ classes.add("b3-menu--expanded");+ } else {+ classes.delete("b3-menu--expanded");+ }+ },performance: {now: () => 1000},getComputedStyle: () => ({overflowY: "auto"}),updateMenuGroupsOnMutation() {},MutationObserver: class { observe() {} },document: {createElement: () => ({})},- window: {siyuan: {languages: {back: "Back"}}, setTimeout() {}},+ window: {innerHeight: 800, siyuan: {languages: {back: "Back"}}, setTimeout() {}},});const menu = new exports.Menu(element as unknown as HTMLElement);menu.closeSheet = () => { closes++; };+ (menu as unknown as {setSheetHeight: () => void}).setSheetHeight = () => {+ element.style.height = classes.has("b3-menu--expanded") ? "800px" : "448px";+ };const swipe = (options: {sortable?: boolean, title?: boolean, scrollTop?: number}, offset: number) => {const items = {scrollHeight: 1000, clientHeight: 400, scrollTop: options.scrollTop || 0, parentElement: element};const target = {@@ -65,7 +77,7 @@ const createSheet = () => {listeners.get("touchend")(event);return {transform, prevented: event.defaultPrevented};};- return {swipe, closes: () => closes};+ return {swipe, element, classes, closes: () => closes};};test("sorting a menu item downward does not move or dismiss its bottom sheet", () => {@@ -93,3 +105,21 @@ for (const title of [false, true]) {assert.equal(sheet.closes(), 1);});}++test("pulling a database menu title upward expands it and pulling down restores half height", () => {+ const sheet = createSheet(true);+ assert.equal(sheet.swipe({title: true}, -100).prevented, true);+ assert.equal(sheet.classes.has("b3-menu--expanded"), true);+ assert.equal(sheet.element.style.height, "800px");+ sheet.swipe({title: true}, 200);+ assert.equal(sheet.classes.has("b3-menu--expanded"), false);+ assert.equal(sheet.element.style.height, "448px");+ assert.equal(sheet.closes(), 0);+});++test("scrolling database menu content upward keeps the half-height menu", () => {+ const sheet = createSheet(true);+ assert.equal(sheet.swipe({}, -100).prevented, false);+ assert.equal(sheet.classes.has("b3-menu--expanded"), false);+ assert.equal(sheet.element.style.height, "448px");+});diff --git a/app/src/menus/menuSheetHeight.test.ts b/app/src/menus/menuSheetHeight.test.tsindex 89bd238f23..e13edc4f61 100644--- a/app/src/menus/menuSheetHeight.test.ts+++ b/app/src/menus/menuSheetHeight.test.ts@@ -19,10 +19,15 @@ const setup = (options: {visualHeight?: number,visualOffsetTop?: number,preserveKeyboard?: boolean,+ expanded?: boolean,+ expandable?: boolean,}) => {const windowResizeListeners = new Set<() => void>();const viewportResizeListeners = new Set<() => void>();const classes = new Set<string>(["b3-menu--sheet"]);+ if (options.expanded) {+ classes.add("b3-menu--expanded");+ }if (options.fit) {classes.add("b3-menu--fit");}@@ -42,6 +47,7 @@ const setup = (options: {classList: {contains: (name: string) => classes.has(name),},+ getAttribute: () => options.expandable ? "true" : null,};const module = {exports: {} as {Menu: typeof Menu}};runInNewContext(compiled, {@@ -87,6 +93,21 @@ const setup = (options: {};describe("mobile menu sheet content fit", () => {+ it("fits an expanded database sheet above the keyboard", () => {+ const {menu, element} = setup({fit: false, contentHeight: 2000, viewportHeight: 800,+ visualHeight: 420, expanded: true, expandable: true});+ menu.resetPosition();+ assert.equal(element.style.height, "420px");+ assert.equal(element.style.bottom, "380px");+ });++ it("keeps a half-height database sheet visible above the keyboard", () => {+ const {menu, element} = setup({fit: false, contentHeight: 2000, viewportHeight: 800,+ visualHeight: 360, expandable: true});+ menu.resetPosition();+ assert.equal(element.style.height, "360px");+ assert.equal(element.style.bottom, "440px");+ });it("positions a keyboard-preserving sheet within the visible viewport", () => {const {menu, element} = setup({fit: false,diff --git a/app/src/menus/sheetActions.ts b/app/src/menus/sheetActions.tsnew file mode 100644index 0000000000..ba09ed343a--- /dev/null+++ b/app/src/menus/sheetActions.ts@@ -0,0 +1,16 @@+import {escapeAttr, escapeHtml} from "../util/escape";++export const getSheetActionsHTML = () => `<div class="b3-menu__actions">+ <button type="button" class="block__icon block__icon--show block__icon--touch ariaLabel" data-type="sheet-expand" aria-expanded="false" aria-label="${escapeAttr(window.siyuan.languages.fullscreen)}">+ <svg><use xlink:href="#iconFullscreen"></use></svg>+ </button>+ <button type="button" class="b3-button b3-button--text" data-type="sheet-close">${escapeHtml(window.siyuan.languages.close)}</button>+</div>`;++export const setSheetExpanded = (menuElement: HTMLElement, expanded: boolean) => {+ menuElement.classList.toggle("b3-menu--expanded", expanded);+ const button = menuElement.querySelector<HTMLElement>('[data-type="sheet-expand"]');+ button?.setAttribute("aria-expanded", String(expanded));+ button?.setAttribute("aria-label", expanded ? window.siyuan.languages.exitFullscreen : window.siyuan.languages.fullscreen);+ button?.querySelector("use")?.setAttribute("xlink:href", expanded ? "#iconFullscreenExit" : "#iconFullscreen");+};diff --git a/app/src/mobile/util/MobileBackFoward.test.ts b/app/src/mobile/util/MobileBackFoward.test.tsindex f76c3f2f05..4c95387b50 100644--- a/app/src/mobile/util/MobileBackFoward.test.ts+++ b/app/src/mobile/util/MobileBackFoward.test.ts@@ -55,7 +55,7 @@ test("mobile back saves the database text editor before leaving its owner", () =let closedMenu = 0;let navigated = 0;const richText = {style: {zIndex: "2"}};- const menu = {classList: {contains: (name: string) =>+ const menu = {style: {zIndex: "3"}, classList: {contains: (name: string) =>name === "fn__none" ? overlay !== "menu" : true},dispatchEvent: () => closedMenu++};const dialogs = overlay === "document" || overlay === "menu" ? [] : [{@@ -75,7 +75,8 @@ test("mobile back saves the database text editor before leaving its owner", () =const api = {} as typeof import("./MobileBackFoward");runInNewContext(source, {exports: api, require: (name: string) => modules[name] || {}, CustomEvent: class {},- document: {getElementById: () => ({style: {}}), querySelector: () => richText},+ document: {getElementById: () => ({style: {}}),+ querySelector: (selector: string) => selector === ".av__richtext-mask" ? richText : undefined},window: {siyuan: {dialogs, menus: {menu: {element: menu}}, mobile: {tabs: {goBack: () => { navigated++; return Promise.resolve(true); }},}}},@@ -115,3 +116,55 @@ test("mobile back closes a select menu before its containing menu or dialog", ()assert.equal(closedSelect, 1);assert.equal(closedOwner, 0);});++test("mobile back handles the top database editor before its retained parent and document history", () => {+ const source = transpileModule(readFileSync(join(__dirname, "MobileBackFoward.ts"), "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2020},+ }).outputText;+ for (const top of ["panel", "cell", "text", "menu", "dialog", "select", "input"]) {+ const calls: string[] = [];+ const panel = {style: {zIndex: "2"}, dispatchEvent: (event: CustomEvent) => calls.push(`panel:${event.detail}`)};+ const menu = {style: {zIndex: top === "menu" ? "4" : "1"},+ classList: {contains: (name: string) => name !== "fn__none"},+ dispatchEvent: (event: CustomEvent) => calls.push(`menu:${event.detail}`)};+ const dialogElement = {style: {zIndex: top === "dialog" ? "4" : "1"}};+ const select = top === "select" ? {style: {zIndex: "4"},+ dispatchEvent: (event: CustomEvent) => calls.push(`select:${event.detail}`)} : undefined;+ const input = top === "input" ? {style: {zIndex: "4"}} : undefined;+ const modules: Record<string, unknown> = {+ "../editor": {getCurrentEditor: (): undefined => undefined},+ "../../util/zIndex": {isAbove},+ "./nativeSelect": {getMobileSelectMenuElement: () => select},+ "../../dialog/anchoredInput": {getAnchoredInputMask: () => input,+ closeAnchoredInput: (save: boolean) => { assert.equal(save, true); calls.push("input"); }},+ "../../protyle/render/av/cellEditor": {closeAVCellEditor: () => calls.push("cell")},+ "../../protyle/render/av/richTextEditor": {destroyAVRichTextEditor: (save: boolean) => {+ assert.equal(save, true);+ calls.push("text");+ }},+ };+ const api = {} as typeof import("./MobileBackFoward");+ runInNewContext(source, {+ exports: api, require: (name: string) => modules[name] || {},+ CustomEvent: class {+ detail: unknown;+ constructor(_name: string, options: {detail: unknown}) { this.detail = options.detail; }+ },+ document: {getElementById: () => ({style: {}}), querySelector: (selector: string) => {+ if (selector === ".av__panel") {+ return panel;+ }+ if (selector === ".av__richtext-mask" && top === "text" ||+ selector === ".av__mask:not(.av__richtext-mask)" && top === "cell") {+ return {style: {zIndex: "3"}};+ }+ return undefined;+ }},+ window: {siyuan: {menus: {menu: {element: menu}}, dialogs: [{+ element: {querySelector: () => dialogElement}, destroy: () => calls.push("dialog"),+ }], mobile: {tabs: {goBack: () => {calls.push("navigate"); return Promise.resolve(true);}}}}},+ });+ api.goBack();+ assert.deepEqual(calls, [top === "panel" || top === "menu" || top === "select" ? `${top}:back` : top], top);+ }+});diff --git a/app/src/mobile/util/MobileBackFoward.ts b/app/src/mobile/util/MobileBackFoward.tsindex 67cd2cbf6b..6e4c63339b 100644--- a/app/src/mobile/util/MobileBackFoward.ts+++ b/app/src/mobile/util/MobileBackFoward.ts@@ -7,6 +7,7 @@ import {destroyAVRichTextEditor} from "../../protyle/render/av/richTextEditor";import {isAbove} from "../../util/zIndex";import {getMobileSelectMenuElement} from "./nativeSelect";import {closeAnchoredInput, getAnchoredInputMask} from "../../dialog/anchoredInput";+import {closeAVCellEditor} from "../../protyle/render/av/cellEditor";export const pushBack = () => {window.siyuan.mobile.tabs?.pushCurrent();@@ -20,30 +21,44 @@ export const goBack = () => {const editor = getCurrentEditor();const menuElement = document.getElementById("menu");const richTextElement = document.querySelector<HTMLElement>(".av__richtext-mask");+ const avPanelElement = document.querySelector<HTMLElement>(".av__panel");+ const avCellElement = document.querySelector<HTMLElement>(".av__mask:not(.av__richtext-mask)");const topDialog = window.siyuan.dialogs[window.siyuan.dialogs.length - 1];const selectMenuElement = getMobileSelectMenuElement();const inputMask = getAnchoredInputMask();const activeMenu = window.siyuan.menus.menu.element;+ const isAboveAVEditors = (element: HTMLElement) => [avPanelElement, avCellElement]+ .every(overlay => !overlay || !isAbove(overlay, element));if (inputMask && (!topDialog || isAbove(inputMask, topDialog.element.querySelector(".b3-dialog"))) &&(!selectMenuElement || isAbove(inputMask, selectMenuElement)) &&- (activeMenu.classList.contains("fn__none") || isAbove(inputMask, activeMenu))) {+ (activeMenu.classList.contains("fn__none") || isAbove(inputMask, activeMenu)) && isAboveAVEditors(inputMask)) {closeAnchoredInput(true);return;} else if (selectMenuElement && (!topDialog ||- isAbove(selectMenuElement, topDialog.element.querySelector(".b3-dialog")))) {+ isAbove(selectMenuElement, topDialog.element.querySelector(".b3-dialog"))) && isAboveAVEditors(selectMenuElement)) {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.classList.contains("fn__none") && isAboveAVEditors(activeMenu) &&+ (!richTextElement || !isAbove(richTextElement, activeMenu))) {window.siyuan.menus.menu.element.dispatchEvent(new CustomEvent("click", {detail: "back"}));return;} else if (window.siyuan.viewer && !window.siyuan.viewer.destroyed) {window.siyuan.viewer.destroy();return;} else if (richTextElement && (!topDialog ||- isAbove(richTextElement, topDialog.element.querySelector(".b3-dialog")))) {+ isAbove(richTextElement, topDialog.element.querySelector(".b3-dialog"))) && isAboveAVEditors(richTextElement)) {destroyAVRichTextEditor(true);return;+ } else if (avCellElement && (!topDialog ||+ isAbove(avCellElement, topDialog.element.querySelector(".b3-dialog"))) &&+ (!avPanelElement || isAbove(avCellElement, avPanelElement))) {+ closeAVCellEditor();+ return;+ } else if (avPanelElement && (!topDialog ||+ isAbove(avPanelElement, topDialog.element.querySelector(".b3-dialog")))) {+ avPanelElement.dispatchEvent(new CustomEvent("click", {detail: "back"}));+ return;} else if (window.siyuan.dialogs.length !== 0) {window.siyuan.dialogs[window.siyuan.dialogs.length - 1].destroy();return;diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.tsindex f3a0242e71..04bf66184d 100644--- a/app/src/protyle/gutter/index.ts+++ b/app/src/protyle/gutter/index.ts@@ -1598,6 +1598,9 @@ export class Gutter {embedContext.targetElement.querySelectorAll(":scope > [data-type=\"NodeListItem\"]").length === 1;const allowRemoval = allowStructuralMutation && !isOnlyTargetListItem;const type = nodeElement.getAttribute("data-type");+ if (type === "NodeAttributeView") {+ window.siyuan.menus.menu.element.setAttribute("data-sheet-expandable", "true");+ }const subType = nodeElement.getAttribute("data-subtype");const turnIntoSubmenu: IMenu[] = [];hideElements(["select"], protyle);diff --git a/app/src/protyle/render/av/action.ts b/app/src/protyle/render/av/action.tsindex 054283e514..30b0863934 100644--- a/app/src/protyle/render/av/action.ts+++ b/app/src/protyle/render/av/action.ts@@ -293,6 +293,7 @@ const openAVEditFieldMenu = (protyle: IProtyle, blockElement: HTMLElement, anchoconst menu = new Menu();getAVEditFieldMenuItems(protyle, blockElement).forEach(item => menu.addItem(item));if (isMobile()) {+ menu.element.setAttribute("data-sheet-expandable", "true");menu.fullscreen();} else {const rect = anchorElement.getBoundingClientRect();@@ -896,6 +897,7 @@ export const avContextmenu = (protyle: IProtyle, rowElement: HTMLElement | undef}const menu = new Menu();const rowElements = blockElement.querySelectorAll(".av__row--select:not(.av__row--header), .av__gallery-item--select");+ menu.element.setAttribute("data-sheet-expandable", "true");const selectedItemInfos = getAVSelectedItemInfos(blockElement);const selectedItems = getAVSelectedItems(blockElement);const primaryRows = selectedItemInfosdiff --git a/app/src/protyle/render/av/mobilePanel.test.ts b/app/src/protyle/render/av/mobilePanel.test.tsindex bff9394856..5039ae2a6b 100644--- a/app/src/protyle/render/av/mobilePanel.test.ts+++ b/app/src/protyle/render/av/mobilePanel.test.ts@@ -3,6 +3,7 @@ import {readFileSync} from "node:fs";import {test} from "node:test";import {runInNewContext} from "node:vm";import {ModuleKind, ScriptTarget, transpileModule} from "typescript";+import {getVisibleSheetViewport} from "../../../menus/sheetOpen";const compiled = transpileModule(readFileSync("src/protyle/render/av/mobilePanel.ts", "utf8"), {compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},@@ -12,9 +13,22 @@ const createPanel = () => {const listeners = new Map<string, (event: unknown) => void>();const scrim = {style: {opacity: ""}};const observers: Array<() => void> = [];+ const classes = new Set<string>();+ const resizeListeners = new Set<() => void>();+ let backTarget: HTMLElement;+ const backButtonClasses = new Set<string>();+ const backButton = {classList: {toggle: (name: string, force: boolean) => {+ if (force) {+ backButtonClasses.add(name);+ } else {+ backButtonClasses.delete(name);+ }+ }}};const menu = {- style: {height: "", transform: "", transition: ""},- classList: {add() {}},+ style: {height: "", transform: "", transition: "", setProperty() {}},+ classList: {add: (...names: string[]) => names.forEach(name => classes.add(name)),+ contains: (name: string) => classes.has(name)},+ setAttribute() {},clientHeight: 400,offsetHeight: 400,firstElementChild: undefined as undefined | {classList: {contains: (name: string) => boolean}},@@ -23,24 +37,32 @@ const createPanel = () => {this.insertedHTML.push(`${position}:${html}`);this.firstElementChild = {classList: {contains: (name: string) => html.includes(name)}};},- querySelectorAll: (): Element[] => [],- querySelector: (): Element => null,+ querySelectorAll: (selector: string): Element[] => selector.includes("block__icon--menu-back") && backTarget ? [backTarget] : [],+ querySelector: (selector: string) => selector.includes("sheet-back") ? backButton : null,addEventListener: (name: string, listener: (event: unknown) => void) => listeners.set(name, listener),};- let closes = 0;+ const actions: string[] = [];const panel = {querySelector: () => scrim,parentElement: {},- dispatchEvent: () => closes++,+ dispatchEvent: (event: CustomEvent) => actions.push(event.detail),};const exports: {bindMobileAVPanel?: (panel: unknown, menu: unknown) => void} = {};runInNewContext(compiled, {exports,- require: () => ({waitForSheetViewport: () => () => {}}),+ require: () => ({waitForSheetViewport: () => () => {}, getVisibleSheetViewport,+ escapeAttr: (value: string) => value || "", getSheetActionsHTML: () => "actions",+ setSheetExpanded: (_menu: unknown, expanded: boolean) => {+ if (expanded) {+ classes.add("b3-menu--expanded");+ } else {+ classes.delete("b3-menu--expanded");+ }+ }, updateMenuItemGroupClasses() {}}),window: {innerHeight: 800,- siyuan: {mobile: {size: {portrait: {height1: 800}}}},- addEventListener() {},+ siyuan: {languages: {back: "Back"}, mobile: {size: {portrait: {height1: 800}}}},+ addEventListener: (_name: string, callback: () => void) => resizeListeners.add(callback),},performance: {now: () => 1000},MutationObserver: class {@@ -52,32 +74,85 @@ const createPanel = () => {disconnect() {}},- CustomEvent: class {},+ CustomEvent: class {detail: unknown; constructor(_name: string, options: {detail: unknown}) { this.detail = options.detail; }},});exports.bindMobileAVPanel(panel, menu);- const drag = (sortable: boolean, offset: number) => {+ const drag = (sortable: boolean, offset: number, title = false) => {const target = {- closest: (selector: string) => sortable && selector.includes('[draggable="true"]') ? {} : null,+ closest: (selector: string) => sortable && selector.includes('[draggable="true"]') ||+ title && selector === ".b3-menu__title--actions" ? {} : null,parentElement: menu,};listeners.get("touchstart")({target, touches: [{clientX: 80, clientY: 100}]});listeners.get("touchmove")({touches: [{clientX: 80, clientY: 100 + offset}]});};- const end = () => listeners.get("touchend")({changedTouches: [{clientY: 300}]});+ const end = (offset = 200) => listeners.get("touchend")({changedTouches: [{clientY: 100 + offset}]});// 触发内容观察者,模拟数据库面板内容整体重绘const rerender = () => observers[0]();- return {menu, scrim, drag, end, rerender, closes: () => closes};+ const click = (type: string) => listeners.get("click")({+ target: {closest: () => ({dataset: {type}})}, detail: 1, preventDefault() {}, stopImmediatePropagation() {},+ });+ return {menu, scrim, drag, end, rerender, click, actions, classes, backButtonClasses,+ cancel: () => listeners.get("touchcancel")({}), resize: () => resizeListeners.forEach(callback => callback()),+ setBackTarget: () => {+ backTarget = {closest: (): null => null} as unknown as HTMLElement;+ rerender();+ }, closes: () => actions.filter(action => action === "close").length};};test("database panel handle is hosted by a root menu title", () => {const panel = createPanel();- assert.deepEqual(panel.menu.insertedHTML,- ['afterbegin:<div class="b3-menu__title b3-menu__title--root"></div>']);+ assert.equal(panel.menu.insertedHTML.length, 1);+ assert.match(panel.menu.insertedHTML[0], /b3-menu__title--actions/);+ assert.equal(panel.backButtonClasses.has("fn__none"), true);panel.menu.firstElementChild = undefined;panel.rerender();assert.equal(panel.menu.insertedHTML.length, 2);});+test("pulling the database panel title upward expands it and downward restores half height", () => {+ const panel = createPanel();+ panel.drag(false, -120, true);+ panel.end(-120);+ assert.equal(panel.classes.has("b3-menu--expanded"), true);+ assert.equal(panel.menu.style.height, "800px");+ panel.resize();+ assert.equal(panel.menu.style.height, "800px");+ panel.drag(false, 200, true);+ panel.end();+ assert.equal(panel.classes.has("b3-menu--expanded"), false);+ assert.ok(Math.abs(parseFloat(panel.menu.style.height) - 448) < .01);+ assert.equal(panel.closes(), 0);+});++test("canceling an upward gesture restores the half-height database panel", () => {+ const panel = createPanel();+ panel.drag(false, -120, true);+ panel.cancel();+ assert.equal(panel.classes.has("b3-menu--expanded"), false);+ assert.ok(Math.abs(parseFloat(panel.menu.style.height) - 448) < .01);+});++test("the expand button toggles full height without closing the panel", () => {+ const panel = createPanel();+ panel.click("sheet-expand");+ assert.equal(panel.classes.has("b3-menu--expanded"), true);+ panel.rerender();+ assert.equal(panel.classes.has("b3-menu--expanded"), true);+ panel.click("sheet-expand");+ assert.equal(panel.classes.has("b3-menu--expanded"), false);+ assert.equal(panel.closes(), 0);+});++test("the close and back controls use the database panel action entry", () => {+ const panel = createPanel();+ panel.click("sheet-close");+ panel.setBackTarget();+ assert.equal(panel.backButtonClasses.has("fn__none"), false);+ panel.click("sheet-back");+ assert.deepEqual(panel.actions, ["close", "back"]);+});+test("sorting the first view downward does not move or dismiss the database panel", () => {const panel = createPanel();panel.drag(true, 200);diff --git a/app/src/protyle/render/av/mobilePanel.ts b/app/src/protyle/render/av/mobilePanel.tsindex d04103cd73..9718dda400 100644--- a/app/src/protyle/render/av/mobilePanel.ts+++ b/app/src/protyle/render/av/mobilePanel.ts@@ -1,18 +1,34 @@import {updateMenuItemGroupClasses} from "../../../menus/menuGroup";-import {waitForSheetViewport} from "../../../menus/sheetOpen";+import {getVisibleSheetViewport, waitForSheetViewport} from "../../../menus/sheetOpen";+import {getSheetActionsHTML, setSheetExpanded} from "../../../menus/sheetActions";+import {escapeAttr} from "../../../util/escape";++export const getMobileAVPanelBackTarget = (menuElement: HTMLElement) =>+ Array.from(menuElement.querySelectorAll<HTMLElement>(+ ".b3-menu__items > .b3-menu__title .block__icon--menu-back, .av__select-list > .b3-menu__title .block__icon--menu-back"))+ .find(element => !element.closest(".fn__none"));export const bindMobileAVPanel = (panelElement: HTMLElement, menuElement: HTMLElement) => {menuElement.classList.add("b3-menu--fullscreen", "b3-menu--sheet");+ menuElement.setAttribute("data-prevent-swipe", "true");+ menuElement.style.maxHeight = "";const scrimElement = panelElement.querySelector<HTMLElement>(".b3-dialog__scrim");const updateHeight = () => {const size = window.siyuan.mobile.size;const orientation = size.isLandscape ? size.landscape : size.portrait;- menuElement.style.height = Math.max(window.innerHeight, orientation?.height1 || 0) * .56 + "px";+ const viewport = getVisibleSheetViewport(window.innerHeight, window.visualViewport);+ const fullHeight = Math.max(window.innerHeight, orientation?.height1 || 0);+ menuElement.style.height = (menuElement.classList.contains("b3-menu--expanded") ? viewport.height :+ Math.min(fullHeight * .56, viewport.height)) + "px";+ menuElement.style.setProperty("--b3-menu-sheet-bottom", viewport.bottomOffset + "px");};const updateContent = () => {- // 抓手统一由 b3-menu__title 的伪元素绘制,与其它底部面板保持一致- if (!menuElement.firstElementChild?.classList.contains("b3-menu__title")) {- menuElement.insertAdjacentHTML("afterbegin", '<div class="b3-menu__title b3-menu__title--root"></div>');+ // 独立标题栏保留返回、展开和关闭入口,内容重绘不改变编辑控件及其事件绑定。+ if (!menuElement.firstElementChild?.classList.contains("b3-menu__title--actions")) {+ menuElement.insertAdjacentHTML("afterbegin", `<div class="b3-menu__title b3-menu__title--root b3-menu__title--actions">+ <button type="button" class="block__icon block__icon--show block__icon--touch ariaLabel fn__none" data-type="sheet-back" aria-label="${escapeAttr(window.siyuan.languages.back)}"><svg><use xlink:href="#iconLeft"></use></svg></button>+ ${getSheetActionsHTML()}+</div>`);}// 保留原有节点和事件绑定,标题的返回操作仍由数据库面板处理menuElement.querySelectorAll(".b3-menu__items, .av__select-list").forEach((itemsElement) => {@@ -33,6 +49,8 @@ export const bindMobileAVPanel = (panelElement: HTMLElement, menuElement: HTMLElvisibleItems[0]?.classList.add("b3-menu__item--group-first");visibleItems[visibleItems.length - 1]?.classList.add("b3-menu__item--group-last");});+ menuElement.querySelector('[data-type="sheet-back"]')?.classList.toggle("fn__none", !getMobileAVPanelBackTarget(menuElement));+ setSheetExpanded(menuElement, menuElement.classList.contains("b3-menu--expanded"));};const contentObserver = new MutationObserver(() => {// 分组类更新不再次触发自身,页面替换和显隐切换都需要重新分组@@ -50,6 +68,8 @@ export const bindMobileAVPanel = (panelElement: HTMLElement, menuElement: HTMLElupdateContent();observeContent();window.addEventListener("resize", updateHeight);+ window.visualViewport?.addEventListener("resize", updateHeight);+ window.visualViewport?.addEventListener("scroll", updateHeight);// 初始定位不参与过渡,确保展开动画从屏幕外开始menuElement.style.transition = "none";menuElement.style.transform = "translateY(100%)";@@ -79,7 +99,7 @@ export const bindMobileAVPanel = (panelElement: HTMLElement, menuElement: HTMLEl}});- let start: {x: number, y: number, time: number};+ let start: {x: number, y: number, time: number, height: number, canExpand: boolean};let dragging = false;let suppressClickUntil = 0;const reset = () => {@@ -94,7 +114,7 @@ export const bindMobileAVPanel = (panelElement: HTMLElement, menuElement: HTMLElconst target = event.target as HTMLElement;// 可排序条目的触摸由拖拽桥接处理,避免向下排序时同时拖动整个面板。if (event.touches.length !== 1 ||- target.closest('input, textarea, select, [contenteditable="true"], .av__select-dropdown, [draggable="true"]') ||+ target.closest('.b3-menu__title--actions button, input, textarea, select, [contenteditable="true"], .av__select-dropdown, [draggable="true"]') ||menuElement.querySelector(".av__select-dropdown")) {return;}@@ -107,7 +127,8 @@ export const bindMobileAVPanel = (panelElement: HTMLElement, menuElement: HTMLElelement = element.parentElement;}const touch = event.touches[0];- start = {x: touch.clientX, y: touch.clientY, time: performance.now()};+ start = {x: touch.clientX, y: touch.clientY, time: performance.now(), height: menuElement.clientHeight,+ canExpand: !!target.closest(".b3-menu__title--actions") && !menuElement.classList.contains("b3-menu--expanded")};}, {passive: true});menuElement.addEventListener("touchmove", (event) => {if (!start || event.touches.length !== 1) {@@ -115,14 +136,18 @@ export const bindMobileAVPanel = (panelElement: HTMLElement, menuElement: HTMLEl}const touch = event.touches[0];const offset = touch.clientY - start.y;- if (!dragging && (offset <= 0 || Math.abs(touch.clientX - start.x) > offset)) {+ if (!dragging && ((offset <= 0 && !start.canExpand) || Math.abs(touch.clientX - start.x) > Math.abs(offset))) {start = undefined;return;}dragging = true;menuElement.style.transition = "none";- menuElement.style.transform = `translateY(${Math.max(0, offset)}px)`;- scrimElement.style.opacity = Math.max(0, 1 - offset / menuElement.clientHeight).toString();+ if (offset < 0) {+ menuElement.style.height = Math.min(window.innerHeight, start.height - offset) + "px";+ } else {+ menuElement.style.transform = `translateY(${offset}px)`;+ }+ scrimElement.style.opacity = Math.max(0, 1 - Math.max(0, offset) / menuElement.clientHeight).toString();if (event.cancelable) {event.preventDefault();}@@ -132,22 +157,43 @@ export const bindMobileAVPanel = (panelElement: HTMLElement, menuElement: HTMLElreset();return;}- const offset = Math.max(0, event.changedTouches[0].clientY - start.y);- const velocity = offset / Math.max(1, performance.now() - start.time);- const shouldClose = offset > Math.min(120, menuElement.clientHeight * .25) ||- (offset > 20 && velocity > .6);+ const offset = event.changedTouches[0].clientY - start.y;+ const velocity = Math.abs(offset) / Math.max(1, performance.now() - start.time);+ const shouldExpand = start.canExpand && (offset < -40 || (offset < -20 && velocity > .6));+ const shouldClose = offset > Math.min(120, start.height * .25) || (offset > 20 && velocity > .6);suppressClickUntil = performance.now() + 300;reset();- if (shouldClose) {+ if (shouldExpand) {+ setSheetExpanded(menuElement, true);+ } else if (shouldClose && menuElement.classList.contains("b3-menu--expanded")) {+ setSheetExpanded(menuElement, false);+ } else if (shouldClose) {// 复用关闭入口,确保日期、关联等编辑值提交及嵌套菜单关闭顺序一致panelElement.dispatchEvent(new CustomEvent("click", {detail: "close"}));}+ updateHeight();+ });+ menuElement.addEventListener("touchcancel", () => {+ reset();+ updateHeight();});- menuElement.addEventListener("touchcancel", reset);menuElement.addEventListener("click", (event) => {if (performance.now() < suppressClickUntil && typeof event.detail === "number") {event.preventDefault();event.stopImmediatePropagation();+ return;+ }+ const action = (event.target as HTMLElement).closest<HTMLElement>("[data-type^=\"sheet-\"]")?.dataset.type;+ if (!action) {+ return;+ }+ event.preventDefault();+ event.stopImmediatePropagation();+ if (action === "sheet-expand") {+ setSheetExpanded(menuElement, !menuElement.classList.contains("b3-menu--expanded"));+ updateHeight();+ } else {+ panelElement.dispatchEvent(new CustomEvent("click", {detail: action === "sheet-back" ? "back" : "close"}));}}, true);@@ -157,6 +203,8 @@ export const bindMobileAVPanel = (panelElement: HTMLElement, menuElement: HTMLElcontentObserver.disconnect();removalObserver.disconnect();window.removeEventListener("resize", updateHeight);+ window.visualViewport?.removeEventListener("resize", updateHeight);+ window.visualViewport?.removeEventListener("scroll", updateHeight);}});removalObserver.observe(panelElement.parentElement, {childList: true});diff --git a/app/src/protyle/render/av/openMenuPanel.ts b/app/src/protyle/render/av/openMenuPanel.tsindex eef130601e..f2f3345bc3 100644--- a/app/src/protyle/render/av/openMenuPanel.ts+++ b/app/src/protyle/render/av/openMenuPanel.ts@@ -12,7 +12,7 @@ import {prepareFilterColumns} from "./filter";import {Constants} from "../../../constants";import {hideElements} from "../../ui/hideElements";import {isMobile} from "../../../util/functions";-import {bindMobileAVPanel} from "./mobilePanel";+import {bindMobileAVPanel, getMobileAVPanelBackTarget} from "./mobilePanel";import {bindSwitcherEvent, getFieldsByData, getSwitcherHTML} from "./view";import {focusBlock} from "../../util/selection";import {getFieldIdByCellElement} from "./row";@@ -227,6 +227,16 @@ export const openMenuPanel = (options: IOpenAVPanelOptions) => {type = (event.detail as { type: string }).type;target = (event.detail as { target: HTMLElement }).target;}+ if (isMobile() && (type === "back" || type === "close")) {+ // 系统返回与标题栏共用导航及提交入口,先结束当前输入框的编辑。+ if (document.activeElement && menuElement.contains(document.activeElement)) {+ (document.activeElement as HTMLElement).blur();+ }+ if (type === "back") {+ target = getMobileAVPanelBackTarget(menuElement);+ type = target?.dataset.type || "close";+ }+ }const selectedElement = target?.closest(".b3-chip--middle") as HTMLElement;if (options.type === "select" && selectedElement?.parentElement.classList.contains("b3-chips") &&!target.closest('[data-type="removeCellOption"]')) {diff --git a/app/src/protyle/render/av/panels/lifecycle.test.ts b/app/src/protyle/render/av/panels/lifecycle.test.tsindex 270e3afda9..e0c78e87d2 100644--- a/app/src/protyle/render/av/panels/lifecycle.test.ts+++ b/app/src/protyle/render/av/panels/lifecycle.test.ts@@ -12,6 +12,7 @@ const createPanel = (mobile = false) => {const observers: Array<() => void> = [];let context: IAVPanelContext;let existing = false;+ let backTarget: HTMLElement;const menuClasses = new Set<string>();const menu = {isConnected: true, clientWidth: 100, dataset: {}, querySelector: (): null => null,classList: {contains: (name: string) => menuClasses.has(name)}};@@ -27,6 +28,7 @@ const createPanel = (mobile = false) => {const dependencies = new Proxy({getPageSize: () => ({}), getFieldsByData: (data: IAV & {fields: IAVColumn[]}) => data.fields,escapeAttr: (value: string) => value, isMobile: () => mobile,+ getMobileAVPanelBackTarget: () => backTarget,getAVPanelDescriptor: () => ({render: (value: IAVPanelContext) => { context = value; value.html = "panel"; return true; },bind: (value: IAVPanelContext) => { value.closeCB = () => calls.push("closeCB"); }}),dispatchAVPanelAction: (value: IAVPanelContext) => { assert.equal(value, context); calls.push("action"); return "handled"; },@@ -48,6 +50,9 @@ const createPanel = (mobile = false) => {const open = exports.openMenuPanel as typeof import("../openMenuPanel").openMenuPanel;const click = (detail: unknown) => events.get("click")({detail, target: {dataset: {}, closest: (): null => null}, preventDefault: () => {}, stopPropagation: () => {}});return {open, options, calls, click, observers, menuClasses, resize: () => events.get("resize")({}),+ setBackTarget: () => {+ backTarget = {dataset: {type: "go-properties"}, closest: (): null => null} as unknown as HTMLElement;+ },get context() { return context; }, setExisting: () => { existing = true; }};};@@ -64,6 +69,22 @@ test("window resizing uses the automation height constraint only while its panelassert.deepEqual(h.calls, ["setPosition"]);});+test("mobile back returns within a database panel and closes the root through its save callback", async () => {+ const h = createPanel(true);+ h.options.keepMenuOpen = true;+ h.open(h.options);+ h.calls.length = 0;+ h.setBackTarget();+ await h.click("back");+ assert.deepEqual(h.calls, ["action"]);+ const root = createPanel(true);+ root.options.keepMenuOpen = true;+ root.open(root.options);+ root.calls.length = 0;+ await root.click("back");+ assert.deepEqual(root.calls, ["closeCB", "remove", "focusBlock"]);+});+test("opening an existing panel destroys it without fetching or binding another panel", () => {const h = createPanel();h.setExisting();