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 font family selection https://github.com/siyuan-note/siyuan/issues/20557
Danielc6a73d5f866a
diff --git a/app/src/assets/scss/main/_mobile.scss b/app/src/assets/scss/main/_mobile.scssindex 8c705ba2fe..f6e5d203de 100644--- a/app/src/assets/scss/main/_mobile.scss+++ b/app/src/assets/scss/main/_mobile.scss@@ -1534,6 +1534,12 @@ body.mobile-topbar--merged {}}+ &__font-family {+ margin: 4px 8px 4px 0;+ min-height: 40px;+ text-align: left;+ }+&__font-size {align-items: center;box-sizing: border-box;diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.tsindex f20615befd..a81b12bed7 100644--- a/app/src/mobile/util/keyboardToolbar.ts+++ b/app/src/mobile/util/keyboardToolbar.ts@@ -73,7 +73,7 @@ import {getInlineFontFamilyLabel,getFontFamilyState,getInlineFontFamilyValue,- renderMobileFontFamilyMenu,+ openFontFamilyMenu,} from "../../protyle/toolbar/fontFamilyMenu";import {notifyMobileKeyboardChange} from "./mobileKeyboardChange";import {getEditorFocusRange, restoreEditorFocusRange} from "../../protyle/util/editorFocus";@@ -103,6 +103,7 @@ import {getCaretOverflowDirection, getCaretScrollDelta} from "../../protyle/wysiconst getCurrentEditor = () => getMobileToolbarProtyle()?.getInstance() || getDocumentEditor();let toolbarProtyle: IProtyle;+let fontFamilyMenu: {element: HTMLElement, protyle: IProtyle} | undefined;let unmountLiteSlashMenu: (() => void) | undefined;const applyKeyboardToolbarEntries = (element: HTMLElement, toolbar: Array<string | IMenuItem>) => {@@ -666,9 +667,8 @@ export const renderTextMenu = (protyle: IProtyle, toolbarElement: Element) => {</div><div data-id="fontFamily" class="keyboard__slash-title${disableFontFamily ? " fn__none" : ""}">${window.siyuan.languages.fontFamily}</div><div data-id="fontFamilyWrap" class="keyboard__slash-block${disableFontFamily ? " fn__none" : ""}">- <button class="keyboard__slash-item" data-action="fontFamilyMenu">- <span class="keyboard__slash-icon" data-type="fontFamilyPreview">A</span>- <span class="keyboard__slash-text">${escapeHtml(getInlineFontFamilyLabel(fontFamilyState))}</span>+ <button class="b3-select keyboard__font-family fn__flex-1" data-action="fontFamilyMenu" data-menu="true" aria-haspopup="listbox" aria-expanded="false">+ <span data-type="fontFamilyPreview">${escapeHtml(getInlineFontFamilyLabel(fontFamilyState))}</span></button></div><div data-id="fontSize" class="keyboard__slash-title${disableFont ? " fn__none" : ""}">${window.siyuan.languages.fontSize}</div>@@ -888,6 +888,48 @@ const hideAndroidKeyboardForPanel = (protyle: IProtyle) => {}, 100);};+const openMobileFontFamilyMenu = (protyle: IProtyle, target: HTMLElement, appearance = false) => {+ if (!protyle || protyle.disabled || window.siyuan.config.readonly) {+ return;+ }+ const range = protyle.toolbar.range.cloneRange();+ const nodes = getFontNodeElements(protyle);+ const state = getFontFamilyState(protyle, nodes);+ const valid = () => getCurrentEditor()?.protyle === protyle && !protyle.disabled &&+ !window.siyuan.config.readonly && target.isConnected &&+ range.startContainer.isConnected && range.endContainer.isConnected;+ preventKeyboardToolbarRender();+ void openFontFamilyMenu(target, {+ ...state,+ isOpenValid: valid,+ onInteraction: preventKeyboardToolbarRender,+ onOpen: element => { fontFamilyMenu = {element, protyle}; },+ onClose() {+ const searchFocused = fontFamilyMenu?.element.contains(document.activeElement);+ fontFamilyMenu = undefined;+ if (searchFocused) {+ activeBlur(true);+ }+ },+ onSelect(family) {+ if (!valid()) {+ return;+ }+ protyle.toolbar.range = range;+ fontEvent(protyle, nodes, "fontFamily", getInlineFontFamilyValue(family), false);+ if (appearance) {+ const toolbarElement = document.getElementById("keyboardToolbar");+ const utilElement = toolbarElement.querySelector(".keyboard__util");+ const scrollTop = utilElement.scrollTop;+ renderTextMenu(protyle, toolbarElement);+ utilElement.scrollTop = scrollTop;+ } else {+ restoreKeyboardToolbarRange(protyle, protyle.toolbar.range);+ }+ },+ });+};+const resetKeyboardToolbarUtilButtons = () => {unmountLiteSlashMenu?.();unmountLiteSlashMenu = undefined;@@ -933,6 +975,10 @@ const hideKeyboardToolbarUtil = (restoreKeyboard = false) => {};export const hideKeyboardToolbarUtilOnEditorClick = () => {+ if (fontFamilyMenu && fontFamilyMenu.protyle === getCurrentEditor()?.protyle &&+ fontFamilyMenu.element.contains(document.activeElement)) {+ return;+ }const toolbarElement = document.getElementById("keyboardToolbar");if (!showUtil && (!toolbarElement || toolbarElement.clientHeight <= 100)) {return;@@ -1102,6 +1148,12 @@ const showKeyboardToolbarElement = () => {const toolbarElement = document.getElementById("keyboardToolbar");if (["INPUT", "TEXTAREA"].includes(document.activeElement?.tagName) &&!toolbarElement.contains(document.activeElement)) {+ if (keyboardPanelTop !== undefined && fontFamilyMenu && fontFamilyMenu.protyle === getCurrentEditor()?.protyle &&+ fontFamilyMenu.element.contains(document.activeElement)) {+ // 字体搜索使用独立菜单,保留底层外观面板及选区。+ notifyMobileKeyboardChange(true);+ return;+ }// 普通输入框可能保留文档选区,不能据此恢复编辑焦点或显示文档工具栏。keyboardPanelClosing = false;hideKeyboardToolbarUtil();@@ -1627,38 +1679,9 @@ export const initKeyboardToolbar = () => {const target = event.target as HTMLElement;const liteSlashBtnElement = target.closest<HTMLElement>(".keyboard__util .protyle-hint .keyboard__slash-item[data-value]");const slashBtnElement = liteSlashBtnElement || hasClosestByClassName(target, "keyboard__slash-item");- if (slashBtnElement && slashBtnElement.dataset.action === "fontFamilyMenu") {- const range = protyle.toolbar.range.cloneRange();- const nodeElements = getFontNodeElements(protyle);- const fontFamilyState = getFontFamilyState(protyle, nodeElements);- const utilElement = toolbarElement.querySelector(".keyboard__util") as HTMLElement;- const isFontFamilyMenuValid = () => getCurrentEditor()?.protyle === protyle &&- toolbarElement.clientHeight > 100 && range.startContainer.isConnected &&- range.endContainer.isConnected && toolbarElement.querySelector('.keyboard__action[data-type="text"]')- ?.classList.contains("protyle-toolbar__item--current") === true;- preventKeyboardToolbarRender();- void renderMobileFontFamilyMenu(utilElement, {- ...fontFamilyState,- isOpenValid: isFontFamilyMenuValid,- onBack() {- if (!isFontFamilyMenuValid()) {- return;- }- protyle.toolbar.range = range;- renderTextMenu(protyle, toolbarElement);- focusByRange(range);- },- onInteraction: preventKeyboardToolbarRender,- onSelect(family) {- if (!isFontFamilyMenuValid()) {- return;- }- protyle.toolbar.range = range;- fontEvent(protyle, nodeElements, "fontFamily", getInlineFontFamilyValue(family), false);- renderTextMenu(protyle, toolbarElement);- focusByRange(protyle.toolbar.range);- }- });+ const fontFamilyButton = target.closest<HTMLElement>('[data-action="fontFamilyMenu"]');+ if (fontFamilyButton) {+ openMobileFontFamilyMenu(protyle, fontFamilyButton, true);event.preventDefault();event.stopPropagation();return;@@ -1824,7 +1847,11 @@ export const initKeyboardToolbar = () => {protyle.toolbar.setInlineMark(protyle, type, "toolbar");}return;- } else if (type === "font-family" || type === "font-size") {+ } else if (type === "font-family") {+ hideKeyboardToolbarUtil();+ openMobileFontFamilyMenu(protyle, buttonElement);+ return;+ } else if (type === "font-size") {if (buttonElement.classList.contains("protyle-toolbar__item--current")) {hideKeyboardToolbarUtil(true);restoreKeyboardToolbarRange(protyle, range);@@ -1853,32 +1880,12 @@ export const initKeyboardToolbar = () => {finish();};preventKeyboardToolbarRender();- if (type === "font-family") {- const state = getFontFamilyState(protyle, nodes);- if (state.disabled) {+ util.replaceChildren(createFontSizePicker(protyle, value => apply("fontSize", value), preventKeyboardToolbarRender, () => {+ if (valid()) {+ protyle.toolbar.range = savedRange;finish();- return;}- void renderMobileFontFamilyMenu(util, {- ...state,- isOpenValid: valid,- onInteraction: preventKeyboardToolbarRender,- onBack() {- if (valid()) {- protyle.toolbar.range = savedRange;- finish();- }- },- onSelect: family => apply("fontFamily", getInlineFontFamilyValue(family)),- });- } else {- util.replaceChildren(createFontSizePicker(protyle, value => apply("fontSize", value), preventKeyboardToolbarRender, () => {- if (valid()) {- protyle.toolbar.range = savedRange;- finish();- }- }));- }+ }));showKeyboardToolbarUtil(protyle.contentElement.scrollTop);hideAndroidKeyboardForPanel(protyle);return;diff --git a/app/src/protyle/toolbar/fontFamilyMenu.test.ts b/app/src/protyle/toolbar/fontFamilyMenu.test.tsindex c8b1adfe58..ff48008bef 100644--- a/app/src/protyle/toolbar/fontFamilyMenu.test.ts+++ b/app/src/protyle/toolbar/fontFamilyMenu.test.ts@@ -1,58 +1,272 @@import * as assert from "node:assert/strict";-import {readFileSync} from "node:fs";-import {join} from "node:path";+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 {runInNewContext} from "node:vm";-import {createSourceFile, isVariableStatement, ScriptTarget, transpileModule} from "typescript";+import {promisify} from "node:util";+import {compile, Logger} from "sass";+import {createSourceFile, forEachChild, isCallExpression, isVariableStatement, ModuleKind, Node, ScriptTarget, transpileModule} from "typescript";-const source = createSourceFile("fontFamilyMenu.ts", readFileSync(join(__dirname, "fontFamilyMenu.ts"), "utf8"),- ScriptTarget.Latest);-const declaration = source.statements.find(node => isVariableStatement(node) &&- node.declarationList.declarations.some(item => item.name.getText(source) === "renderMobileFontFamilyMenu"));-assert.ok(declaration);-const code = transpileModule(declaration.getText(source).replace("export ", "") +- "\nrenderMobileFontFamilyMenu;", {compilerOptions: {target: ScriptTarget.ES2020}}).outputText;+const browserCases = async (sources: Record<string, string>, toolbarSource: string, dropdown: string, css: string, themes: string[]) => {+ const check: typeof assert = require("node:assert/strict");+ let mobile = true;+ let readonly = false;+ let fonts = Array.from({length: 60}, (_, index) => ({family: `Font ${index}`, displayName: `Font ${index}`, weight: 400}));+ let pendingFonts: Promise<{fontItems: typeof fonts}>;+ const modules: Record<string, {exports: any}> = {};+ const externals = {+ "util/functions": {isMobile: () => mobile},+ "protyle/util/compatibility": {getEventName: () => "click", isInMobileApp: () => false, updateHotkeyTip: (value: string) => value},+ "util/zIndex": {isScrollAboveMenu: () => false},+ "layout/getTopBarHeight": {getTopBarHeight: () => 0},+ constants: {Constants: {TIMEOUT_DBLCLICK: 10, ATTRIBUTE_MENU_KEYMAP: "data-keymap"}},+ "protyle/undo": {electronUndo() {}},+ "menus/menuKeyboard": {setMenuInputCurrent() {}},+ "plugin/EventBusCore": {forEachPluginSubscriber() {}},+ "mobile/util/keyboardToolbar": {activeBlur: () => (document.activeElement as HTMLElement)?.blur()},+ "block/popoverLifecycle": {setPopoverMenuOpen() {}},+ "config/entryVisibility/runtime": {applyMenuEntryVisibility() {}},+ "util/availableFont": {loadAvailableFonts: () => pendingFonts || Promise.resolve({fontItems: fonts})},+ "util/fontPreview": {observeFontPreview: () => () => {}},+ "protyle/util/selection": {},+ };+ 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 dependency ${name}`);+ const module = {exports: {}};+ modules[name] = module;+ new Function("require", "exports", sources[name])((dependency: string) => {+ const parts = name.split("/");+ parts.pop();+ dependency.split("/").forEach(part => part === ".." ? parts.pop() : part !== "." && parts.push(part));+ return load(parts.join("/"));+ }, module.exports);+ return module.exports;+ };+ const style = document.createElement("style");+ style.textContent = css + ":root {--b3-font-size:16px;} body {margin:0;} button {font:inherit;}";+ document.head.append(style);+ const themeStyle = document.createElement("style");+ document.head.append(themeStyle);+ Object.assign(window, {siyuan: {languages: {default: "Default", back: "Back", close: "Close", searchPlaceholder: "Search",+ fontFamily: "Font", loading: "Loading", expand: "Expand", collapse: "Collapse"}, zIndex: 1, storage: {},+ config: {get readonly() { return readonly; }}, mobile: {size: {portrait: {height1: innerHeight}}}, menus: {}}});+ const menuElement = document.createElement("div");+ menuElement.id = "commonMenu";+ menuElement.className = "b3-menu fn__none";+ menuElement.innerHTML = '<div class="b3-menu__title fn__none"><span class="b3-menu__label"></span></div><div class="b3-menu__items"></div>';+ const scrim = document.createElement("div");+ scrim.id = "commonMenuScrim";+ scrim.className = "b3-menu__scrim";+ document.body.append(scrim, menuElement);+ const {Menu}: typeof import("../../menus/Menu") = load("menus/Menu");+ const menu = new Menu(menuElement);+ window.siyuan.menus.menu = menu;+ const api: typeof import("./fontFamilyMenu") = load("protyle/toolbar/fontFamilyMenu");+ const escape = load("util/escape");+ const toolbar = document.createElement("div");+ toolbar.id = "keyboardToolbar";+ toolbar.className = "keyboard";+ toolbar.style.height = "300px";+ toolbar.innerHTML = '<div class="keyboard__bar"><button class="keyboard__action protyle-toolbar__item--current" data-type="text">Appearance</button></div><div class="keyboard__util"></div>';+ const util = toolbar.querySelector<HTMLElement>(".keyboard__util");+ util.innerHTML = new Function("disableFontFamily", "escapeHtml", "getInlineFontFamilyLabel", "fontFamilyState",+ "return `" + dropdown + "`;")(false, escape.escapeHtml, () => "Default", {});+ document.body.append(toolbar);+ const button = util.querySelector<HTMLElement>('[data-action="fontFamilyMenu"]');+ const editor = document.createElement("div");+ editor.contentEditable = "true";+ editor.textContent = "Selected text";+ document.body.prepend(editor);+ const range = document.createRange();+ range.selectNodeContents(editor);+ const protyle = {disabled: false, toolbar: {range}, wysiwyg: {element: editor}};+ let current = protyle;+ const applied: string[] = [];+ let restored = 0;+ const dependencies = {+ getCurrentEditor: () => ({protyle: current}),+ getFontNodeElements: () => [editor],+ getFontFamilyState: () => ({disabled: false, mixed: false, family: undefined as string | undefined}),+ preventKeyboardToolbarRender() {},+ ...api,+ fontEvent: (_owner: unknown, _nodes: unknown, _style: string, value: string) => applied.push(value),+ renderTextMenu: () => { button.querySelector("span").textContent = "Font 12"; },+ restoreKeyboardToolbarRange: () => restored++,+ activeBlur: () => (document.activeElement as HTMLElement)?.blur(),+ keyboardPanelTop: 200,+ notifyMobileKeyboardChange() {},+ hideKeyboardToolbarUtil: () => check.fail("font searches must preserve the appearance panel"),+ hasClosestByClassName: load("protyle/util/hasClosest").hasClosestByClassName,+ takeMenuKeyboard() {}, moved: false,+ };+ const controls = new Function(...Object.keys(dependencies), "let fontFamilyMenu;\n" + toolbarSource ++ "\nreturn {openMobileFontFamilyMenu, hideKeyboardToolbarUtilOnEditorClick, showKeyboardToolbarElement, handler};")(...Object.values(dependencies));+ toolbar.addEventListener("touchend", controls.handler);+ const settle = async () => {+ await new Promise(resolve => setTimeout(resolve, 350));+ };+ const tap = async (element: Element) => {+ check.ok(element, "touch target is present");+ const rect = element.getBoundingClientRect();+ const x = element === scrim ? 20 : rect.left + rect.width / 2;+ const y = element === scrim ? 20 : rect.top + rect.height / 2;+ check.ok(element.contains(document.elementFromPoint(x, y)),+ "touch target is not obscured by another control");+ await require("electron").ipcRenderer.invoke("font-tap", x, y);+ await settle();+ };+ const search = () => menuElement.querySelector<HTMLInputElement>('[data-type="font-family-search"]');+ for (const theme of themes) {+ themeStyle.textContent = theme;+ for (const size of [320, 420]) {+ for (const fontSize of [16, 32]) {+ toolbar.style.fontSize = `${fontSize}px`;+ util.style.width = size + "px";+ check.ok(button.getBoundingClientRect().width >= size - 20, "font dropdown spans both appearance columns");+ check.ok(button.getBoundingClientRect().height >= 40, "dropdown retains a mobile touch target");+ check.notEqual(getComputedStyle(button).backgroundImage, "none", "shared select styling provides the dropdown arrow");+ }+ }+ }+ toolbar.style.fontSize = "";+ util.style.width = "";+ await tap(button);+ check.ok(menuElement.classList.contains("b3-menu--sheet"));+ check.equal(button.getAttribute("aria-expanded"), "true");+ check.equal(menuElement.querySelector('[data-action="fontFamilyBack"]'), null);+ check.ok(util.contains(button), "font list opens outside the original appearance panel");+ check.notEqual(document.activeElement, search(), "opening does not summon the search keyboard");+ check.ok(menuElement.getBoundingClientRect().top > 100, "font sheet opens from the bottom");+ await tap(menuElement.querySelector('[data-type="sheet-close"]'));+ check.ok(menuElement.classList.contains("fn__none"), "a real touch closes the sheet");+ check.ok(util.contains(button));+ check.equal(button.getAttribute("aria-expanded"), "false");+ await tap(button);+ await tap(search());+ check.equal(document.activeElement, search());+ controls.showKeyboardToolbarElement();+ controls.hideKeyboardToolbarUtilOnEditorClick();+ search().value = "Font 12";+ search().dispatchEvent(new InputEvent("input", {bubbles: true}));+ const visible = menuElement.querySelectorAll('[role="option"]:not(.fn__none)');+ check.equal(visible.length, 1);+ await tap(visible[0]);+ check.ok(menuElement.classList.contains("fn__none"));+ check.equal(applied.length, 1);+ check.match(applied[0], /Font 12/);+ check.equal(restored, 0, "appearance selection does not reopen the editor keyboard");+ check.equal(button.querySelector("span").textContent, "Font 12");+ await tap(button);+ search().dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true}));+ await settle();+ check.ok(menuElement.classList.contains("fn__none"));+ await tap(button);+ await tap(scrim);+ check.ok(menuElement.classList.contains("fn__none"));+ let resolve: (value: {fontItems: typeof fonts}) => void;+ pendingFonts = new Promise(done => { resolve = done; });+ const opening = api.openFontFamilyMenu(button, {disabled: false, mixed: false, onSelect() {}});+ await settle();+ await tap(menuElement.querySelector('[data-type="sheet-close"]'));+ resolve({fontItems: fonts});+ await opening;+ check.ok(menuElement.classList.contains("fn__none"));+ check.equal(search(), null, "late loading cannot reopen a dismissed font menu");+ pendingFonts = undefined;+ await tap(button);+ current = {...protyle};+ await tap(menuElement.querySelector('[role="option"]'));+ check.equal(applied.length, 1, "changing editors invalidates the saved font operation");+ current = protyle;+ readonly = true;+ await tap(button);+ check.ok(menuElement.classList.contains("fn__none"));+ readonly = false;+ const direct = document.createElement("button");+ document.body.append(direct);+ controls.openMobileFontFamilyMenu(protyle, direct);+ await settle();+ await tap(menuElement.querySelector('[role="option"]'));+ check.equal(restored, 1, "the independent font entry resumes editor input after selection");+ check.equal(applied.length, 2);+ direct.remove();+ toolbar.removeEventListener("touchend", controls.handler);+ toolbar.addEventListener("click", controls.handler);+ await tap(button);+ check.ok(menuElement.classList.contains("b3-menu--sheet"), "click-based mobile entry opens the same font sheet");+ await tap(menuElement.querySelector('[data-type="sheet-close"]'));+ toolbar.removeEventListener("click", controls.handler);+ mobile = false;+ fonts = [];+ await api.openFontFamilyMenu(button, {disabled: false, mixed: false, onSelect() {}});+ check.ok(!menuElement.classList.contains("b3-menu--sheet"));+ check.equal(document.activeElement, search(), "desktop keeps automatic search focus");+ search().dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true}));+ check.equal(document.activeElement, button, "desktop Escape returns focus to the dropdown");+ check.ok(menuElement.classList.contains("fn__none"));+ return "Font menu touch and layout cases passed";+};-test("mobile font loading keeps the picker visible without automatically opening the keyboard", async () => {- let complete: (fonts: unknown[]) => void;- const pending = new Promise(resolve => { complete = resolve; });- let focusCount = 0;- let bound = 0;- const input = {focus: () => focusCount++};- const element = {isConnected: true, innerHTML: "", querySelector: (selector: string) =>- selector.includes("data-font-family-request") ? element.innerHTML.includes("data-font-family-request") : input};- const render = runInNewContext(code, {- mobileRequestID: 0,- window: {siyuan: {languages: {loading: "Loading"}}},- loadFontFamilies: () => pending,- genFontPickerHTML: () => "Search and default font option",- bindFontPicker: () => bound++,+test("font menus preserve the mobile appearance panel and support real touch dismissal, search and selection", {timeout: 45000}, async () => {+ const names = ["menus/Menu", "menus/menuPosition", "menus/menuMouseScroll", "menus/menuGroup", "menus/sheetOpen", "menus/sheetActions",+ "menus/menuToggle", "plugin/Menu", "util/setPosition", "protyle/util/hasClosest", "protyle/toolbar/fontFamilyMenu",+ "protyle/toolbar/fontFamilyCore", "util/systemFontCore", "util/escape", "util/upDownHint"];+ const sources = Object.fromEntries(names.map(name => [name, transpileModule(readFileSync(path.join(__dirname, "../..", name + ".ts"), "utf8"), {+ compilerOptions: {target: ScriptTarget.ES2021, module: ModuleKind.CommonJS},+ }).outputText]));+ const toolbarText = readFileSync(path.join(__dirname, "../../mobile/util/keyboardToolbar.ts"), "utf8");+ const file = createSourceFile("keyboardToolbar.ts", toolbarText, ScriptTarget.Latest);+ const declarations = file.statements.filter(node => isVariableStatement(node) && node.declarationList.declarations.some(item =>+ ["openMobileFontFamilyMenu", "hideKeyboardToolbarUtilOnEditorClick", "showKeyboardToolbarElement"].includes(item.name.getText(file))));+ let handler: string;+ const visit = (node: Node) => {+ if (isCallExpression(node) && node.expression.getText(file) === "toolbarElement.addEventListener" &&+ node.arguments[0].getText(file).includes('"touchend"')) handler = node.arguments[1].getText(file);+ forEachChild(node, visit);+ };+ visit(file);+ assert.equal(declarations.length, 3);+ assert.ok(handler);+ const toolbarSource = transpileModule(declarations.map(node => node.getText(file).replace("export ", "")).join("\n") ++ `\nconst handler = ${handler};`, {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;+ const dropdown = toolbarText.slice(toolbarText.indexOf('<div data-id="fontFamilyWrap"'), toolbarText.indexOf('<div data-id="fontSize"'));+ const css = ["component/_menu.scss", "component/_list.scss", "component/_text-field.scss", "component/_select.scss", "component/_button.scss", "business/_block.scss", "util/_function.scss", "main/_mobile.scss"]+ .map(name => compile(path.join(__dirname, "../../assets/scss", name), {logger: Logger.silent}).css).join("\n");+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-font-menu-test-"));+ const script = path.join(temporary, "run.cjs");+ const themes = ["daylight", "midnight"].map(name => readFileSync(path.join(__dirname, `../../../appearance/themes/${name}/theme.css`), "utf8"));+ const invocation = `const __name = value => value; (${browserCases.toString()})(${JSON.stringify(sources)}, ${JSON.stringify(toolbarSource)}, ${JSON.stringify(dropdown)}, ${JSON.stringify(css)}, ${JSON.stringify(themes)})`;+ writeFileSync(script, `const {app, BrowserWindow, ipcMain} = 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:420, height:850, useContentSize:true,+ webPreferences:{nodeIntegration:true, contextIsolation:false, offscreen:true, backgroundThrottling:false}});+ win.webContents.debugger.attach("1.3");+ ipcMain.handle("font-tap", async (_event, x, y) => {+ await win.webContents.debugger.sendCommand("Input.dispatchTouchEvent", {type:"touchStart", touchPoints:[{x,y}]});+ await win.webContents.debugger.sendCommand("Input.dispatchTouchEvent", {type:"touchEnd", touchPoints:[]});});- const result = render(element, {isOpenValid: () => true});- assert.match(element.innerHTML, /Loading/);- complete([]);- await result;- assert.equal(element.innerHTML, "Search and default font option");- assert.equal(bound, 1);- assert.equal(focusCount, 0);-});--test("font responses cannot replace a mobile picker that has been closed", async () => {- let complete: (fonts: unknown[]) => void;- const pending = new Promise(resolve => { complete = resolve; });- const element = {isConnected: true, innerHTML: "", querySelector: () => true};- let open = true;- const render = runInNewContext(code, {- mobileRequestID: 0,- window: {siyuan: {languages: {loading: "Loading"}}},- loadFontFamilies: () => pending,- genFontPickerHTML: () => assert.fail("closed picker must not render"),- bindFontPicker: () => assert.fail("closed picker must not bind"),- });- const result = render(element, {isOpenValid: () => open});- open = false;- element.innerHTML = "Other panel";- complete([]);- await result;- assert.equal(element.innerHTML, "Other panel");+ try {+ await win.loadURL("about:blank");+ await win.webContents.debugger.sendCommand("Emulation.setTouchEmulationEnabled", {enabled:true, maxTouchPoints:1});+ console.log(await win.webContents.executeJavaScript(${JSON.stringify(invocation)}));+ 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: 40000, windowsHide: true});+ assert.match(result.stdout, /Font menu touch and layout cases passed/);+ } finally {+ assert.equal(path.dirname(path.resolve(temporary)), path.resolve(tmpdir()));+ assert.ok(path.basename(temporary).startsWith("siyuan-font-menu-test-"));+ rmSync(temporary, {recursive: true, force: true});+ }});diff --git a/app/src/protyle/toolbar/fontFamilyMenu.ts b/app/src/protyle/toolbar/fontFamilyMenu.tsindex 5764b046dd..0534975680 100644--- a/app/src/protyle/toolbar/fontFamilyMenu.ts+++ b/app/src/protyle/toolbar/fontFamilyMenu.ts@@ -12,6 +12,7 @@ import {upDownHint} from "../../util/upDownHint";import {Constants} from "../../constants";import {getBlockRanges} from "../util/selection";import {hasClosestBlock} from "../util/hasClosest";+import {isMobile} from "../../util/functions";import {FONT_FAMILY_EXCLUDED_BLOCK_TYPES,getInlineFontFamilySelection,@@ -27,7 +28,7 @@ export interface IInlineFontFamilyState {interface IFontFamilyPickerOptions extends IInlineFontFamilyState {isOpenValid?: () => boolean;- onBack?: () => void;+ onOpen?: (element: HTMLElement) => void;onClose?: () => void;onInteraction?: () => void;onSelect: (family?: string) => void;@@ -163,9 +164,8 @@ const genFontPickerHTML = (fonts: IFontItem[], options: IFontFamilyPickerOptionsconst id = `fontFamilyPicker${++pickerID}`;const listID = `${id}List`;const searchInput = `<input spellcheck="false" class="b3-text-field fn__flex-1" data-type="font-family-search" role="combobox" aria-expanded="true" aria-controls="${listID}" aria-label="${escapeAttr(window.siyuan.languages.fontFamily)}" placeholder="${escapeAttr(window.siyuan.languages.searchPlaceholder)}">`;- return `<div class="fn__flex-column${mobile ? "" : " b3-menu__filter"}" style="height:100%">+ return `<div class="fn__flex-column ${mobile ? "b3-menu__custom" : "b3-menu__filter"}" style="height:100%"><div class="fn__flex">- ${mobile ? `<button class="block__icon block__icon--show fn__flex-center" data-action="fontFamilyBack" aria-label="${escapeAttr(window.siyuan.languages.back)}"><svg><use xlink:href="#iconLeft"></use></svg></button><span class="fn__space"></span>` : ""}${searchInput}</div><div class="fn__hr"></div>@@ -176,7 +176,6 @@ const genFontPickerHTML = (fonts: IFontItem[], options: IFontFamilyPickerOptionsconst bindFontPicker = (element: HTMLElement, options: IFontFamilyPickerOptions) => {const listElement = element.querySelector<HTMLElement>('[data-type="font-family-list"]');const inputElement = element.querySelector<HTMLInputElement>('[data-type="font-family-search"]');- let removalObserver: MutationObserver;const syncActiveDescendant = () => {const activeElement = listElement.querySelector<HTMLElement>(".b3-list-item--focus");if (activeElement) {@@ -209,7 +208,6 @@ const bindFontPicker = (element: HTMLElement, options: IFontFamilyPickerOptions)};const cleanup = () => {cleanupPreview?.();- removalObserver?.disconnect();};const selectItem = (item: HTMLElement) => {options.onInteraction?.();@@ -236,12 +234,8 @@ const bindFontPicker = (element: HTMLElement, options: IFontFamilyPickerOptions)} else if (event.key === "Escape") {event.preventDefault();cleanup();- if (options.onBack) {- options.onBack();- } else {- window.siyuan.menus.menu.remove();- options.onClose?.();- }+ window.siyuan.menus.menu.remove();+ options.onClose?.();}});inputElement.addEventListener("input", (event: InputEvent) => {@@ -257,21 +251,6 @@ const bindFontPicker = (element: HTMLElement, options: IFontFamilyPickerOptions)selectItem(item);}});- element.querySelector<HTMLElement>('[data-action="fontFamilyBack"]')?.addEventListener("click", event => {- options.onInteraction?.();- event.preventDefault();- event.stopPropagation();- cleanup();- options.onBack?.();- });- if (options.onBack) {- removalObserver = new MutationObserver(() => {- if (!listElement.isConnected) {- cleanup();- }- });- removalObserver.observe(element, {childList: true});- }filterFontList();return cleanup;};@@ -292,8 +271,8 @@ const loadFontFamilies = async (currentFamily?: string) => {return fonts;};-let desktopRequestID = 0;-const desktopMenuIDs = new WeakMap<HTMLElement, string>();+let fontFamilyRequestID = 0;+const fontFamilyMenuIDs = new WeakMap<HTMLElement, string>();export const openFontFamilyMenu = async (target: HTMLElement, options: IFontFamilyPickerOptions) => {if (options.disabled) {@@ -302,16 +281,17 @@ export const openFontFamilyMenu = async (target: HTMLElement, options: IFontFamiawait toggleMenu({target: target,build: async (_menu, session) => {- const requestID = ++desktopRequestID;- if (!desktopMenuIDs.has(target)) {- desktopMenuIDs.set(target, `inlineFontFamily${requestID}`);+ const requestID = ++fontFamilyRequestID;+ if (!fontFamilyMenuIDs.has(target)) {+ fontFamilyMenuIDs.set(target, `inlineFontFamily${requestID}`);}let closed = false;let cleanup: () => void = undefined;- const menu = new Menu(desktopMenuIDs.get(target), () => {+ const menu = new Menu(fontFamilyMenuIDs.get(target), () => {closed = true;cleanup?.();target.setAttribute("aria-expanded", "false");+ options.onClose?.();});if (menu.isOpen) {return;@@ -321,17 +301,27 @@ export const openFontFamilyMenu = async (target: HTMLElement, options: IFontFamitype: "empty",label: `<div class="b3-menu__filter">${escapeHtml(window.siyuan.languages.loading)}</div>`,});+ const mobile = isMobile();+ if (mobile) {+ menu.element.setAttribute("data-sheet-expandable", "true");+ pickerElement.style.height = "100%";+ }const openMenu = () => {if (!session.isCurrent()) {return;}- const rect = target.getBoundingClientRect();- session.show(() => menu.open({x: rect.left, y: rect.bottom, h: rect.height, w: rect.width, target}));- menu.element.querySelector(".b3-menu__items").setAttribute("style", "overflow: initial");+ if (mobile) {+ session.show(() => menu.fullscreen("bottom"));+ } else {+ const rect = target.getBoundingClientRect();+ session.show(() => menu.open({x: rect.left, y: rect.bottom, h: rect.height, w: rect.width, target}));+ menu.element.querySelector(".b3-menu__items").setAttribute("style", "overflow: initial");+ }};target.setAttribute("aria-expanded", "true");openMenu();+ options.onOpen?.(menu.element);const fonts = await loadFontFamilies(options.family);if (!session.isCurrent()) {return;@@ -339,43 +329,35 @@ export const openFontFamilyMenu = async (target: HTMLElement, options: IFontFamiif (closed) {return;}- if (requestID !== desktopRequestID || !target.isConnected || options.isOpenValid?.() === false) {+ if (requestID !== fontFamilyRequestID || !target.isConnected || options.isOpenValid?.() === false) {menu.close();return;}if (target.tagName === "INPUT") {(target as HTMLInputElement).value = getInlineFontFamilyLabel(options);}- pickerElement.innerHTML = genFontPickerHTML(fonts, options, false);+ pickerElement.innerHTML = genFontPickerHTML(fonts, options, mobile);cleanup = bindFontPicker(pickerElement, {...options,- onClose: () => target.focus(),+ onClose: () => {+ if (!mobile) {+ target.focus();+ }+ },onSelect(family) {menu.close();options.onSelect(family);}});- openMenu();- menu.element.querySelector<HTMLInputElement>('[data-type="font-family-search"]')?.focus();+ if (!mobile) {+ openMenu();+ menu.element.querySelector<HTMLInputElement>('[data-type="font-family-search"]')?.focus();+ }},});};-let mobileRequestID = 0;--export const renderMobileFontFamilyMenu = async (element: HTMLElement, options: IFontFamilyPickerOptions) => {- const requestID = ++mobileRequestID;- element.innerHTML = `<div class="keyboard__slash-title" data-font-family-request="${requestID}">${window.siyuan.languages.loading}</div>`;- const fonts = await loadFontFamilies(options.family);- if (requestID !== mobileRequestID || !element.isConnected ||- !element.querySelector(`[data-font-family-request="${requestID}"]`) || options.isOpenValid?.() === false) {- return;- }- element.innerHTML = genFontPickerHTML(fonts, options, true);- bindFontPicker(element, options);-};-export const getInlineFontFamilyLabel = (state: IInlineFontFamilyState) => state.mixed ?window.siyuan.languages.mixed :(getFontFamilyDisplayName(loadedFontFamilies, state.family) || window.siyuan.languages.default);diff --git a/app/src/util/customFont.test.ts b/app/src/util/customFont.test.tsindex 533ef560ac..c0796e3a7f 100644--- a/app/src/util/customFont.test.ts+++ b/app/src/util/customFont.test.ts@@ -67,7 +67,7 @@ test("inline font picker uses the same available fonts on desktop and mobile", aassert.equal(fonts[0].family, font.family);assert.equal(menu.getInlineFontFamilyLabel({family: font.family}), font.displayName);const source = readFileSync(resolve(process.cwd(), "src/protyle/toolbar/fontFamilyMenu.ts"), "utf8");- assert.equal(source.split("await loadFontFamilies(options.family)").length - 1, 2);+ assert.equal(source.split("await loadFontFamilies(options.family)").length - 1, 1);});test("one unavailable font source does not hide the other source", async () => {