Skip to content

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

:bug: Correct mobile video insertion and keyboard behavior https://github.com/siyuan-note/siyuan/issues/20149

Daniele76985971438
diff --git a/app/src/assets/scss/main/_mobile.scss b/app/src/assets/scss/main/_mobile.scss
index ec58fbb452..d89221071b 100644
--- a/app/src/assets/scss/main/_mobile.scss
+++ b/app/src/assets/scss/main/_mobile.scss
@@ -561,6 +561,10 @@ body.mobile-topbar--merged {
}
}
+.protyle-wysiwyg video {
+ max-height: var(--mobile-video-max-height, 90vh);
+}
+
.mobile-keyboard--open .mobile-bottom-bar,
.mobile-selection--active .mobile-bottom-bar {
opacity: 0;
diff --git a/app/src/mobile/util/keyboardOrientation.test.ts b/app/src/mobile/util/keyboardOrientation.test.ts
index 1f5f203b38..1a2a0b9a0c 100644
--- a/app/src/mobile/util/keyboardOrientation.test.ts
+++ b/app/src/mobile/util/keyboardOrientation.test.ts
@@ -11,6 +11,7 @@ import {shouldHideKeyboardAfterResize} from "./touchSelection";
const source = createSourceFile("keyboardToolbar.ts", readFileSync(join(__dirname, "keyboardToolbar.ts"), "utf8"), ScriptTarget.Latest);
let resizeSource: string;
let panelSource: string;
+let videoSource: string;
const visit = (node: Node) => {
if (isCallExpression(node) && node.expression.getText(source) === "window.addEventListener" &&
node.arguments[0].getText(source) === '"resize"' &&
@@ -20,10 +21,13 @@ const visit = (node: Node) => {
if (isVariableDeclaration(node) && node.name.getText(source) === "updateKeyboardPanelHeight") {
panelSource = node.initializer.getText(source);
}
+ if (isVariableDeclaration(node) && node.name.getText(source) === "updateVideoMaxHeight") {
+ videoSource = node.initializer.getText(source);
+ }
forEachChild(node, visit);
};
visit(source);
-assert.ok(resizeSource && panelSource);
+assert.ok(resizeSource && panelSource && videoSource);
const compile = (text: string) => transpileModule(`(${text})`, {
compilerOptions: {target: ScriptTarget.ES2020},
}).outputText;
@@ -37,6 +41,14 @@ const createBrowser = () => ({
test("portrait keyboard resizing updates only the portrait height cache", () => {
const browser = createBrowser();
+ let videoHeight: string;
+ const updateVideoMaxHeight = runInNewContext(compile(videoSource), {
+ window: browser,
+ document: {documentElement: {style: {setProperty: (name: string, value: string) => {
+ assert.equal(name, "--mobile-video-max-height");
+ videoHeight = value;
+ }}}},
+ });
const onResize = runInNewContext(compile(resizeSource), {
window: browser,
isMobileLandscape: () => isMobileLandscape(browser as unknown as typeof window),
@@ -44,6 +56,7 @@ test("portrait keyboard resizing updates only the portrait height cache", () =>
document: {activeElement: {tagName: "DIV", isContentEditable: true}},
shouldHideKeyboardAfterResize, hasRecentAndroidTableCellSelectAll: () => false,
activeBlur: () => assert.fail("keyboard-only resizing must keep editor focus"), preventRender: false,
+ updateVideoMaxHeight,
});
for (const height of [450, 1200, 450]) {
browser.innerHeight = height;
@@ -52,6 +65,7 @@ test("portrait keyboard resizing updates only the portrait height cache", () =>
assert.equal("landscape" in browser.siyuan.mobile.size, false);
assert.equal(browser.siyuan.mobile.size.portrait.height1, 1200);
assert.equal(browser.siyuan.mobile.size.portrait.height2, 450);
+ assert.equal(videoHeight, "1080px");
}
});
diff --git a/app/src/mobile/util/keyboardReference.test.ts b/app/src/mobile/util/keyboardReference.test.ts
index 9f13fbfb9c..2a6f48fd64 100644
--- a/app/src/mobile/util/keyboardReference.test.ts
+++ b/app/src/mobile/util/keyboardReference.test.ts
@@ -4,6 +4,7 @@ import {join} from "node:path";
import {test} from "node:test";
import {runInNewContext} from "node:vm";
import {createSourceFile, forEachChild, isCallExpression, isVariableDeclaration, Node, ScriptTarget, transpileModule} from "typescript";
+import {getMobileToolbarContextPath} from "../../config/entryVisibility/mobileToolbarContext";
const source = createSourceFile("keyboardToolbar.ts", readFileSync(join(__dirname, "keyboardToolbar.ts"), "utf8"), ScriptTarget.Latest);
let handlerSource: string;
@@ -40,6 +41,7 @@ test("mobile reference remains available at a caret without exposing other selec
stripSemanticMarkersFromRangeText: () => hasText ? "selected" : "",
Constants: {ZWSP: "\u200b"}, getEntryOrder: (): string[] => [], isEntryVisible: () => false,
TOOLBAR_ENTRY_ROOT_PATH: "editor.toolbar", MOBILE_TOOLBAR_NAMES: ["block-ref", "strong"],
+ getMobileToolbarContextPath,
MOBILE_TOOLBAR_ACTION_NAMES: [],
applyMobileToolbarEntries: (_element: unknown, _toolbar: unknown, options: {
isAvailable: (name: string) => boolean, isVisible: (key: string) => boolean,
diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.ts
index 6d858c93ea..0fd4aa7f6d 100644
--- a/app/src/mobile/util/keyboardToolbar.ts
+++ b/app/src/mobile/util/keyboardToolbar.ts
@@ -943,6 +943,12 @@ const restoreKeyboardToolbarRange = (protyle: IProtyle | undefined, range?: Rang
}
};
+export const resumeMobileEditorAfterInsertion = (protyle: IProtyle, range: Range) => {
+ hideKeyboardToolbarUtilOnEditorClick();
+ restoreKeyboardToolbarRange(protyle, range);
+ showKeyboardToolbar();
+};
+
export const bindMobileMenuKeyboard = (element: HTMLElement, selector: string, getProtyle: () => IProtyle) => {
let restoreKeyboard: (() => void) | undefined;
if (isMobile()) {
@@ -994,7 +1000,7 @@ const renderKeyboardToolbar = () => {
renderKeyboardToolbarFrame = window.requestAnimationFrame(() => {
renderKeyboardToolbarFrame = undefined;
if (!canInput(document.activeElement)) {
- hideKeyboardToolbar();
+ hideKeyboardToolbar(false);
return;
}
const selection = getSelection();
@@ -1085,7 +1091,7 @@ const showKeyboardToolbarElement = () => {
// 普通输入框可能保留文档选区,不能据此恢复编辑焦点或显示文档工具栏。
keyboardPanelClosing = false;
hideKeyboardToolbarUtil();
- hideKeyboardToolbar();
+ hideKeyboardToolbar(false);
notifyMobileKeyboardChange(true);
return;
}
@@ -1231,7 +1237,7 @@ const scrollKeyboardSelectionIntoView = () => {
}, Constants.TIMEOUT_TRANSITION);
};
-export const hideKeyboardToolbar = () => {
+export const hideKeyboardToolbar = (keyboardClosed = true) => {
if (renderKeyboardToolbarFrame !== undefined) {
window.cancelAnimationFrame(renderKeyboardToolbarFrame);
renderKeyboardToolbarFrame = undefined;
@@ -1261,7 +1267,10 @@ export const hideKeyboardToolbar = () => {
if (modelElement.style.transform === "translateX(0px)") {
modelElement.style.paddingBottom = "";
}
- notifyMobileKeyboardChange(false);
+ // 仅隐藏编辑工具栏时保留系统键盘状态,关闭通知由原生回调或主动收起操作发送。
+ if (keyboardClosed) {
+ notifyMobileKeyboardChange(false);
+ }
};
export const hideKeyboardToolbarByApp = (preserveSelection = false) => {
@@ -1321,6 +1330,14 @@ export const activeBlur = (force = false) => {
(document.activeElement as HTMLElement).blur();
};
+const updateVideoMaxHeight = () => {
+ const size = window.siyuan.mobile.size;
+ const height = (size.isLandscape ? size.landscape : size.portrait)?.height1;
+ if (height) {
+ document.documentElement.style.setProperty("--mobile-video-max-height", `${height * 0.9}px`);
+ }
+};
+
export const initKeyboardToolbar = () => {
window.addEventListener("siyuan-mobile-toolbar-focus", renderKeyboardToolbar);
window.addEventListener("siyuan-mobile-toolbar-editor", (event: CustomEvent<IProtyle>) => {
@@ -1332,7 +1349,7 @@ export const initKeyboardToolbar = () => {
}
keyboardPanelClosing = false;
hideKeyboardToolbarUtil();
- hideKeyboardToolbar();
+ hideKeyboardToolbar(false);
renderKeyboardToolbar();
});
let composing = false;
@@ -1427,6 +1444,7 @@ export const initKeyboardToolbar = () => {
height2: window.innerHeight,
};
}
+ updateVideoMaxHeight();
if (!isInEdge()) {
window.addEventListener("resize", () => {
updateKeyboardToolbarPosition();
@@ -1479,6 +1497,7 @@ export const initKeyboardToolbar = () => {
renderKeyboardToolbar();
}
}
+ updateVideoMaxHeight();
});
}
const toolbarElement = document.getElementById("keyboardToolbar");
diff --git a/app/src/mobile/util/keyboardVideo.test.ts b/app/src/mobile/util/keyboardVideo.test.ts
new file mode 100644
index 0000000000..733b14bfda
--- /dev/null
+++ b/app/src/mobile/util/keyboardVideo.test.ts
@@ -0,0 +1,83 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {join} from "node:path";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {createSourceFile, isVariableStatement, ScriptTarget, transpileModule} from "typescript";
+import {createMobileKeyboardChangeNotifier} from "./mobileKeyboardChange";
+
+const source = createSourceFile("keyboardToolbar.ts", readFileSync(join(__dirname, "keyboardToolbar.ts"), "utf8"), ScriptTarget.Latest);
+const extract = (name: string) => {
+ const declaration = source.statements.find(node => isVariableStatement(node) &&
+ node.declarationList.declarations.some(item => item.name.getText(source) === name));
+ assert.ok(declaration, name);
+ return declaration.getText(source).replace(/^export /, "");
+};
+
+test("a non-editable video focus hides editing controls without reporting a system keyboard close", () => {
+ const changes: boolean[] = [];
+ const timers = new Map<number, () => void>();
+ const notify = createMobileKeyboardChangeNotifier({
+ dispatch: open => changes.push(open),
+ setTimer: callback => { timers.set(1, callback); return 1; },
+ clearTimer: timer => { timers.delete(timer); },
+ });
+ const classes = new Set<string>();
+ const toolbar = {classList: {
+ contains: (name: string) => classes.has(name), add: (name: string) => { classes.add(name); },
+ }, style: {height: "48px"}};
+ let frame: () => void;
+ const context = {
+ window: {requestAnimationFrame: (callback: () => void) => { frame = callback; return 1; }, cancelAnimationFrame() {}},
+ document: {activeElement: {tagName: "VIDEO"}, getElementById: (id: string) => id === "keyboardToolbar" ? toolbar :
+ {style: {transform: ""}}},
+ renderKeyboardToolbarFrame: undefined as number | undefined, scrollSelectionIntoViewTimeout: undefined as number | undefined,
+ clearRenderGutterAfterScroll: undefined as (() => void) | undefined, showUtil: false,
+ keyboardPanelTop: undefined as number | undefined,
+ pendingKeyboardFocus: undefined as {protyle: unknown, range: unknown} | undefined,
+ canInput: () => false, getCurrentEditor: (): undefined => undefined,
+ clearTimeout() {}, notifyMobileKeyboardChange: notify,
+ };
+ const code = transpileModule([extract("hideKeyboardToolbar"), extract("renderKeyboardToolbar"),
+ "({hideKeyboardToolbar, renderKeyboardToolbar})"].join("\n"), {compilerOptions: {target: ScriptTarget.ES2020}}).outputText;
+ const api = runInNewContext(code, context);
+ notify(true);
+ api.renderKeyboardToolbar();
+ frame();
+ assert.ok(classes.has("fn__none"));
+ assert.deepEqual(changes, [true]);
+ assert.equal(timers.size, 0, "tool visibility changes must not schedule a keyboard close");
+
+ api.hideKeyboardToolbar();
+ [...timers.values()].forEach(callback => callback());
+ assert.deepEqual(changes, [true, false], "the native keyboard close still restores navigation");
+});
+
+test("video insertion hands the menu back to the keyboard and restores the paragraph range after native focus", () => {
+ for (const platform of ["android", "harmony", "ios"]) {
+ const calls: string[] = [];
+ const range = {startContainer: {isConnected: true}, endContainer: {isConnected: true}};
+ const protyle = {wysiwyg: {element: {}}, toolbar: {range: undefined as typeof range | undefined}};
+ const context = {
+ getCurrentEditor: () => ({protyle}),
+ getEditorFocusRange: () => range,
+ pendingKeyboardFocus: undefined as {protyle: unknown, range: unknown} | undefined,
+ isInAndroid: () => platform === "android", isInHarmony: () => platform === "harmony",
+ callMobileAppShowKeyboard: () => calls.push("native-show"),
+ restoreEditorFocusRange: (editor: unknown, target: unknown) => {
+ assert.equal(editor, protyle.wysiwyg.element);
+ assert.equal(target, range);
+ calls.push("focus");
+ return true;
+ },
+ hideKeyboardToolbarUtilOnEditorClick: () => calls.push("close-panel"),
+ showKeyboardToolbar: () => calls.push("show-toolbar"),
+ };
+ const code = transpileModule([extract("restoreKeyboardToolbarRange"), extract("resumeMobileEditorAfterInsertion"),
+ "resumeMobileEditorAfterInsertion"].join("\n"), {compilerOptions: {target: ScriptTarget.ES2020}}).outputText;
+ runInNewContext(code, context)(protyle, range);
+ assert.deepEqual(calls, platform === "ios" ? ["close-panel", "focus", "show-toolbar"] :
+ ["close-panel", "native-show", "focus", "show-toolbar"]);
+ assert.equal(context.pendingKeyboardFocus?.range, platform === "ios" ? undefined : range);
+ }
+});
diff --git a/app/src/protyle/render/iframeResize.test.ts b/app/src/protyle/render/iframeResize.test.ts
index 6e2d810570..b457f17153 100644
--- a/app/src/protyle/render/iframeResize.test.ts
+++ b/app/src/protyle/render/iframeResize.test.ts
@@ -10,7 +10,7 @@ import {createSourceFile, isClassDeclaration, isIfStatement, isVariableStatement
const browserCases = async (renderSource: string, resizeSource: string, luteSource: string, css: string,
bridgeSource: string, coreSource: string, insertSources: Record<string, string>,
- hintSource: string, menuSource: string) => {
+ hintSource: string, menuSource: string, mobileCSS: string) => {
const check: typeof assert = require("node:assert/strict");
document.body.replaceChildren();
new Function(luteSource)();
@@ -35,13 +35,32 @@ const browserCases = async (renderSource: string, resizeSource: string, luteSour
root.dataset.readonly = "false";
document.body.appendChild(root);
const inserts: {operations: IOperation[], undo: IOperation[]}[] = [];
+ let mobileInsertion = false;
+ let videoInsertion = false;
+ let resumed = 0;
const modules: Record<string, unknown> = {
+ "src/util/functions": {isMobile: () => mobileInsertion},
"src/constants": {Constants: {ZWSP: "\u200b", ATTRIBUTE_EDITING: "data-editing"}},
"src/util/hostCapabilities": {getHostCapabilities: () => ({remoteKernel: false})},
"src/protyle/util/selection": {
getEditorRange: () => window.getSelection().getRangeAt(0),
- focusBlock() {},
+ focusBlock: (element: Element) => {
+ if (!videoInsertion) {
+ return;
+ }
+ const range = document.createRange();
+ range.selectNodeContents(element.querySelector('[contenteditable="true"]') || element);
+ range.collapse(true);
+ window.getSelection().removeAllRanges();
+ window.getSelection().addRange(range);
+ return range;
+ },
},
+ "src/mobile/util/keyboardToolbar": {resumeMobileEditorAfterInsertion: (protyle: IProtyle, range: Range) => {
+ resumed++;
+ const {restoreEditorFocusRange} = load("src/protyle/util/editorFocus") as typeof import("../util/editorFocus");
+ check.equal(restoreEditorFocusRange(protyle.wysiwyg.element, range), true);
+ }},
"src/protyle/wysiwyg/transaction": {
transaction: (_protyle: IProtyle, operations: IOperation[], undo: IOperation[]) => inserts.push({operations, undo}),
},
@@ -98,6 +117,131 @@ const browserCases = async (renderSource: string, resizeSource: string, luteSour
}
}
}
+ const replay = (operations: IOperation[]) => {
+ operations.forEach(operation => {
+ const current = root.querySelector(`[data-node-id="${operation.id}"]`);
+ if (operation.action === "delete") {
+ current?.remove();
+ return;
+ }
+ if (typeof operation.data !== "string") {
+ throw new Error("Block insertion and update operations must contain serialized block DOM");
+ }
+ const holder = document.createElement("template");
+ holder.innerHTML = operation.data;
+ if (operation.action === "update") {
+ current.replaceWith(holder.content);
+ } else {
+ const previous = root.querySelector(`[data-node-id="${operation.previousID}"]`);
+ const next = root.querySelector(`[data-node-id="${operation.nextID}"]`);
+ if (previous) {
+ previous.after(holder.content);
+ } else if (next) {
+ next.before(holder.content);
+ } else {
+ (root.querySelector(`[data-node-id="${operation.parentID}"]`) || root).prepend(holder.content);
+ }
+ }
+ });
+ root.querySelectorAll("wbr").forEach(marker => marker.remove());
+ };
+ videoInsertion = true;
+ window.siyuan = {config: {editor: {spellcheck: false}}} as typeof window.siyuan;
+ for (const mobile of [false, true]) {
+ mobileInsertion = mobile;
+ for (const container of ["document", "list", "quote"]) {
+ for (const following of ["none", "paragraph", "video"]) {
+ for (const empty of [false, true]) {
+ root.innerHTML = lute.Md2BlockDOM(container === "list" ? "- Start" : container === "quote" ? "> Start" : "Start");
+ const paragraph = root.querySelector('[data-type="NodeParagraph"]');
+ const parent = paragraph.parentElement;
+ if (empty) {
+ paragraph.firstElementChild.replaceChildren();
+ }
+ if (following !== "none") {
+ paragraph.insertAdjacentHTML("afterend", following === "paragraph" ? lute.Md2BlockDOM("Continue here") :
+ lute.SpinBlockDOM('<video src="assets/existing.mp4" controls="controls"></video>'));
+ }
+ const next = paragraph.nextElementSibling;
+ const before = lute.BlockDOM2StdMd(root.innerHTML);
+ const range = document.createRange();
+ range.selectNodeContents(paragraph.firstElementChild);
+ range.collapse(false);
+ window.getSelection().removeAllRanges();
+ window.getSelection().addRange(range);
+ const protyle = {lute, wysiwyg: {element: root}, toolbar: {range, getCurrentType: () => []},
+ block: {parentID: "document"}} as IProtyle;
+ resumed = 0;
+ inserts.length = 0;
+ insertHTML(lute.SpinBlockDOM('<video src="assets/inserted.mp4" controls="controls"></video>'),
+ protyle, true, true);
+ const video = root.querySelector('video[src="assets/inserted.mp4"]').closest('[data-type="NodeVideo"]');
+ check.equal(video.parentElement, parent, "insertion stays in the original container");
+ check.equal(inserts.length, 1);
+ check.equal(resumed, mobile ? 1 : 0);
+ if (mobile) {
+ const target = video.nextElementSibling;
+ check.equal(target.getAttribute("data-type"), "NodeParagraph");
+ check.equal(document.activeElement, target.firstElementChild);
+ check.ok(target.contains(window.getSelection().anchorNode));
+ if (following === "paragraph") {
+ check.equal(target, next, "reuse the next paragraph without overwriting it");
+ check.equal(target.firstElementChild.textContent, "Continue here");
+ } else {
+ check.equal(target.firstElementChild.textContent, "");
+ check.ok(inserts[0].undo.some(operation => operation.action === "delete" &&
+ operation.id === target.getAttribute("data-node-id")), "undo removes the automatically created paragraph");
+ }
+ }
+ const after = lute.BlockDOM2StdMd(root.innerHTML);
+ replay(inserts[0].undo);
+ check.equal(lute.BlockDOM2StdMd(root.innerHTML), before, "one undo restores the original content");
+ replay(inserts[0].operations);
+ check.equal(lute.BlockDOM2StdMd(root.innerHTML), after, "redo restores the video and continuation paragraph");
+ }
+ }
+ }
+ }
+ root.innerHTML = lute.Md2BlockDOM("Start");
+ const sourceParagraph = root.firstElementChild;
+ const rangeBefore = document.createRange();
+ rangeBefore.selectNodeContents(sourceParagraph.firstElementChild);
+ rangeBefore.collapse(true);
+ window.getSelection().removeAllRanges();
+ window.getSelection().addRange(rangeBefore);
+ const multiProtyle = {lute, wysiwyg: {element: root}, toolbar: {range: rangeBefore, getCurrentType: () => []},
+ block: {parentID: "document"}} as IProtyle;
+ insertHTML(lute.SpinBlockDOM('<video src="assets/first.mp4"></video>') +
+ lute.SpinBlockDOM('<video src="assets/second.mp4"></video>'),
+ multiProtyle, true, true, false, "before");
+ check.deepEqual(Array.from(root.querySelectorAll("video")).map(video => video.getAttribute("src")),
+ ["assets/first.mp4", "assets/second.mp4"]);
+ check.equal(root.querySelectorAll('[data-type="NodeParagraph"]').length, 1);
+ check.equal(document.activeElement, sourceParagraph.firstElementChild, "continue after all videos inserted before existing text");
+ mobileInsertion = false;
+ videoInsertion = false;
+
+ const mobileStyle = document.createElement("style");
+ mobileStyle.textContent = mobileCSS;
+ document.head.appendChild(mobileStyle);
+ const sizedVideo = root.querySelector("video");
+ sizedVideo.style.height = "1800px";
+ sizedVideo.style.width = "100px";
+ for (const viewportHeight of [700, 350, 700]) {
+ await require("electron").ipcRenderer.invoke("video-test-resize", viewportHeight, window.innerWidth);
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ check.equal(window.innerHeight, viewportHeight);
+ document.documentElement.style.setProperty("--mobile-video-max-height", "630px");
+ check.equal(getComputedStyle(sizedVideo).maxHeight, "630px", `keyboard viewport height ${viewportHeight}`);
+ check.equal(sizedVideo.getBoundingClientRect().height, 630, "manual dimensions still obey the stable height cap");
+ }
+ document.documentElement.style.setProperty("--mobile-video-max-height", "350px");
+ check.equal(sizedVideo.getBoundingClientRect().height, 350, "rotation can update the cached height cap");
+ mobileStyle.remove();
+ document.documentElement.style.removeProperty("--mobile-video-max-height");
+ check.equal(getComputedStyle(sizedVideo).maxHeight, `${window.innerHeight * 0.9}px`,
+ "desktop and export retain the shared video height limit");
+ await require("electron").ipcRenderer.invoke("video-test-resize", null);
const constants = {ZWSP: "\u200b", ATTRIBUTE_EDITING: "data-editing", BLOCK_HINT_KEYS: ["(("], INLINE_TYPE: [] as string[]};
const selection = window.getSelection();
const menuElement = document.createElement("div");
@@ -467,8 +611,17 @@ test("external resize handles preserve source, independent axes, historical dime
"src/protyle/wysiwyg/getBlock", "src/protyle/util/inlineElementBoundary", "src/protyle/util/inlineElementMarker",
"src/protyle/util/longTextWrap", "src/protyle/util/codeBlockRenderState", "src/asset/html",
"src/protyle/hint/blockHintRange",
+ "src/protyle/util/editorFocus",
].map(file => [file, transpileModule(readFileSync(file + ".ts", "utf8"),
{compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021}}).outputText]));
+ const blockFile = createSourceFile("block.ts", readFileSync("src/block/util.ts", "utf8"), ScriptTarget.ES2021, true);
+ const emptyDeclaration = blockFile.statements.find(node => isVariableStatement(node) &&
+ node.declarationList.declarations.some(item => item.name.getText(blockFile) === "genEmptyElement"));
+ assert.ok(emptyDeclaration);
+ insertSources["src/block/util"] = transpileModule('import {Constants} from "../constants";\n' +
+ emptyDeclaration.getText(blockFile), {compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021}}).outputText;
+ const mobileCSS = compileString('@use "main/mobile";',
+ {loadPaths: ["src/assets/scss"], logger: {warn() {}, debug() {}}}).css;
const hintFile = createSourceFile("hint.ts", readFileSync("src/protyle/hint/index.ts", "utf8"), ScriptTarget.ES2021, true);
const hintDeclaration = hintFile.statements.find(node => isClassDeclaration(node) && node.name.text === "Hint");
assert.ok(hintDeclaration && isClassDeclaration(hintDeclaration));
@@ -483,7 +636,7 @@ test("external resize handles preserve source, independent axes, historical dime
{compilerOptions: {target: ScriptTarget.ES2021}}).outputText;
const makeCode = (styles: string) => "const __name = value => value; (" + browserCases.toString() + ")(" +
[renderSource, resizeSource, readFileSync("stage/protyle/js/lute/lute.min.js", "utf8"), styles, ...bridgeSources,
- insertSources, hintSource, menuSource]
+ insertSources, hintSource, menuSource, mobileCSS]
.map(value => JSON.stringify(value)).join(",") + ")";
const code = makeCode(css);
writeFileSync(script, `const {app, BrowserWindow} = require("electron");
@@ -492,6 +645,9 @@ app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});
app.whenReady().then(async () => {
const win = new BrowserWindow({show: false, width: 900, height: 700,
webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: !!process.env.SIYUAN_RESIZE_PREVIEW}});
+ require("electron").ipcMain.handle("video-test-resize", (_event, height, width) => height === null ?
+ win.webContents.debugger.sendCommand("Emulation.clearDeviceMetricsOverride") :
+ win.webContents.debugger.sendCommand("Emulation.setDeviceMetricsOverride", {width, height, deviceScaleFactor: 1, mobile: false}));
win.webContents.setBackgroundThrottling(false);
try {
win.webContents.debugger.attach("1.3");
diff --git a/app/src/protyle/util/insertHTML.ts b/app/src/protyle/util/insertHTML.ts
index 330e5fe161..41cd06cfe7 100644
--- a/app/src/protyle/util/insertHTML.ts
+++ b/app/src/protyle/util/insertHTML.ts
@@ -12,6 +12,7 @@ import {copyTableCellContent} from "./tableCellRich";
import {
fixAdjacentTags,
getContenteditableElement,
+ getNextBlockSibling,
getParentBlock,
getPreviousBlockSibling
} from "../wysiwyg/getBlock";
@@ -66,6 +67,8 @@ import {resetCodeBlockRenderState} from "./codeBlockRenderState";
import {getTextWithoutSemanticMarkers} from "./inlineElementMarker";
import {normalizeHTMLAssetIFrameSources} from "../../asset/html";
import {renderIFrameResize} from "../render/iframeResize";
+import {genEmptyElement} from "../../block/util";
+import {resumeMobileEditorAfterInsertion} from "../../mobile/util/keyboardToolbar";
// 粘贴时临时插入的占位行标记,遍历结束后统一移除,避免污染虚拟滚动的 renderedStart/renderedEnd/spacer 状态
const PLACEHOLDER_ROW_CLASS = "av__row--placeholder";
@@ -1397,6 +1400,19 @@ export const insertHTML = (html: string, protyle: IProtyle, isBlock = false,
}
normalizeHTMLAssetIFrameSources(tempElement.content);
markFoldHeadingChildren(tempElement.content);
+ let mobileVideoFocus: Element;
+ if (isMobile() && !templateDocTreePlanID &&
+ tempElement.content.lastElementChild?.getAttribute("data-type") === "NodeVideo") {
+ // 视频插入后在同一容器内继续编辑,新增段落与视频共用一次撤销事务。
+ const nextElement = insertBefore ? blockElement : getNextBlockSibling(blockElement);
+ if (nextElement?.getAttribute("data-type") === "NodeParagraph" &&
+ nextElement.getAttribute("fold") !== "1" && !nextElement.hasAttribute("parent-heading")) {
+ mobileVideoFocus = nextElement;
+ } else {
+ mobileVideoFocus = genEmptyElement(false, false);
+ tempElement.content.appendChild(mobileVideoFocus);
+ }
+ }
(insertBefore ? Array.from(tempElement.content.children) : Array.from(tempElement.content.children).reverse()).find((item) => {
let addId = item.getAttribute("data-node-id");
const hasParentHeading = item.getAttribute("parent-heading");
@@ -1491,7 +1507,12 @@ export const insertHTML = (html: string, protyle: IProtyle, isBlock = false,
});
blockElement.remove();
}
- if (lastElement) {
+ if (mobileVideoFocus) {
+ const focusRange = focusBlock(mobileVideoFocus);
+ if (focusRange) {
+ resumeMobileEditorAfterInsertion(protyle, focusRange);
+ }
+ } else if (lastElement) {
// https://github.com/siyuan-note/siyuan/issues/5591
focusBlock(lastElement, undefined, false);
}