Skip to content

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

:sparkles: Improve mobile editing bars and configurable selection actions https://github.com/siyuan-note/siyuan/issues/19949

Danielec9486f7b1b1
diff --git a/app/src/assets/scss/main/_mobile.scss b/app/src/assets/scss/main/_mobile.scss
index 7475142c1e..1a962da20b 100644
--- a/app/src/assets/scss/main/_mobile.scss
+++ b/app/src/assets/scss/main/_mobile.scss
@@ -1342,6 +1342,11 @@ body.mobile-topbar--merged {
flex-direction: column;
z-index: 1;
+ &--selection {
+ width: calc(100% - 16px);
+ max-width: 480px;
+ }
+
&__dynamic {
overflow: auto;
display: flex;
diff --git a/app/src/config/entryVisibility/catalog.test.ts b/app/src/config/entryVisibility/catalog.test.ts
index a834abcb87..914f50af27 100644
--- a/app/src/config/entryVisibility/catalog.test.ts
+++ b/app/src/config/entryVisibility/catalog.test.ts
@@ -348,7 +348,7 @@ test("plugin top bar entries use the legacy unpinned list as their default visib
});
test("toolbar catalog follows the default toolbar declaration", () => {
- const children = getEntryCatalogChildren(TOOLBAR_ENTRY_ROOT_PATH);
+ const children = getEntryCatalogChildren(TOOLBAR_ENTRY_ROOT_PATH).filter(item => !item.key.startsWith("mobile-"));
assert.deepEqual(children.map((item) => item.key), DESKTOP_TOOLBAR_ENTRIES.map((item) => item.key));
assert.equal(children.filter((item) => item.type === "separator").length, 2);
const familyIndex = children.findIndex(item => item.key === "font-family");
@@ -377,7 +377,7 @@ test("toolbar catalog follows plugin insertion slots and removes unloaded plugin
[defaults[0], pluginItem, "|", ...defaults.slice(1)], "plugin.name", () => "Plugin Name - Shared Item")
.map((item) => typeof item === "string" ? {name: item} : item);
refreshToolbarCatalog(toolbar);
- const children = getEntryCatalogChildren(TOOLBAR_ENTRY_ROOT_PATH);
+ const children = getEntryCatalogChildren(TOOLBAR_ENTRY_ROOT_PATH).filter(item => !item.key.startsWith("mobile-"));
assert.deepEqual(children.slice(0, 4).map((item) => item.key), [
DESKTOP_TOOLBAR_ENTRIES[0].key,
pluginKey,
diff --git a/app/src/config/entryVisibility/catalog.ts b/app/src/config/entryVisibility/catalog.ts
index e939746080..dc76bb7e5c 100644
--- a/app/src/config/entryVisibility/catalog.ts
+++ b/app/src/config/entryVisibility/catalog.ts
@@ -6,6 +6,7 @@ import {
TOOLBAR_ENTRY_ROOT_PATH,
} from "../../protyle/toolbar/defaults";
import {mergeEntryOrderPreservingUnknown} from "./order";
+import {getMobileToolbarActionKey, MOBILE_TOOLBAR_ACTIONS, MOBILE_TOOLBAR_INSERTS} from "../../mobile/util/toolbarActions";
import {getPluginDockEntryKey} from "../../plugin/dockKey";
import {
getLegacyPluginTopBarEntryKey,
@@ -501,17 +502,23 @@ const gutterSingle = () => [
export const SLASH_MENU_ROOT_PATH = "editor.slash.menu";
// 共享工具栏声明决定目录默认顺序,字体和字号位于外观之前。
-const toolbarBuiltinChildren = DESKTOP_TOOLBAR_ENTRIES.map((item) => {
- if (item.separator) {
- return separator(item.key);
- }
- const fontControl = ["font-family", "font-size"].includes(item.key);
- return node(item.key, lang(item.lang), !fontControl, undefined, undefined,
- fontControl ? {
- defaultVisible: () => typeof window === "undefined" || !window.siyuan.mobile,
- customDefaultVisible: false,
- } : undefined);
-});
+const toolbarBuiltinChildren = [
+ ...MOBILE_TOOLBAR_ACTIONS.map(item => node(getMobileToolbarActionKey(item.name), lang(item.lang), true)),
+ separator("mobile-separator"),
+ ...DESKTOP_TOOLBAR_ENTRIES.map((item) => {
+ if (item.separator) {
+ return separator(item.key);
+ }
+ const fontControl = ["font-family", "font-size"].includes(item.key);
+ return node(item.key, lang(item.lang), !fontControl, undefined, undefined,
+ fontControl ? {
+ defaultVisible: () => typeof window === "undefined" || !window.siyuan.mobile,
+ customDefaultVisible: false,
+ } : undefined);
+ }),
+ ...MOBILE_TOOLBAR_INSERTS.map(item => node(getMobileToolbarActionKey(item.name), lang(item.lang), false,
+ undefined, undefined, {defaultVisible: () => false, customDefaultVisible: false})),
+];
const toolbarBuiltinNodeMap = new Map(toolbarBuiltinChildren.map((item) => [item.key, item]));
const slashMenuBuiltinChildren = [
@@ -1303,8 +1310,12 @@ export const refreshToolbarCatalog = (items: Array<string | IMenuItem>) => {
pluginLabels.set(key, label);
nodes.set(key, menuItem.name === "|" ? separator(key) : node(key, literal(label)));
});
- const order = mergeEntryOrderPreservingUnknown(toolbarBuiltinChildren.map((item) => item.key), actualOrder);
- const children = normalizeToolbarCatalogSeparators(order.flatMap((key) => nodes.get(key) || []));
+ const order = mergeEntryOrderPreservingUnknown(DESKTOP_TOOLBAR_ENTRIES.map((item) => item.key), actualOrder);
+ const children = normalizeToolbarCatalogSeparators([
+ ...toolbarBuiltinChildren.filter(item => item.key.startsWith("mobile-") && item.simple),
+ ...order.flatMap((key) => nodes.get(key) || []),
+ ...toolbarBuiltinChildren.filter(item => item.key.startsWith("mobile-") && !item.simple),
+ ]);
const signature = JSON.stringify(children.map((item) => toolbarCatalogNodeSignature(item, pluginLabels)));
if (signature === toolbarCatalogSignature) {
return;
diff --git a/app/src/config/entryVisibility/mobileUi.test.ts b/app/src/config/entryVisibility/mobileUi.test.ts
index 228eed5d94..c48cd61e61 100644
--- a/app/src/config/entryVisibility/mobileUi.test.ts
+++ b/app/src/config/entryVisibility/mobileUi.test.ts
@@ -245,7 +245,8 @@ test("mobile entry settings preserve preferences and support touch sorting witho
}, async () => {
const modules = ["config/entryVisibility/ui", "config/entryVisibility/catalog", "config/entryVisibility/order",
"config/entryVisibility/profile", "config/entryVisibility/dockOrder", "config/entryVisibility/touchOrder",
- "protyle/toolbar/defaults", "protyle/wysiwyg/codeBlockUtil", "plugin/dockKey", "plugin/topBarKey", "util/escape"];
+ "protyle/toolbar/defaults", "mobile/util/toolbarActions", "protyle/wysiwyg/codeBlockUtil",
+ "plugin/dockKey", "plugin/topBarKey", "util/escape"];
const sources = Object.fromEntries(modules.map(id => [id, transpileModule(
readFileSync(path.resolve(process.cwd(), "src", id + ".ts"), "utf8") +
(id.endsWith("/ui") ? "\nexports.open = openProfileEditor;" : ""),
diff --git a/app/src/config/entryVisibility/ui.test.ts b/app/src/config/entryVisibility/ui.test.ts
index 16cedd707b..64b72eff85 100644
--- a/app/src/config/entryVisibility/ui.test.ts
+++ b/app/src/config/entryVisibility/ui.test.ts
@@ -27,6 +27,8 @@ test("entry settings show exit only on native tablets without changing the persi
const hasExit = (catalog: typeof entryCatalog) => catalog.find(item => item.key === TOP_BAR_ROOT_PATH)
.children.some(item => item.key === "barExit");
assert.equal(hasExit(exports.catalog()), false);
+ assert.equal(exports.catalog().find(item => item.key === TOOLBAR_ENTRY_ROOT_PATH)
+ .children.some(item => item.key.startsWith("mobile-")), false);
assert.equal(hasExit(entryCatalog), true);
nativeTablet = true;
assert.equal(hasExit(exports.catalog()), true);
@@ -34,5 +36,9 @@ test("entry settings show exit only on native tablets without changing the persi
const catalog = exports.catalog();
assert.deepEqual(Array.from(catalog, item => item.key), [TOOLBAR_ENTRY_ROOT_PATH, "editor.slash"]);
assert.equal(catalog[1], entryCatalog.find(item => item.key === "editor.slash"));
- assert.ok(catalog[0].children.every(item => item.type === "separator" || MOBILE_TOOLBAR_NAMES.includes(item.key)));
+ assert.ok(catalog[0].children.every(item => item.type === "separator" ||
+ item.key.startsWith("mobile-") || MOBILE_TOOLBAR_NAMES.includes(item.key)));
+ for (const name of ["undo", "indent", "heading1", "table", "template"]) {
+ assert.ok(catalog[0].children.some(item => item.key === `mobile-${name}`));
+ }
});
diff --git a/app/src/config/entryVisibility/ui.ts b/app/src/config/entryVisibility/ui.ts
index 77e20f751c..93c4233b31 100644
--- a/app/src/config/entryVisibility/ui.ts
+++ b/app/src/config/entryVisibility/ui.ts
@@ -60,7 +60,9 @@ import {
const getVisibleEntryCatalog = () => isMobile() ? entryCatalog.filter(item =>
item.key === TOOLBAR_ENTRY_ROOT_PATH || item.key === "editor.slash")
.map(item => item.key === TOOLBAR_ENTRY_ROOT_PATH ? {...item, children: item.children.filter(child =>
- child.type === "separator" || MOBILE_TOOLBAR_NAMES.includes(child.key) || child.key.startsWith("plugin:"))} : item) : entryCatalog.map(item =>
+ child.type === "separator" || child.key.startsWith("mobile-") ||
+ MOBILE_TOOLBAR_NAMES.includes(child.key) || child.key.startsWith("plugin:"))} : item) : entryCatalog.map(item =>
+ item.key === TOOLBAR_ENTRY_ROOT_PATH ? {...item, children: item.children.filter(child => !child.key.startsWith("mobile-"))} :
item.key === TOP_BAR_ROOT_PATH && !isInMobileApp() ?
{...item, children: item.children.filter(child => child.key !== "barExit")} : item);
diff --git a/app/src/mobile/index.ts b/app/src/mobile/index.ts
index 336088b833..25f71e6e3b 100644
--- a/app/src/mobile/index.ts
+++ b/app/src/mobile/index.ts
@@ -62,6 +62,7 @@ import {correctHotkey} from "../boot/globalEvent/commonHotkey";
import {processIOSPurchaseResponse} from "../util/iOSPurchase";
import {nbsp2space} from "../protyle/util/normalizeText";
import {armKeyboardLock, callMobileAppShowKeyboard, canInput, setWebViewFocusable} from "./util/mobileAppUtil";
+import {suppressMobileSelectionFocus} from "./util/selectionKeyboard";
import {hideAllElements} from "../protyle/ui/hideElements";
import {initTouchDragBridge} from "../util/touchDragBridge";
import {appearanceConfigApi} from "../config/tabs/appearanceRuntime";
@@ -139,7 +140,7 @@ class App {
scrollInputIntoView(editableElement);
}, Constants.TIMEOUT_TRANSITION);
}
- if (editableElement) {
+ if (editableElement && !suppressMobileSelectionFocus(editableElement)) {
hideKeyboardToolbarUtilOnEditorClick();
// 原生 App 通过桥接主动唤起键盘;移动端浏览器没有桥接,但点击可编辑区域后也会立刻触发 resize,
// 进而调用 activeBlur 关闭键盘(比如三星键盘 https://github.com/siyuan-note/siyuan/issues/18078),所以此处也需要上锁
@@ -156,6 +157,7 @@ class App {
{
const __siyuan_original_focus = HTMLElement.prototype.focus;
HTMLElement.prototype.focus = function (this: HTMLElement, ...args) {
+ const selectionOnly = suppressMobileSelectionFocus(this);
try {
if (typeof __siyuan_original_focus === "function") {
__siyuan_original_focus.apply(this, args);
@@ -163,7 +165,7 @@ class App {
} catch (e) {
console.error("Error in focus event:", e);
}
- if (canInput(this)) {
+ if (!selectionOnly && canInput(this)) {
// 原生 App 通过桥接主动唤起键盘;移动端浏览器没有桥接,仅上锁以阻止 focus 后立即触发的 activeBlur 关闭键盘
if (window.JSAndroid && window.JSAndroid.showKeyboard || window.JSHarmony && window.JSHarmony.showKeyboard) {
callMobileAppShowKeyboard();
diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.ts
index 2e0a06a8f0..99f90b47c1 100644
--- a/app/src/mobile/util/keyboardToolbar.ts
+++ b/app/src/mobile/util/keyboardToolbar.ts
@@ -88,6 +88,9 @@ import {mountLiteSlashMenu} from "./liteSlashMenu";
import {getTableCellRichContext} from "../../protyle/util/tableCellRichContext";
import {insertEmptyBlock} from "../../block/util";
import {getIconByType} from "../../editor/getIcon";
+import {MOBILE_TOOLBAR_ACTIONS, MOBILE_TOOLBAR_INSERTS} from "./toolbarActions";
+import {pauseMobileBarsScroll} from "./mobileBars";
+import {clearMobileSelectionInput, getMobileSelectionRange, initMobileSelectionInput, isMobileSelectionMode} from "./selectionKeyboard";
const getCurrentEditor = () => getMobileToolbarProtyle()?.getInstance() || getDocumentEditor();
let toolbarProtyle: IProtyle;
@@ -97,6 +100,16 @@ const applyKeyboardToolbarEntries = (element: HTMLElement, toolbar: Array<string
applyMobileToolbarEntries(element, toolbar, {
order: getEntryOrder(TOOLBAR_ENTRY_ROOT_PATH),
isVisible: key => isEntryVisible(`${TOOLBAR_ENTRY_ROOT_PATH}.${key}`),
+ isAvailable: name => {
+ const protyle = getCurrentEditor()?.protyle;
+ if (name === "copy" || name === "cut") {
+ return !!getMobileSelectionRange();
+ }
+ if (name === "block") {
+ return !!protyle?.gutter || !!protyle && !!getTableCellRichContext(protyle);
+ }
+ return !protyle?.lite || !MOBILE_TOOLBAR_INSERTS.some(item => item.name === name);
+ },
});
};
@@ -383,12 +396,43 @@ const preventKeyboardToolbarRender = () => {
};
const updateKeyboardToolbarPosition = () => {
+ const toolbarElement = document.getElementById("keyboardToolbar");
+ const range = getMobileSelectionRange();
+ const floating = !!range && keyboardPanelTop === undefined;
+ if (toolbarElement.classList.contains("keyboard--selection") && !floating) {
+ toolbarElement.style.top = "";
+ toolbarElement.style.left = "";
+ toolbarElement.style.bottom = "";
+ toolbarElement.style.visibility = "";
+ }
+ toolbarElement.classList.toggle("keyboard--selection", floating);
+ if (floating) {
+ const viewport = getVisibleViewportBounds();
+ const content = hasClosestByClassName(range.startContainer, "protyle-content", true);
+ if (content) {
+ const contentRect = content.getBoundingClientRect();
+ viewport.top = Math.max(viewport.top, contentRect.top);
+ viewport.bottom = Math.min(viewport.bottom, contentRect.bottom);
+ }
+ const rect = Array.from(range.getClientRects()).find(item => item.bottom > viewport.top && item.top < viewport.bottom);
+ toolbarElement.style.visibility = rect ? "" : "hidden";
+ if (rect) {
+ const width = toolbarElement.getBoundingClientRect().width;
+ const height = toolbarElement.clientHeight || 48;
+ toolbarElement.style.top = `${Math.max(viewport.top + 8, Math.min(viewport.bottom - height - 8,
+ rect.top - height - 8 >= viewport.top ? rect.top - height - 8 : rect.bottom + 8))}px`;
+ toolbarElement.style.left = `${Math.max(8, Math.min(window.innerWidth - width - 8,
+ rect.left + (rect.width - width) / 2))}px`;
+ }
+ toolbarElement.style.bottom = "auto";
+ toolbarElement.style.transform = "";
+ return;
+ }
updateKeyboardPanelHeight();
scrollKeyboardSelectionIntoView();
if (isInMobileApp() || !window.visualViewport) {
return;
}
- const toolbarElement = document.getElementById("keyboardToolbar");
const viewportBottom = window.visualViewport.offsetTop + window.visualViewport.height;
const toolbarHeight = toolbarElement.getBoundingClientRect().height || 48;
toolbarElement.style.transform = "";
@@ -852,7 +896,7 @@ const hideKeyboardToolbarUtil = (restoreKeyboard = false) => {
if (keyboardPanelClosing) {
return;
}
- if (restoreKeyboard && keyboardPanelTop !== undefined) {
+ if (restoreKeyboard && keyboardPanelTop !== undefined && !isMobileSelectionMode()) {
keyboardPanelClosing = true;
showUtil = true;
resetKeyboardToolbarUtilButtons();
@@ -941,7 +985,7 @@ const renderKeyboardToolbar = () => {
// 合并同一帧内的选区变化,在浏览器更新选区后及时显示工具栏。
renderKeyboardToolbarFrame = window.requestAnimationFrame(() => {
renderKeyboardToolbarFrame = undefined;
- if (!canInput(document.activeElement)) {
+ if (!canInput(document.activeElement) && !getMobileSelectionRange()) {
hideKeyboardToolbar();
return;
}
@@ -953,118 +997,75 @@ const renderKeyboardToolbar = () => {
hideKeyboardToolbarUtil();
}
showKeyboardToolbarElement();
+ updateKeyboardToolbarPosition();
if (document.getElementById("keyboardToolbar").classList.contains("fn__none")) {
return;
}
- const dynamicElements = document.querySelectorAll("#keyboardToolbar .keyboard__dynamic");
+ const actions = document.querySelector<HTMLElement>("#keyboardToolbar .keyboard__dynamic");
const range = selection.getRangeAt(0);
- const isProtyle = hasClosestByClassName(range.startContainer, "protyle-wysiwyg", true);
+ const protyle = getCurrentEditor()?.protyle;
const nodeElement = hasClosestBlock(range.startContainer);
const endNodeElement = hasClosestBlock(range.endContainer);
- if (!isProtyle || !nodeElement ||
+ if (!protyle || !nodeElement ||
+ hasClosestByClassName(range.startContainer, "protyle-wysiwyg", true) !== protyle.wysiwyg.element ||
hasClosestByAttribute(range.startContainer, "data-type", "av-search")) {
- dynamicElements[0].classList.add("fn__none");
- dynamicElements[1].classList.add("fn__none");
+ actions.classList.add("fn__none");
return;
}
+ actions.classList.remove("fn__none");
+ applyKeyboardToolbarEntries(actions, protyle.options.toolbar);
+ protyle.toolbar.range = range;
- const blockButton = document.querySelector<HTMLElement>('#keyboardToolbar [data-type="block"]');
+ const blockButton = actions.querySelector<HTMLElement>('[data-type="block"]');
const blockType = nodeElement.getAttribute("data-type");
+ const inCode = nodeElement.classList.contains("code-block");
blockButton.querySelector("use").setAttribute("xlink:href",
`#${getIconByType(blockType, nodeElement.getAttribute("data-subtype")) || "iconParagraph"}`);
blockButton.setAttribute("aria-label", blockType === "NodeCodeBlock" ? window.siyuan.languages.code :
blockType === "NodeMathBlock" ? window.siyuan.languages.math :
blockType === "NodeParagraph" ? window.siyuan.languages.paragraph : window.siyuan.languages.contentBlock);
- const selectText = stripSemanticMarkersFromRangeText(range).split(Constants.ZWSP).join("");
- const startCellElement = hasClosestByTag(range.startContainer, "TD") ||
- hasClosestByTag(range.startContainer, "TH");
- const endCellElement = hasClosestByTag(range.endContainer, "TD") ||
- hasClosestByTag(range.endContainer, "TH");
- const disableLink = (!!endNodeElement && nodeElement !== endNodeElement) ||
- (!!startCellElement && !!endCellElement && startCellElement !== endCellElement);
- dynamicElements[1].querySelector('[data-type="a"]').toggleAttribute("disabled", disableLink);
- dynamicElements[1].querySelector('[data-type="block-ref"]').toggleAttribute("disabled", disableLink);
-
- if (!nodeElement.classList.contains("code-block") &&
- (selectText || dynamicElements[0].querySelector('[data-type="goinline"]').classList.contains("protyle-toolbar__item--current"))) {
- dynamicElements[0].classList.add("fn__none");
- dynamicElements[1].classList.remove("fn__none");
- } else {
- dynamicElements[0].classList.remove("fn__none");
- dynamicElements[1].classList.add("fn__none");
- }
-
- const protyle = getCurrentEditor().protyle;
- protyle.toolbar.range = range;
- if (!dynamicElements[0].classList.contains("fn__none")) {
- // 撤销权威栈在 kernel,本地按 rootID 读镜像设按钮态,首次进入嵌入源文档时按需初始化。
- const undoProtyle = getMobileToolbarUndo(protyle)?.owner || protyle;
- const undoRootID = undoProtyle.lite ? undefined : getUndoRootID(undoProtyle, range);
- if (undoRootID && !hasUndoStateMirror(undoRootID)) {
- initMirror(undoRootID).then((initialized) => {
- if (initialized && getCurrentEditor()?.protyle === protyle) {
- renderKeyboardToolbar();
- }
- });
+ const startCell = hasClosestByTag(range.startContainer, "TD") || hasClosestByTag(range.startContainer, "TH");
+ const endCell = hasClosestByTag(range.endContainer, "TD") || hasClosestByTag(range.endContainer, "TH");
+ const disableLink = inCode || (!!endNodeElement && nodeElement !== endNodeElement) ||
+ (!!startCell && !!endCell && startCell !== endCell);
+ actions.querySelector('[data-type="a"]').toggleAttribute("disabled", disableLink);
+ actions.querySelector('[data-type="block-ref"]').toggleAttribute("disabled", disableLink);
+ actions.querySelectorAll<HTMLElement>("[data-type]").forEach(item => {
+ if (Constants.INLINE_TYPE.includes(item.dataset.type) && !["a", "block-ref"].includes(item.dataset.type) ||
+ ["font-family", "font-size", "text", "clear"].includes(item.dataset.type)) {
+ item.toggleAttribute("disabled", inCode);
}
- const undoState = undoProtyle.undo instanceof LocalUndo ? {
- canUndo: undoProtyle.undo.undoStack.length > 0,
- canRedo: undoProtyle.undo.redoStack.length > 0,
- } : undoRootID ? getMirror(undoRootID) : {
- canUndo: false,
- canRedo: false
- };
- if (!undoState.canUndo) {
- dynamicElements[0].querySelector('[data-type="undo"]').setAttribute("disabled", "disabled");
- } else {
- dynamicElements[0].querySelector('[data-type="undo"]').removeAttribute("disabled");
- }
- if (!undoState.canRedo) {
- dynamicElements[0].querySelector('[data-type="redo"]').setAttribute("disabled", "disabled");
- } else {
- dynamicElements[0].querySelector('[data-type="redo"]').removeAttribute("disabled");
- }
- const outdentElement = dynamicElements[0].querySelector('[data-type="outdent"]');
- const goinlineElement = dynamicElements[0].querySelector('[data-type="goinline"]');
- if (nodeElement.classList.contains("code-block")) {
- goinlineElement.classList.add("fn__none");
- } else {
- goinlineElement.classList.remove("fn__none");
- }
- if (nodeElement.parentElement.classList.contains("li")) {
- outdentElement.classList.remove("fn__none");
- outdentElement.nextElementSibling.classList.remove("fn__none");
- if (nodeElement.parentElement.previousElementSibling) {
- outdentElement.nextElementSibling.removeAttribute("disabled");
- } else {
- outdentElement.nextElementSibling.setAttribute("disabled", "true");
- }
- } else if (nodeElement.classList.contains("code-block") && range.toString()) {
- outdentElement.classList.remove("fn__none");
- outdentElement.nextElementSibling.classList.remove("fn__none");
- } else {
- outdentElement.classList.add("fn__none");
- outdentElement.nextElementSibling.classList.add("fn__none");
- }
- }
+ });
- if (!dynamicElements[1].classList.contains("fn__none")) {
- dynamicElements[1].querySelectorAll(".protyle-toolbar__item--current").forEach(item => {
- item.classList.remove("protyle-toolbar__item--current");
- });
- const types = protyle.toolbar.getCurrentToolbarType(protyle, range);
- types.forEach(item => {
- if (["search-mark", "a", "block-ref", "virtual-block-ref", "text", "file-annotation-ref", "inline-math",
- "inline-memo", "", "backslash"].includes(item)) {
- return;
- }
- const itemElement = dynamicElements[1].querySelector(`[data-type="${item}"]`);
- if (itemElement) {
- itemElement.classList.add("protyle-toolbar__item--current");
+ // 撤销状态沿用所属编辑器的权威镜像,列表缩进按钮独立定位,允许任意排序。
+ const undoProtyle = getMobileToolbarUndo(protyle)?.owner || protyle;
+ const undoRootID = undoProtyle.lite ? undefined : getUndoRootID(undoProtyle, range);
+ if (undoRootID && !hasUndoStateMirror(undoRootID)) {
+ initMirror(undoRootID).then(initialized => {
+ if (initialized && getCurrentEditor()?.protyle === protyle) {
+ renderKeyboardToolbar();
}
});
}
+ const undoState = undoProtyle.undo instanceof LocalUndo ? {
+ canUndo: undoProtyle.undo.undoStack.length > 0,
+ canRedo: undoProtyle.undo.redoStack.length > 0,
+ } : undoRootID ? getMirror(undoRootID) : {canUndo: false, canRedo: false};
+ actions.querySelector('[data-type="undo"]').toggleAttribute("disabled", !undoState.canUndo);
+ actions.querySelector('[data-type="redo"]').toggleAttribute("disabled", !undoState.canRedo);
+ const inList = nodeElement.parentElement.classList.contains("li");
+ const indentCode = inCode && !range.collapsed;
+ actions.querySelector('[data-type="outdent"]').toggleAttribute("disabled", !inList && !indentCode);
+ actions.querySelector('[data-type="indent"]').toggleAttribute("disabled",
+ !(inList && nodeElement.parentElement.previousElementSibling) && !indentCode);
+ const types = protyle.toolbar.getCurrentToolbarType(protyle, range);
+ actions.querySelectorAll<HTMLElement>("[data-type]").forEach(item => {
+ if (["add", "text", "font-family", "font-size"].includes(item.dataset.type)) {
+ return;
+ }
+ item.classList.toggle("protyle-toolbar__item--current", types.includes(item.dataset.type));
+ });
});
};
@@ -1089,7 +1090,7 @@ const showKeyboardToolbarElement = () => {
}
const selection = getSelection();
// 空块恢复焦点时 Selection 可能暂时为空,但原生键盘已经显示,仍需隐藏普通底栏。
- notifyMobileKeyboardChange(true);
+ notifyMobileKeyboardChange(!isMobileSelectionMode());
const protyle = getCurrentEditor()?.protyle;
if (!protyle || (selection.rangeCount > 0 && (
hasClosestByClassName(selection.getRangeAt(0).startContainer, "protyle-wysiwyg", true) !== protyle.wysiwyg.element ||
@@ -1106,8 +1107,14 @@ const showKeyboardToolbarElement = () => {
toolbarProtyle = protyle;
updateMobilePluginToolbar(protyle);
}
- toolbarElement.querySelector('[data-type="block"]').classList.toggle("fn__none",
- !protyle.gutter && !getTableCellRichContext(protyle));
+ const selectionOnly = isMobileSelectionMode();
+ const done = toolbarElement.querySelector('.keyboard__action[data-type="done"]');
+ done.setAttribute("aria-label", selectionOnly && keyboardPanelTop === undefined ? window.siyuan.languages.edit : window.siyuan.languages.close);
+ done.querySelector("use").setAttribute("xlink:href",
+ keyboardPanelTop !== undefined ? "#iconCloseRound" : selectionOnly ? "#iconEdit" : "#iconKeyboardHide");
+ if (selectionOnly) {
+ getMobileToolbarPaddingElement(protyle).style.paddingBottom = "";
+ }
if (!toolbarElement.classList.contains("fn__none")) {
return;
}
@@ -1117,6 +1124,9 @@ const showKeyboardToolbarElement = () => {
toolbarElement.classList.remove("fn__none");
toolbarElement.style.zIndex = (++window.siyuan.zIndex).toString();
updateKeyboardToolbarPosition();
+ if (selectionOnly) {
+ return;
+ }
const modelElement = document.getElementById("model");
if (modelElement.style.transform === "translateX(0px)") {
modelElement.style.paddingBottom = "48px";
@@ -1145,7 +1155,7 @@ export const showKeyboardToolbar = () => {
const scrollKeyboardSelectionIntoView = () => {
const toolbarElement = document.getElementById("keyboardToolbar");
- if (!toolbarElement || toolbarElement.classList.contains("fn__none") || showUtil) {
+ if (!toolbarElement || toolbarElement.classList.contains("fn__none") || showUtil || isMobileSelectionMode()) {
return;
}
clearTimeout(scrollSelectionIntoViewTimeout);
@@ -1207,6 +1217,7 @@ const scrollKeyboardSelectionIntoView = () => {
clearRenderGutterAfterScroll = clearRenderGutter;
contentElement.addEventListener("scrollend", renderGutterAfterScroll, {once: true});
contentElement.addEventListener("touchstart", clearRenderGutter, {once: true, passive: true});
+ pauseMobileBarsScroll(Constants.TIMEOUT_COUNT);
contentElement.scroll({
top: cursorTop < 0 ?
contentElement.scrollTop + visibleBottom - viewportBounds.top + extraLineHeight :
@@ -1226,7 +1237,7 @@ export const hideKeyboardToolbar = () => {
clearTimeout(scrollSelectionIntoViewTimeout);
clearRenderGutterAfterScroll?.();
// 键盘退场时保留已展开的移动端菜单,菜单由用户操作或编辑器切换关闭。
- if (showUtil || keyboardPanelTop !== undefined) {
+ if (showUtil || keyboardPanelTop !== undefined || getMobileSelectionRange()) {
return;
}
pendingKeyboardFocus = undefined;
@@ -1252,6 +1263,11 @@ export const hideKeyboardToolbar = () => {
};
export const hideKeyboardToolbarByApp = (preserveSelection = false) => {
+ if (isMobileSelectionMode()) {
+ notifyMobileKeyboardChange(false);
+ renderKeyboardToolbar();
+ return KeyboardHideResult.PreserveSelection;
+ }
inlineMathSelection.reset();
if (preserveSelection && ["INPUT", "TEXTAREA"].includes(document.activeElement?.tagName)) {
// 输入法切换安全键盘时会临时隐藏,保留普通输入框焦点,避免中断密码输入。
@@ -1289,6 +1305,9 @@ export const hideKeyboardToolbarByApp = (preserveSelection = false) => {
};
export const activeBlur = (force = false) => {
+ if (!force && isMobileSelectionMode()) {
+ return;
+ }
const now = Date.now();
if (!force && now < keyboardLockUntil) {
console.warn(`activeBlur blocked by lock (remaining: ${keyboardLockUntil - now}ms)`);
@@ -1309,6 +1328,20 @@ export const activeBlur = (force = false) => {
};
export const initKeyboardToolbar = () => {
+ initMobileSelectionInput(() => {
+ const protyle = getCurrentEditor()?.protyle;
+ if (protyle) {
+ hideElements(["util"], protyle);
+ }
+ notifyMobileKeyboardChange(false);
+ window.JSAndroid?.hideKeyboard?.();
+ window.JSHarmony?.hideKeyboard?.();
+ }, renderKeyboardToolbar);
+ document.addEventListener("scroll", () => {
+ if (getMobileSelectionRange()) {
+ updateKeyboardToolbarPosition();
+ }
+ }, true);
window.addEventListener("siyuan-mobile-toolbar-focus", renderKeyboardToolbar);
window.addEventListener("siyuan-mobile-toolbar-editor", (event: CustomEvent<IProtyle>) => {
if (event.detail) {
@@ -1324,6 +1357,9 @@ export const initKeyboardToolbar = () => {
});
let composing = false;
window.addEventListener("siyuan-mobile-keyboard-hiding", () => {
+ if (isMobileSelectionMode()) {
+ return;
+ }
// 键盘退场前先隐藏工具栏,焦点和选区由原生端在动画结束后清理。
preventKeyboardToolbarRender();
hideKeyboardToolbar();
@@ -1472,21 +1508,9 @@ export const initKeyboardToolbar = () => {
toolbarElement.innerHTML = `<div class="fn__flex keyboard__bar">
<div class="fn__flex-1">
<div class="fn__none keyboard__dynamic">
- <button class="keyboard__action" data-type="outdent" aria-label="${window.siyuan.languages.outdent}"><svg><use xlink:href="#iconOutdent"></use></svg></button>
- <button class="keyboard__action" data-type="indent" aria-label="${window.siyuan.languages.indent}"><svg><use xlink:href="#iconIndent"></use></svg></button>
- <button class="keyboard__action" data-type="add" aria-label="${window.siyuan.languages.addAttr}"><svg><use xlink:href="#iconAdd"></use></svg></button>
- <button class="keyboard__action" data-type="block" aria-label="${window.siyuan.languages.paragraph}"><svg><use xlink:href="#iconParagraph"></use></svg></button>
- <button class="keyboard__action" data-type="goinline" aria-label="${window.siyuan.languages.entryInlineMenu}"><svg class="keyboard__svg--big"><use xlink:href="#iconBIU"></use></svg></button>
- <button class="keyboard__action" data-type="softLine" aria-label="${window.siyuan.languages.wrap}"><svg><use xlink:href="#iconSoftWrap"></use></svg></button>
- <span class="keyboard__split"></span>
- <button class="keyboard__action" data-type="undo" aria-label="${window.siyuan.languages.undo}"><svg><use xlink:href="#iconUndo"></use></svg></button>
- <button class="keyboard__action" data-type="redo" aria-label="${window.siyuan.languages.redo}"><svg><use xlink:href="#iconRedo"></use></svg></button>
- <span class="keyboard__split"></span>
- <button class="keyboard__action" data-type="moveup" aria-label="${window.siyuan.languages.moveToUp}"><svg><use xlink:href="#iconUp"></use></svg></button>
- <button class="keyboard__action" data-type="movedown" aria-label="${window.siyuan.languages.moveToDown}"><svg><use xlink:href="#iconDown"></use></svg></button>
- </div>
- <div class="fn__none keyboard__dynamic">
- <button class="keyboard__action" data-type="goback" aria-label="${window.siyuan.languages.back}"><svg><use xlink:href="#iconBack"></use></svg></button>
+ ${[...MOBILE_TOOLBAR_ACTIONS, ...MOBILE_TOOLBAR_INSERTS].map(item =>
+ `<button class="keyboard__action" data-type="${item.name}" aria-label="${window.siyuan.languages[item.lang]}"><svg><use xlink:href="#${item.icon}"></use></svg></button>`).join("")}
+ <span class="keyboard__split" data-id="mobile-separator"></span>
<button class="keyboard__action" data-type="block-ref" aria-label="${window.siyuan.languages.ref}"><svg><use xlink:href="#iconRef"></use></svg></button>
<button class="keyboard__action" data-type="a" aria-label="${window.siyuan.languages.link}"><svg><use xlink:href="#iconLink"></use></svg></button>
<span class="keyboard__split" data-id="separator_1"></span>
@@ -1515,7 +1539,7 @@ export const initKeyboardToolbar = () => {
<div class="keyboard__util"></div>`;
const refreshEntries = () => {
const protyle = getCurrentEditor()?.protyle;
- const inline = toolbarElement.querySelector<HTMLElement>('.keyboard__action[data-type="goback"]').parentElement;
+ const inline = toolbarElement.querySelector<HTMLElement>(".keyboard__dynamic");
applyKeyboardToolbarEntries(inline, protyle?.options.toolbar || []);
hideKeyboardToolbarUtil();
};
@@ -1539,7 +1563,7 @@ export const initKeyboardToolbar = () => {
toolbarElement.addEventListener("mousedown", event => {
const buttonElement = hasClosestByTag(event.target as HTMLElement, "BUTTON");
const type = buttonElement && buttonElement.getAttribute("data-type");
- if (type === "undo" || type === "redo" || type === "block") {
+ if (isMobileSelectionMode() || type === "undo" || type === "redo" || type === "block") {
// 保持编辑器焦点,避免工具栏操作期间软键盘收起。
event.preventDefault();
}
@@ -1636,7 +1660,7 @@ export const initKeyboardToolbar = () => {
return;
}
const buttonElement = hasClosestByTag(target, "BUTTON");
- if (!buttonElement || buttonElement.getAttribute("disabled")) {
+ if (!buttonElement || buttonElement.hasAttribute("disabled")) {
return;
}
const type = buttonElement.getAttribute("data-type");
@@ -1669,6 +1693,12 @@ export const initKeyboardToolbar = () => {
event.stopPropagation();
const selection = getSelection();
const currentRange = selection.rangeCount > 0 ? selection.getRangeAt(0) : undefined;
+ if (type === "done" && isMobileSelectionMode() && keyboardPanelTop === undefined) {
+ const range = currentRange?.cloneRange() || protyle?.toolbar.range;
+ clearMobileSelectionInput();
+ restoreKeyboardToolbarRange(protyle, range);
+ return;
+ }
// 收起菜单不依赖实时选区,编辑器失焦后使用保存的选区恢复光标。
const closeAddMenu = type === "add" && buttonElement.classList.contains("protyle-toolbar__item--current");
if (type === "done" || closeAddMenu) {
@@ -1695,7 +1725,12 @@ export const initKeyboardToolbar = () => {
if (window.siyuan.config.readonly || !protyle || protyle.disabled) {
return;
}
- if (type === "undo") {
+ if (type === "copy" || type === "cut") {
+ focusByRange(range);
+ document.execCommand(type);
+ renderKeyboardToolbar();
+ return;
+ } else if (type === "undo") {
const undoContext = getMobileToolbarUndo(protyle);
if (undoContext) {
undoContext.run(false);
@@ -1722,23 +1757,10 @@ export const initKeyboardToolbar = () => {
return;
}
// inline element
- if (type === "goback") {
- toolbarElement.querySelector('.keyboard__action[data-type="goinline"]').classList.remove("protyle-toolbar__item--current");
- const dynamicElements = document.querySelectorAll("#keyboardToolbar .keyboard__dynamic");
- dynamicElements[0].classList.remove("fn__none");
- dynamicElements[1].classList.add("fn__none");
- focusByRange(range);
- preventRender = true;
- setTimeout(() => {
- preventRender = false;
- }, 1000);
- return;
- } else if (type === "goinline") {
- buttonElement.classList.add("protyle-toolbar__item--current");
- const dynamicElements = document.querySelectorAll("#keyboardToolbar .keyboard__dynamic");
- dynamicElements[1].classList.remove("fn__none");
- dynamicElements[0].classList.add("fn__none");
- focusByRange(range);
+ const insert = MOBILE_TOOLBAR_INSERTS.find(item => item.name === type);
+ if (insert) {
+ protyle.toolbar.range = range.cloneRange();
+ protyle.hint.fill(insert.value(Constants), protyle, false);
return;
} else if (["a", "block-ref", "inline-math", "inline-memo"].includes(type)) {
if (!hasClosestByAttribute(range.startContainer, "data-type", "NodeCodeBlock")) {
diff --git a/app/src/mobile/util/mobileAppUtil.test.ts b/app/src/mobile/util/mobileAppUtil.test.ts
index 4391151dfe..3d42a394dc 100644
--- a/app/src/mobile/util/mobileAppUtil.test.ts
+++ b/app/src/mobile/util/mobileAppUtil.test.ts
@@ -118,6 +118,8 @@ describe("mobile input detection", () => {
describe("mobile app keyboard", () => {
it("notifies listeners before requesting the Android keyboard", () => {
const originalWindow = globalThis.window;
+ const originalDocument = globalThis.document;
+ Object.defineProperty(globalThis, "document", {configurable: true, value: {activeElement: undefined}});
const calls: string[] = [];
const testWindow = new EventTarget() as Window & typeof globalThis;
Object.assign(testWindow, {
@@ -140,6 +142,7 @@ describe("mobile app keyboard", () => {
callMobileAppShowKeyboard();
assert.deepEqual(calls, ["change", "keyboard"]);
} finally {
+ Object.defineProperty(globalThis, "document", {configurable: true, value: originalDocument});
Object.defineProperty(globalThis, "window", {
configurable: true,
value: originalWindow,
diff --git a/app/src/mobile/util/mobileAppUtil.ts b/app/src/mobile/util/mobileAppUtil.ts
index 2343ba3304..2117dea78f 100644
--- a/app/src/mobile/util/mobileAppUtil.ts
+++ b/app/src/mobile/util/mobileAppUtil.ts
@@ -1,5 +1,6 @@
import {hasClosestByAttribute, hasClosestByClassName} from "../../protyle/util/hasClosest";
import {notifyMobileKeyboardChange} from "./mobileKeyboardChange";
+import {isMobileSelectionMode, suppressMobileSelectionFocus} from "./selectionKeyboard";
export let keyboardLockUntil = 0;
@@ -10,6 +11,9 @@ export const armKeyboardLock = () => {
};
export const callMobileAppShowKeyboard = () => {
+ if (isMobileSelectionMode() || suppressMobileSelectionFocus(document.activeElement)) {
+ return;
+ }
armKeyboardLock();
notifyMobileKeyboardChange(true);
diff --git a/app/src/mobile/util/mobileBars.ts b/app/src/mobile/util/mobileBars.ts
index b1f65d98fb..f06ba442b6 100644
--- a/app/src/mobile/util/mobileBars.ts
+++ b/app/src/mobile/util/mobileBars.ts
@@ -203,13 +203,19 @@ export const initMobileBars = () => {
}
initialized = true;
window.addEventListener("siyuan-mobile-keyboard-change", ((event: CustomEvent<boolean>) => {
+ pauseMobileBarsScroll();
barsState = reduceMobileBarsState(barsState, {
type: "set-editing",
active: event.detail,
scrollTop: scrollElement?.scrollTop,
});
+ if (!isMobileBarsAutoHide()) {
+ barsState = reduceMobileBarsState(barsState, {type: "set-reading-bars", visible: true});
+ }
renderMobileBars();
}) as EventListener);
+ window.addEventListener("resize", () => pauseMobileBarsScroll());
+ window.visualViewport?.addEventListener("resize", () => pauseMobileBarsScroll());
document.addEventListener("selectionchange", onSelectionChange);
panelObserver?.disconnect();
diff --git a/app/src/mobile/util/mobileBarsState.test.ts b/app/src/mobile/util/mobileBarsState.test.ts
index af4f80eaf9..7d5df2daa1 100644
--- a/app/src/mobile/util/mobileBarsState.test.ts
+++ b/app/src/mobile/util/mobileBarsState.test.ts
@@ -78,36 +78,43 @@ describe("mobile bars state", () => {
assert.equal(getVisibility(state).topbarVisible, true);
});
- it("keeps the visible reading state while editing", () => {
+ it("hides the top bars on entering input and reveals them when scrolling back", () => {
let state = createMobileBarsState(100);
state = update(state, {type: "set-editing", active: true});
assert.deepEqual(getVisibility(state), {
- topbarVisible: true,
+ topbarVisible: false,
bottomBarVisible: false,
editingBarVisible: true,
- scrollPaused: true,
+ scrollPaused: false,
});
state = update(state, {type: "scroll", scrollTop: 180});
- assert.equal(state.readingBarsOffset, 0);
+ assert.equal(state.readingBarsOffset, 30);
assert.equal(state.scrollTop, 180);
+ state = update(state, {type: "scroll", scrollTop: 150});
+ assert.equal(state.readingBarsOffset, 0);
+ state = update(state, {type: "set-editing", active: true});
+ assert.equal(state.readingBarsOffset, 0);
+
state = update(state, {type: "set-editing", active: false, scrollTop: 180});
assert.equal(getVisibility(state).bottomBarVisible, true);
});
- it("restores hidden reading bars when editing so sidebar buttons remain accessible", () => {
+ it("preserves hidden bars across keyboard changes and ignores cursor scrolling", () => {
let state = createMobileBarsState(100);
state = update(state, {type: "set-reading-bars", visible: false});
state = update(state, {type: "set-editing", active: true, scrollTop: 100});
- state = update(state, {type: "scroll", scrollTop: 180});
- assert.equal(state.readingBarsOffset, 0);
- assert.equal(getVisibility(state).topbarVisible, true);
+ state = update(state, {type: "set-programmatic-scrolling", active: true});
+ state = update(state, {type: "scroll", scrollTop: 50});
+ state = update(state, {type: "set-programmatic-scrolling", active: false});
+ assert.equal(state.readingBarsOffset, 30);
+ assert.equal(getVisibility(state).topbarVisible, false);
state = update(state, {type: "set-editing", active: false, scrollTop: 180});
assert.deepEqual(getVisibility(state), {
- topbarVisible: true,
- bottomBarVisible: true,
+ topbarVisible: false,
+ bottomBarVisible: false,
editingBarVisible: false,
scrollPaused: false,
});
diff --git a/app/src/mobile/util/mobileBarsState.ts b/app/src/mobile/util/mobileBarsState.ts
index 50a01c8d9c..6ae206fc5d 100644
--- a/app/src/mobile/util/mobileBarsState.ts
+++ b/app/src/mobile/util/mobileBarsState.ts
@@ -73,7 +73,7 @@ export const createMobileBarsState = (scrollTop = 0): IMobileBarsState => ({
});
export const isMobileBarsScrollPaused = (state: IMobileBarsState) => {
- return state.editing || state.selecting || state.panelOpen || state.programmaticScrolling;
+ return state.selecting || state.panelOpen || state.programmaticScrolling;
};
export const getMobileBarsVisibility = (
@@ -111,7 +111,7 @@ export const reduceMobileBarsState = (
return {
...resetScrollTracking(state, action.scrollTop),
editing: action.active,
- readingBarsOffset: action.active ? 0 : state.readingBarsOffset,
+ readingBarsOffset: action.active && !state.editing ? scrollOptions.maxOffset : state.readingBarsOffset,
};
}
diff --git a/app/src/mobile/util/selectionKeyboard.ts b/app/src/mobile/util/selectionKeyboard.ts
new file mode 100644
index 0000000000..a5001dadff
--- /dev/null
+++ b/app/src/mobile/util/selectionKeyboard.ts
@@ -0,0 +1,176 @@
+let editor: HTMLElement;
+let selecting = false;
+let touching = false;
+let gestureUntil = 0;
+const inputModes = new Map<Element, string | null>();
+
+const suppressInput = (element: Element) => {
+ if (!inputModes.has(element)) {
+ inputModes.set(element, element.getAttribute("inputmode"));
+ }
+ element.setAttribute("inputmode", "none");
+};
+
+export const clearMobileSelectionInput = () => {
+ inputModes.forEach((value, element) => {
+ if (value === null) {
+ element.removeAttribute("inputmode");
+ } else {
+ element.setAttribute("inputmode", value);
+ }
+ });
+ inputModes.clear();
+ editor = undefined;
+ selecting = false;
+ touching = false;
+ gestureUntil = 0;
+};
+
+export const isMobileSelectionMode = () => {
+ if (editor && !editor.isConnected) {
+ clearMobileSelectionInput();
+ }
+ return selecting;
+};
+
+export const suppressMobileSelectionFocus = (element: Element) => {
+ if (editor && element && !editor.contains(element) && !element.closest("#keyboardToolbar, .protyle-util, .b3-menu")) {
+ clearMobileSelectionInput();
+ return false;
+ }
+ if (!editor?.isConnected || !editor.contains(element) || (!selecting && inputModes.size === 0)) {
+ return false;
+ }
+ // 格式操作可能替换可编辑节点,恢复焦点时继续保留选择模式。
+ suppressInput(element);
+ return true;
+};
+
+export const getMobileSelectionRange = () => {
+ if (!isMobileSelectionMode()) {
+ return;
+ }
+ const selection = getSelection();
+ if (!selection?.rangeCount) {
+ return;
+ }
+ const range = selection.getRangeAt(0);
+ if (!range.collapsed && editor.contains(range.startContainer) && editor.contains(range.endContainer)) {
+ return range;
+ }
+};
+
+const refreshSelectionFocus = () => {
+ const active = document.activeElement as HTMLElement;
+ const selection = getSelection();
+ if (window.JSAndroid || window.JSHarmony || !getMobileSelectionRange() || !editor.contains(active)) {
+ return;
+ }
+ // 浏览器在焦点切换时应用 inputmode,保留方向及端点,避免收起键盘时丢失选区。
+ const {anchorNode, anchorOffset, focusNode, focusOffset} = selection;
+ suppressInput(active);
+ active.blur();
+ active.focus({preventScroll: true});
+ selection.setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset);
+};
+
+export const initMobileSelectionInput = (onSelect: () => void, onChange: () => void) => {
+ const begin = (event: PointerEvent) => {
+ if (event.pointerType !== "touch" && event.pointerType !== "pen") {
+ return;
+ }
+ const target = event.target as HTMLElement;
+ if (target.closest("#keyboardToolbar, .protyle-util, .b3-menu")) {
+ return;
+ }
+ const root = target.closest<HTMLElement>('.protyle-wysiwyg[data-readonly="false"]');
+ const editable = target.closest<HTMLElement>('[contenteditable="true"], [contenteditable="plaintext-only"]');
+ if (!root || !editable || target.closest("input, textarea") ||
+ target.closest("[contenteditable]")?.getAttribute("contenteditable") === "false" ||
+ root.querySelector(".protyle-wysiwyg--select")) {
+ clearMobileSelectionInput();
+ return;
+ }
+ if (editor !== root) {
+ clearMobileSelectionInput();
+ }
+ editor = root;
+ touching = true;
+ // 在浏览器处理长按之前阻止首次唤起键盘;短按会在 click 中恢复输入。
+ if (selecting || !document.body.classList.contains("mobile-keyboard--open")) {
+ suppressInput(editable);
+ }
+ };
+ const end = () => {
+ touching = false;
+ gestureUntil = Date.now() + 600;
+ refreshSelectionFocus();
+ };
+ const update = () => {
+ if (!editor?.isConnected || (!selecting && !touching && Date.now() > gestureUntil)) {
+ return;
+ }
+ const selection = getSelection();
+ if (!selection?.rangeCount || selection.isCollapsed || !editor.contains(selection.anchorNode) ||
+ !editor.contains(selection.focusNode)) {
+ onChange();
+ return;
+ }
+ const wasSelecting = selecting;
+ selecting = true;
+ [selection.anchorNode, selection.focusNode].forEach(node => {
+ const element = (node.nodeType === Node.ELEMENT_NODE ? node as Element : node.parentElement)
+ ?.closest<HTMLElement>('[contenteditable="true"], [contenteditable="plaintext-only"]');
+ if (element) {
+ suppressInput(element);
+ }
+ });
+ if (!wasSelecting) {
+ onSelect();
+ if (!touching) {
+ refreshSelectionFocus();
+ }
+ }
+ onChange();
+ };
+ const click = (event: MouseEvent) => {
+ const target = event.target as HTMLElement;
+ if (!editor?.contains(target)) {
+ return;
+ }
+ update();
+ if (getMobileSelectionRange()) {
+ return;
+ }
+ const editable = target.closest<HTMLElement>('[contenteditable="true"], [contenteditable="plaintext-only"]');
+ const restoreInput = inputModes.size > 0;
+ const selection = getSelection();
+ const range = selection?.rangeCount ? selection.getRangeAt(0).cloneRange() : undefined;
+ clearMobileSelectionInput();
+ if (restoreInput && editable && range) {
+ editable.blur();
+ editable.focus({preventScroll: true});
+ selection.removeAllRanges();
+ selection.addRange(range);
+ }
+ };
+ document.addEventListener("pointerdown", begin, true);
+ document.addEventListener("pointerup", end, true);
+ document.addEventListener("pointercancel", end, true);
+ document.addEventListener("selectionchange", update, true);
+ document.addEventListener("click", click, true);
+ document.addEventListener("contextmenu", event => {
+ update();
+ if (getMobileSelectionRange() && editor.contains(event.target as Node)) {
+ event.preventDefault();
+ event.stopPropagation();
+ onChange();
+ }
+ }, true);
+ document.addEventListener("focusin", event => {
+ const target = event.target as HTMLElement;
+ if (target.matches("input, textarea") && !target.closest("#keyboardToolbar")) {
+ clearMobileSelectionInput();
+ }
+ }, true);
+};
diff --git a/app/src/mobile/util/toolbarActions.ts b/app/src/mobile/util/toolbarActions.ts
new file mode 100644
index 0000000000..c499a535bf
--- /dev/null
+++ b/app/src/mobile/util/toolbarActions.ts
@@ -0,0 +1,41 @@
+import type {Constants} from "../../constants";
+
+export const MOBILE_TOOLBAR_ACTIONS = [
+ {name: "copy", lang: "copy", icon: "iconCopy"},
+ {name: "cut", lang: "cut", icon: "iconCut"},
+ {name: "outdent", lang: "outdent", icon: "iconOutdent"},
+ {name: "indent", lang: "indent", icon: "iconIndent"},
+ {name: "add", lang: "addAttr", icon: "iconAdd"},
+ {name: "block", lang: "contentBlock", icon: "iconParagraph"},
+ {name: "softLine", lang: "wrap", icon: "iconSoftWrap"},
+ {name: "undo", lang: "undo", icon: "iconUndo"},
+ {name: "redo", lang: "redo", icon: "iconRedo"},
+ {name: "moveup", lang: "moveToUp", icon: "iconUp"},
+ {name: "movedown", lang: "moveToDown", icon: "iconDown"},
+];
+
+// 常用插入按钮复用斜杠菜单命令,避免维护另一套内容转换逻辑。
+export const MOBILE_TOOLBAR_INSERTS = [
+ ...[1, 2, 3, 4, 5, 6].map(level => ({
+ name: `heading${level}`, lang: `heading${level}`, icon: `iconH${level}`,
+ value: () => `${"#".repeat(level)} ${Lute.Caret}`,
+ })),
+ {name: "list", lang: "list", icon: "iconList", value: () => `- ${Lute.Caret}`},
+ {name: "orderedList", lang: "ordered-list", icon: "iconOrderedList", value: () => `1. ${Lute.Caret}`},
+ {name: "check", lang: "check", icon: "iconCheck", value: () => `- [ ] ${Lute.Caret}`},
+ {name: "quote", lang: "quote", icon: "iconQuote", value: () => `> ${Lute.Caret}`},
+ {name: "codeBlock", lang: "code", icon: "iconCode", value: () => "```"},
+ {name: "table", lang: "table", icon: "iconTable", value: () =>
+ `| ${Lute.Caret} | | |\n| --- | --- | --- |\n| | | |\n| | | |`},
+ {name: "database", lang: "database", icon: "iconDatabase", value: () =>
+ '<div data-type="NodeAttributeView" data-av-type="table"></div>'},
+ {name: "mathBlock", lang: "math", icon: "iconMath", value: () => "$$"},
+ {name: "tabs", lang: "tabs", icon: "iconTabs", value: () => `::: tabs\n@tab\n\n${Lute.Caret}\n\n@tab\n\n:::\n`},
+ {name: "mindmap", lang: "mindmap", icon: "iconMindmap", value: (constants: typeof Constants) =>
+ `- ${Lute.Caret}\n{: ${constants.CUSTOM_SY_LIST_MINDMAP}="1"}`},
+ {name: "template", lang: "template", icon: "iconMarkdown", value: (constants: typeof Constants) => constants.ZWSP},
+ {name: "assets", lang: "assets", icon: "iconImage", value: (constants: typeof Constants) => constants.ZWSP + 2},
+];
+
+export const getMobileToolbarActionKey = (name: string) => `mobile-${name}`;
+export const MOBILE_TOOLBAR_ACTION_NAMES = [...MOBILE_TOOLBAR_ACTIONS, ...MOBILE_TOOLBAR_INSERTS].map(item => item.name);
diff --git a/app/src/mobile/util/toolbarEntries.test.ts b/app/src/mobile/util/toolbarEntries.test.ts
index dc1363e35e..5b754c4e37 100644
--- a/app/src/mobile/util/toolbarEntries.test.ts
+++ b/app/src/mobile/util/toolbarEntries.test.ts
@@ -2,6 +2,8 @@ import * as assert from "node:assert/strict";
import {test} from "node:test";
import {applyMobileToolbarEntries} from "./toolbarEntries";
import {getDefaultToolbar, getPluginToolbarEntryKey, markPluginToolbarEntries} from "../../protyle/toolbar/defaults";
+import {getEntryCatalogChildren} from "../../config/entryVisibility/catalog";
+import {resolveEntryOrder} from "../../config/entryVisibility/order";
class ToolbarElement {
public children: ToolbarElement[] = [];
@@ -28,58 +30,55 @@ class ToolbarElement {
test("shared toolbar restores document entries after editing a restricted fragment", () => {
const root = new ToolbarElement();
- const back = new ToolbarElement("goback");
const bold = new ToolbarElement("strong");
const tag = new ToolbarElement("tag");
const separator = new ToolbarElement(undefined, "separator_1");
- root.children = [back, bold, separator, tag];
+ root.children = [bold, separator, tag];
const options = {order: ["strong", "separator_1", "tag"], isVisible: () => true};
applyMobileToolbarEntries(root as unknown as HTMLElement, ["strong"], options);
- assert.deepEqual(root.children.filter(item => !item.classList.contains("fn__none")), [back, bold]);
+ assert.deepEqual(root.children.filter(item => !item.classList.contains("fn__none")), [bold]);
applyMobileToolbarEntries(root as unknown as HTMLElement, getDefaultToolbar(true), options);
- assert.deepEqual(root.children.filter(item => !item.classList.contains("fn__none")), [back, bold, separator, tag]);
+ assert.deepEqual(root.children.filter(item => !item.classList.contains("fn__none")), [bold, separator, tag]);
});
-test("mobile toolbar keeps navigation reachable and removes empty separators", () => {
+test("mobile toolbar removes leading, trailing and empty separators", () => {
const root = new ToolbarElement();
- const back = new ToolbarElement("goback");
const family = new ToolbarElement("font-family");
const size = new ToolbarElement("font-size");
const first = new ToolbarElement(undefined, "separator_1");
const second = new ToolbarElement(undefined, "separator_2");
- root.children = [back, first, family, second, size];
+ root.children = [first, family, second, size];
const toolbar = getDefaultToolbar(true);
const order = ["separator_1", "font-family", "separator_2", "font-size"];
applyMobileToolbarEntries(root as unknown as HTMLElement, toolbar, {order, isVisible: key => key !== "font-family"});
- assert.deepEqual(root.children.filter(item => !item.classList.contains("fn__none")), [back, size]);
+ assert.deepEqual(root.children.filter(item => !item.classList.contains("fn__none")), [size]);
applyMobileToolbarEntries(root as unknown as HTMLElement, toolbar, {order, isVisible: () => false});
- assert.deepEqual(root.children.filter(item => !item.classList.contains("fn__none")), [back]);
+ assert.deepEqual(root.children.filter(item => !item.classList.contains("fn__none")), []);
applyMobileToolbarEntries(root as unknown as HTMLElement, toolbar, {
order: ["font-size", "separator_1", "font-family", "separator_2"], isVisible: () => true,
});
- assert.deepEqual(root.children.filter(item => !item.classList.contains("fn__none")), [back, size, first, family]);
+ assert.deepEqual(root.children.filter(item => !item.classList.contains("fn__none")), [size, first, family]);
});
test("mobile toolbar follows font visibility changes while preserving formatting entries", () => {
const root = new ToolbarElement();
- const back = new ToolbarElement("goback");
const family = new ToolbarElement("font-family");
const size = new ToolbarElement("font-size");
const appearance = new ToolbarElement("text");
const bold = new ToolbarElement("strong");
const separator = new ToolbarElement(undefined, "separator_1");
- root.children = [back, family, size, separator, appearance, bold];
+ root.children = [family, size, separator, appearance, bold];
applyMobileToolbarEntries(root as unknown as HTMLElement, getDefaultToolbar(true), {
order: ["font-family", "font-size", "separator_1", "text", "strong"],
isVisible: key => !["font-family", "font-size"].includes(key),
});
- assert.deepEqual(root.children.filter(item => !item.classList.contains("fn__none")), [back, appearance, bold]);
+ assert.deepEqual(root.children.filter(item => !item.classList.contains("fn__none")), [appearance, bold]);
applyMobileToolbarEntries(root as unknown as HTMLElement, getDefaultToolbar(true), {
order: ["font-family", "font-size", "separator_1", "text", "strong"],
isVisible: () => true,
});
assert.deepEqual(root.children.filter(item => !item.classList.contains("fn__none")),
- [back, family, size, separator, appearance, bold]);
+ [family, size, separator, appearance, bold]);
});
test("mobile toolbar applies plugin visibility and restores its configured order", () => {
@@ -88,16 +87,36 @@ test("mobile toolbar applies plugin visibility and restores its configured order
const toolbar = markPluginToolbarEntries(defaults, [...defaults, plugin], "example", () => "Example");
const key = getPluginToolbarEntryKey("example", "plugin-action");
const root = new ToolbarElement();
- const back = new ToolbarElement("goback");
const family = new ToolbarElement("font-family");
const custom = new ToolbarElement(plugin.name);
- root.children = [back, family, custom];
+ root.children = [family, custom];
const order = [key, "font-family"];
applyMobileToolbarEntries(root as unknown as HTMLElement, toolbar, {order, isVisible: id => id !== key});
assert.equal(custom.dataset.id, key);
- assert.deepEqual(root.children, [back, custom, family]);
+ assert.deepEqual(root.children, [custom, family]);
assert.equal(custom.classList.contains("fn__none"), true);
applyMobileToolbarEntries(root as unknown as HTMLElement, toolbar, {order, isVisible: () => true});
- assert.deepEqual(root.children, [back, custom, family]);
+ assert.deepEqual(root.children, [custom, family]);
assert.equal(custom.classList.contains("fn__none"), false);
});
+
+test("mobile actions merge into saved formatting order and honor availability and visibility", () => {
+ const catalog = getEntryCatalogChildren("editor.toolbar");
+ const order = resolveEntryOrder(catalog.map(item => item.key), ["em", "strong", "a"],
+ new Set(catalog.filter(item => item.type === "separator").map(item => item.key)));
+ assert.ok(order.indexOf("em") < order.indexOf("strong"));
+ assert.ok(order.includes("mobile-undo"));
+ assert.ok(order.includes("mobile-heading1"));
+ const root = new ToolbarElement();
+ const bold = new ToolbarElement("strong");
+ const italic = new ToolbarElement("em");
+ const undo = new ToolbarElement("undo");
+ const heading = new ToolbarElement("heading1");
+ root.children = [bold, italic, undo, heading];
+ applyMobileToolbarEntries(root as unknown as HTMLElement, getDefaultToolbar(true), {
+ order, isVisible: key => key !== "mobile-undo", isAvailable: name => name !== "heading1",
+ });
+ assert.deepEqual(root.children.filter(item => !item.classList.contains("fn__none")), [italic, bold]);
+ assert.equal(undo.dataset.id, "mobile-undo");
+ assert.equal(heading.dataset.id, "mobile-heading1");
+});
diff --git a/app/src/mobile/util/toolbarEntries.ts b/app/src/mobile/util/toolbarEntries.ts
index 63b7b248d8..b78efc3105 100644
--- a/app/src/mobile/util/toolbarEntries.ts
+++ b/app/src/mobile/util/toolbarEntries.ts
@@ -1,16 +1,19 @@
import {getToolbarEntryId, MOBILE_TOOLBAR_NAMES} from "../../protyle/toolbar/defaults";
import {resolveToolbarItems} from "../../protyle/toolbar/entryVisibility";
+import {getMobileToolbarActionKey, MOBILE_TOOLBAR_ACTION_NAMES} from "./toolbarActions";
export const applyMobileToolbarEntries = (element: HTMLElement, toolbar: Array<string | IMenuItem>, options: {
order: string[];
isVisible: (key: string) => boolean;
+ isAvailable?: (name: string) => boolean;
}) => {
const items = new Map(toolbar.filter((item): item is IMenuItem => typeof item !== "string")
.map(item => [item.name, item]));
const available = new Set(toolbar.map(item => typeof item === "string" ? item : item.name));
- const children = Array.from(element.children).filter((child: HTMLElement) => child.dataset.type !== "goback") as HTMLElement[];
+ const children = Array.from(element.children) as HTMLElement[];
children.forEach(child => {
const item = items.get(child.dataset.type);
- const key = item ? getToolbarEntryId(item) : MOBILE_TOOLBAR_NAMES.includes(child.dataset.type) ? child.dataset.type : undefined;
+ const key = MOBILE_TOOLBAR_ACTION_NAMES.includes(child.dataset.type) ? getMobileToolbarActionKey(child.dataset.type) :
+ item ? getToolbarEntryId(item) : MOBILE_TOOLBAR_NAMES.includes(child.dataset.type) ? child.dataset.type : undefined;
if (key) {
child.dataset.id = key;
}
@@ -19,7 +22,9 @@ export const applyMobileToolbarEntries = (element: HTMLElement, toolbar: Array<s
getKey: item => item.dataset.id,
isSeparator: item => item.classList.contains("keyboard__split"),
isVisible: key => options.isVisible(key) && children.some(item => item.dataset.id === key &&
- (item.classList.contains("keyboard__split") || available.has(item.dataset.type))),
+ (item.classList.contains("keyboard__split") ||
+ (MOBILE_TOOLBAR_ACTION_NAMES.includes(item.dataset.type) || available.has(item.dataset.type)) &&
+ options.isAvailable?.(item.dataset.type) !== false)),
order: options.order,
});
const visible = new Set(result.visible);
diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.ts
index af607c61d1..237d3f5a10 100644
--- a/app/src/protyle/gutter/index.ts
+++ b/app/src/protyle/gutter/index.ts
@@ -1112,9 +1112,7 @@ export class Gutter {
private showMobileAppearance(protyle: IProtyle) {
const toolbarElement = document.getElementById("keyboardToolbar");
- const dynamicElements = toolbarElement.querySelectorAll("#keyboardToolbar .keyboard__dynamic");
- dynamicElements[0].classList.add("fn__none");
- dynamicElements[1].classList.remove("fn__none");
+ toolbarElement.querySelector(".keyboard__dynamic").classList.remove("fn__none");
toolbarElement.querySelector('.keyboard__action[data-type="text"]').classList.add("protyle-toolbar__item--current");
toolbarElement.querySelector('.keyboard__action[data-type="done"] use').setAttribute("xlink:href", "#iconCloseRound");
toolbarElement.classList.remove("fn__none");
diff --git a/app/src/protyle/toolbar/index.ts b/app/src/protyle/toolbar/index.ts
index 264e5269b0..918e1e6c49 100644
--- a/app/src/protyle/toolbar/index.ts
+++ b/app/src/protyle/toolbar/index.ts
@@ -740,7 +740,7 @@ export class Toolbar {
return;
}
- const toolbarElement = isMobile() ? document.querySelector("#keyboardToolbar .keyboard__dynamic").nextElementSibling : this.element;
+ const toolbarElement = isMobile() ? document.querySelector("#keyboardToolbar .keyboard__dynamic") : this.element;
const actionBtn = action === "toolbar" ? toolbarElement.querySelector(`[data-type="${type}"]`) : undefined;
const remove = INLINE_FORMAT_TYPES.includes(type) && !textObj ?
getRangesInlineFormats(ranges).includes(type) :
@@ -1012,7 +1012,7 @@ export class Toolbar {
}
});
}
- const toolbarElement = isMobile() ? document.querySelector("#keyboardToolbar .keyboard__dynamic").nextElementSibling : this.element;
+ const toolbarElement = isMobile() ? document.querySelector("#keyboardToolbar .keyboard__dynamic") : this.element;
const actionBtn = action === "toolbar" ? toolbarElement.querySelector(`[data-type="${type}"]`) : undefined;
const newNodes: Node[] = [];
let startContainer: Node;
diff --git a/app/tests/mobileEditingToolbar.test.js b/app/tests/mobileEditingToolbar.test.js
new file mode 100644
index 0000000000..aa0bac5956
--- /dev/null
+++ b/app/tests/mobileEditingToolbar.test.js
@@ -0,0 +1,236 @@
+const assert = require("node:assert/strict");
+const {readFileSync, mkdtempSync, rmSync} = require("node:fs");
+const path = require("node:path");
+const os = require("node:os");
+
+const runCases = async (sources, platform) => {
+ const assert = require("node:assert/strict");
+ const path = require("node:path");
+ const cache = {};
+ let current;
+ let keyboardShows = 0;
+ let keyboardHides = 0;
+ let inputRequests = 0;
+ let undoCalls = 0;
+ const inserts = [];
+ const visible = new Set(["mobile-copy", "mobile-cut", "mobile-undo", "mobile-redo", "mobile-indent",
+ "mobile-outdent", "mobile-block", "mobile-add", "mobile-heading1", "strong", "em", "mobile-separator"]);
+ const order = ["strong", "mobile-undo", "mobile-separator", "mobile-heading1", "em", "mobile-indent", "mobile-outdent"];
+ const constants = {INLINE_TYPE: ["a", "block-ref", "strong", "em", "u", "s", "code"], ZWSP: "\u200b",
+ TIMEOUT_TRANSITION: 20, TIMEOUT_COUNT: 50};
+ class LocalUndo {}
+ const stubs = {
+ "constants": {Constants: constants},
+ "mobile/editor": {getCurrentEditor: () => current && {protyle: current}},
+ "protyle/lite/mobileToolbar": {getMobileToolbarProtyle: () => undefined, getMobileToolbarUndo: () => undefined,
+ getMobileToolbarPaddingElement: protyle => protyle.element},
+ "protyle/util/compatibility": {isInAndroid: () => platform === "android", isInHarmony: () => false,
+ isInMobileApp: () => platform === "android",
+ isInEdge: () => false},
+ "mobile/util/inlineMathSelection": {createInlineMathSelection: () => ({reset() {}, update() {}, prepareInput() {}})},
+ "mobile/util/pluginToolbar": {getMobilePluginToolbarItems: () => []},
+ "protyle/undo": {LocalUndo},
+ "protyle/undo/globalUndo": {getUndoRootID: () => "doc", hasUndoStateMirror: () => true,
+ getMirror: () => ({canUndo: true, canRedo: false})},
+ "config/entryVisibility/runtime": {getEntryOrder: () => order, isEntryVisible: key => visible.has(key.slice("editor.toolbar.".length))},
+ "util/functions": {isMobile: () => true},
+ "mobile/util/menuKeyboard": {captureMenuKeyboard: () => () => {}},
+ "protyle/util/tableCellRichContext": {getTableCellRichContext: () => undefined},
+ "editor/getIcon": {getIconByType: () => "iconParagraph"},
+ "plugin/EventBusCore": {forEachPluginSubscriber() {}},
+ "protyle/util/inlineElementMarker": {stripSemanticMarkersFromRangeText: range => range.toString()},
+ "protyle/util/editorFocus": {getEditorFocusRange: (_root, range, fallback) => range || fallback,
+ restoreEditorFocusRange: (_root, range) => {
+ current.editable.focus();
+ getSelection().removeAllRanges();
+ getSelection().addRange(range);
+ return true;
+ }},
+ };
+ const load = (name) => {
+ if (stubs[name]) {
+ return stubs[name];
+ }
+ if (!sources[name]) {
+ return new Proxy({}, {get: () => () => {}});
+ }
+ if (!cache[name]) {
+ cache[name] = {};
+ new Function("require", "exports", sources[name])(relative =>
+ load(path.posix.normalize(path.posix.join(path.posix.dirname(name), relative))), cache[name]);
+ }
+ return cache[name];
+ };
+ document.body.innerHTML = '<div id="editor"><div class="protyle-content"><div class="protyle-wysiwyg" data-readonly="false" contenteditable="false"><div data-node-id="one" data-type="NodeParagraph"><div contenteditable="true">Alpha beta gamma</div></div></div></div></div><div id="model"></div><div id="keyboardToolbar" class="keyboard fn__none"></div>';
+ const root = document.querySelector(".protyle-wysiwyg");
+ const editable = root.querySelector('[contenteditable="true"]');
+ const toolbar = document.getElementById("keyboardToolbar");
+ const preview = document.createElement("div");
+ preview.className = "fn__none";
+ const selectionInput = load("mobile/util/selectionKeyboard");
+ const focus = HTMLElement.prototype.focus;
+ HTMLElement.prototype.focus = function (...args) {
+ const suppressed = selectionInput.suppressMobileSelectionFocus(this);
+ focus.apply(this, args);
+ if (!suppressed && this === editable) {
+ load("mobile/util/mobileAppUtil").callMobileAppShowKeyboard();
+ }
+ };
+ window.siyuan = {zIndex: 1, languages: {}, mobile: {size: {}}, config: {readonly: false, editor: {fontSize: 16}},
+ menus: {menu: {remove() {}}}};
+ if (platform === "android") {
+ window.JSAndroid = {showKeyboard: () => keyboardShows++, hideKeyboard: () => keyboardHides++};
+ }
+ window.addEventListener("siyuan-mobile-keyboard-change", event => {
+ if (event.detail) {
+ inputRequests++;
+ }
+ });
+ window.Lute = {Caret: "‸"};
+ current = {element: document.getElementById("editor"), editable, contentElement: root.parentElement,
+ wysiwyg: {element: root}, preview: {element: preview},
+ options: {toolbar: load("protyle/toolbar/defaults").getDefaultToolbar(true)},
+ toolbar: {isMultiSelectMode: () => false, getCurrentToolbarType: () => [], setInlineMark: () => editable.focus()},
+ gutter: {}, undo: {undo: () => undoCalls++}, hint: {fill: value => inserts.push(value)}};
+ const keyboard = load("mobile/util/keyboardToolbar");
+ keyboard.initKeyboardToolbar();
+ const settle = async () => {
+ document.dispatchEvent(new Event("selectionchange"));
+ await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
+ };
+ const select = (end = 5) => {
+ const range = document.createRange();
+ range.setStart(editable.firstChild, 0);
+ range.setEnd(editable.firstChild, end);
+ getSelection().removeAllRanges();
+ getSelection().addRange(range);
+ };
+ const touch = type => editable.dispatchEvent(new PointerEvent(type, {bubbles: true, pointerType: "touch"}));
+ touch("pointerdown");
+ assert.equal(editable.getAttribute("inputmode"), "none");
+ editable.focus();
+ assert.equal(keyboardShows, 0);
+ select();
+ touch("pointerup");
+ await settle();
+ assert.equal(selectionInput.isMobileSelectionMode(), true);
+ assert.equal(keyboardHides, platform === "android" ? 1 : 0);
+ assert.equal(toolbar.classList.contains("fn__none"), false);
+ assert.equal(toolbar.classList.contains("keyboard--selection"), true);
+ assert.equal(getSelection().toString(), "Alpha");
+ const contextMenu = new MouseEvent("contextmenu", {bubbles: true, cancelable: true});
+ editable.dispatchEvent(contextMenu);
+ assert.equal(contextMenu.defaultPrevented, true);
+ assert.equal(getSelection().toString(), "Alpha");
+ editable.blur();
+ load("mobile/util/mobileAppUtil").callMobileAppShowKeyboard();
+ assert.equal(keyboardShows, 0);
+ assert.equal(selectionInput.isMobileSelectionMode(), true);
+ assert.equal(keyboard.hideKeyboardToolbarByApp(false), load("mobile/util/touchSelection").KeyboardHideResult.PreserveSelection);
+ assert.equal(getSelection().toString(), "Alpha");
+ const action = name => toolbar.querySelector(`[data-type="${name}"]`).dispatchEvent(
+ new Event(platform === "android" ? "touchend" : "click", {bubbles: true, cancelable: true}));
+ action("strong");
+ await settle();
+ assert.equal(keyboardShows, 0);
+ assert.equal(editable.getAttribute("inputmode"), "none");
+ action("undo");
+ assert.equal(undoCalls, 1);
+ action("redo");
+ assert.equal(undoCalls, 1);
+ action("heading1");
+ assert.equal(inserts[0], "# ‸");
+ const actualOrder = [...toolbar.querySelector(".keyboard__dynamic").children]
+ .filter(item => !item.classList.contains("fn__none")).map(item => item.dataset.id);
+ assert.ok(actualOrder.indexOf("strong") < actualOrder.indexOf("mobile-undo"));
+ assert.ok(actualOrder.indexOf("mobile-heading1") < actualOrder.indexOf("em"));
+ // 显隐变化和编辑器切换不得恢复隐藏项,也不得向受限的字段编辑器插入文档块。
+ visible.delete("mobile-undo");
+ window.dispatchEvent(new Event("siyuan-entry-visibility"));
+ await settle();
+ assert.equal(toolbar.querySelector('[data-type="undo"]').classList.contains("fn__none"), true);
+ current.lite = {};
+ await settle();
+ assert.equal(toolbar.querySelector('[data-type="heading1"]').classList.contains("fn__none"), true);
+ current.lite = undefined;
+ action("done");
+ await settle();
+ assert.equal(selectionInput.isMobileSelectionMode(), false);
+ assert.equal(editable.hasAttribute("inputmode"), false);
+ assert.ok(inputRequests > 0);
+ assert.equal(keyboardShows > 0, platform === "android");
+ assert.equal(toolbar.classList.contains("keyboard--selection"), false);
+ // 短按折叠光标恢复输入,保留已有的 inputmode 属性。
+ selectionInput.clearMobileSelectionInput();
+ editable.setAttribute("inputmode", "text");
+ touch("pointerdown");
+ select(0);
+ touch("pointerup");
+ editable.click();
+ assert.equal(editable.getAttribute("inputmode"), "text");
+ assert.equal(selectionInput.isMobileSelectionMode(), false);
+ // 输入框与数据库字段弹层不会继承文档的选择模式。
+ touch("pointerdown");
+ select();
+ await settle();
+ const input = document.createElement("input");
+ document.body.append(input);
+ input.focus();
+ assert.equal(selectionInput.isMobileSelectionMode(), false);
+ assert.equal(editable.getAttribute("inputmode"), "text");
+};
+
+const runElectron = async () => {
+ const {app, BrowserWindow} = require("electron");
+ app.setPath("userData", process.argv[2]);
+ app.commandLine.appendSwitch("disable-gpu");
+ await app.whenReady();
+ const win = new BrowserWindow({show: false, width: 400, height: 800,
+ webPreferences: {nodeIntegration: true, contextIsolation: false, backgroundThrottling: false}});
+ let exitCode = 0;
+ try {
+ const ts = require("typescript");
+ const modules = ["mobile/util/selectionKeyboard", "mobile/util/keyboardToolbar", "mobile/util/toolbarActions",
+ "mobile/util/toolbarEntries", "mobile/util/mobileAppUtil", "mobile/util/mobileKeyboardChange",
+ "mobile/util/touchSelection", "mobile/util/visibleViewport", "protyle/util/hasClosest",
+ "protyle/toolbar/defaults", "protyle/toolbar/entryVisibility", "config/entryVisibility/order"];
+ const sources = Object.fromEntries(modules.map(name => [name, ts.transpileModule(
+ readFileSync(path.join(__dirname, "../src", name + ".ts"), "utf8"),
+ {compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020}}).outputText]));
+ const css = require("sass").compile(path.join(__dirname, "../src/assets/scss/mobile.scss"), {logger: {warn() {}}}).css;
+ for (const platform of ["android", "browser"]) {
+ await win.loadURL("data:text/html,<html><body></body></html>");
+ await win.webContents.insertCSS(css);
+ await win.webContents.executeJavaScript(`(${runCases.toString()})(${JSON.stringify(sources)}, ${JSON.stringify(platform)})`);
+ }
+ console.log("Mobile editing toolbar cases passed");
+ } catch (error) {
+ console.error(error);
+ exitCode = 1;
+ } finally {
+ win.destroy();
+ app.exit(exitCode);
+ }
+};
+
+if (process.versions.electron && process.type === "browser") {
+ runElectron().catch(error => {console.error(error); require("electron").app.exit(1);});
+} else {
+ require("node:test").it("keeps touch selections editable without opening the keyboard and shares toolbar configuration", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
+ timeout: 45000,
+ }, async () => {
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ const profile = mkdtempSync(path.join(os.tmpdir(), "siyuan-mobile-editing-"));
+ try {
+ const {stdout} = await require("node:util").promisify(require("node:child_process").execFile)(
+ require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 40000});
+ assert.match(stdout, /Mobile editing toolbar cases passed/);
+ } finally {
+ assert.equal(path.dirname(path.resolve(profile)), path.resolve(os.tmpdir()));
+ assert.ok(path.basename(profile).startsWith("siyuan-mobile-editing-"));
+ rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});
+ }
+ });
+}