An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Restore tablet block gutters after keyboard resize and selection https://github.com/siyuan-note/siyuan/issues/19909
Daniel55979aadcdb2
diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.tsindex 27b00af2ae..953fdb34de 100644--- a/app/src/mobile/util/keyboardToolbar.ts+++ b/app/src/mobile/util/keyboardToolbar.ts@@ -82,6 +82,7 @@ import {applyMobileToolbarEntries} from "./toolbarEntries";import {getEntryOrder, isEntryVisible} from "../../config/entryVisibility/runtime";import {TOOLBAR_ENTRY_ROOT_PATH} from "../../protyle/toolbar/defaults";import {getKeyboardPanelHeight} from "./keyboardPanelHeight";+import {restoreGutterBySelection} from "../../protyle/gutter/restore";import {mountLiteSlashMenu} from "./liteSlashMenu";import {getTableCellRichContext} from "../../protyle/util/tableCellRichContext";import {insertEmptyBlock} from "../../block/util";@@ -1162,14 +1163,7 @@ const scrollKeyboardSelectionIntoView = () => {const contentElement = hasClosestByClassName(range.startContainer, "protyle-content", true);if (contentElement) {const renderGutter = () => {- const blockElement = hasClosestBlock(range.startContainer);- if (!editor?.protyle.gutter || !editor.protyle.options.render.gutter ||- !blockElement || !editor.protyle.wysiwyg.element.contains(blockElement)) {- return;- }- const targetElement = range.startContainer.nodeType === Node.ELEMENT_NODE ?- range.startContainer as Element : range.startContainer.parentElement;- editor.protyle.gutter.render(editor.protyle, blockElement, targetElement);+ restoreGutterBySelection(editor.protyle);};let cursorTop = getSelectionPosition(contentElement, range.cloneRange()).top;if (cursorTop < 0 && window.siyuan.mobile.touchRange) {diff --git a/app/src/protyle/gutter/restore.test.ts b/app/src/protyle/gutter/restore.test.tsnew file mode 100644index 0000000000..0a766894e9--- /dev/null+++ b/app/src/protyle/gutter/restore.test.ts@@ -0,0 +1,230 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";++const compile = (file: string) => transpileModule(readFileSync(`src/protyle/${file}.ts`, "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+}).outputText;+const restoreSource = compile("gutter/restore");+const resizeSource = compile("util/resize");++class TestElement {+ public nodeType = 1;+ public isConnected = true;+ public visible = true;+ public selected: TestElement[] = [];+ public classes = new Set<string>();+ public classList = {contains: (name: string) => this.classes.has(name)};+ public top = 10;+ public bottom = 40;+ public ownerDocument: any;+ public embed?: TestElement;+ public embedContext = false;++ constructor(public parentElement?: TestElement, public block = false, public editor = false) {+ }++ public contains(element: TestElement): boolean {+ return !!element && (element === this || this.contains(element.parentElement));+ }++ public closest(): TestElement | null {+ return this.editor ? this : this.parentElement?.closest() || null;+ }++ public querySelectorAll(selector: string) {+ return selector === ".protyle-wysiwyg--select" ? this.selected : [];+ }++ public querySelector(): null {+ return null;+ }++ public getClientRects() {+ return this.visible ? [this.getBoundingClientRect()] : [];+ }++ public getBoundingClientRect() {+ return {top: this.top, bottom: this.bottom};+ }+}++const fixture = () => {+ const root = new TestElement(undefined, false, true);+ const blocks = [new TestElement(root, true), new TestElement(root, true), new TestElement(root, true)];+ const editable = blocks.map(block => new TestElement(block));+ const selection = {focusNode: editable[0]};+ const ownerDocument = {body: new TestElement(), activeElement: editable[0], getSelection: () => selection};+ root.ownerDocument = ownerDocument;+ let phablet = true;+ let mobile = false;+ let multiSelect = false;+ let rendered: TestElement | undefined;+ const calls: TestElement[] = [];+ const frames: FrameRequestCallback[] = [];+ const timers: Array<() => void> = [];+ const protyle: any = {+ wysiwyg: {element: root},+ gutter: {render: (_protyle: unknown, block: TestElement) => {+ rendered = block;+ calls.push(block);+ }},+ options: {render: {gutter: true}},+ toolbar: {isMultiSelectMode: () => multiSelect},+ contentElement: {getBoundingClientRect: () => ({top: 0, bottom: 100})},+ };+ const modules: Record<string, unknown> = {+ "../util/compatibility": {isPhablet: () => phablet},+ "../../util/functions": {isMobile: () => mobile},+ "../util/hasClosest": {+ hasClosestBlock: (element: TestElement) => {+ while (element && !element.block) {+ element = element.parentElement;+ }+ return element;+ },+ isInEmbedBlock: (element: TestElement) => element.embed,+ },+ "../wysiwyg/blockSelection": {BLOCK_SELECTION_CLASS: "protyle-wysiwyg--select"},+ "../wysiwyg/getBlock": {getEmbedGutterOperationContext: (block: TestElement) => block.embedContext},+ "../ui/hideElements": {hideElements: (): void => { rendered = undefined; }},+ "../ui/initUI": {setPadding: () => ({width: 0})},+ "../../constants": {Constants: {TIMEOUT_TRANSITION: 300}},+ };+ const globals = {+ require: (name: string) => modules[name], Node: {ELEMENT_NODE: 1}, window: {},+ requestAnimationFrame: (callback: FrameRequestCallback) => frames.push(callback),+ setTimeout: (callback: () => void) => timers.push(callback),+ };+ const restoreExports: any = {};+ runInNewContext(restoreSource, {...globals, exports: restoreExports});+ modules["../gutter/restore"] = restoreExports;+ const resizeExports: any = {};+ runInNewContext(resizeSource, {...globals, exports: resizeExports});+ return {+ root, blocks, editable, selection, ownerDocument, protyle, calls,+ render: (selectedElement?: TestElement) => restoreExports.restoreGutterBySelection(protyle, selectedElement),+ resize: () => resizeExports.resize(protyle),+ clearGutter: (): void => { rendered = undefined; },+ rendered: () => rendered,+ flushTimers: () => timers.splice(0).forEach(callback => callback()),+ flushFrames: () => frames.splice(0).forEach(callback => callback(0)),+ setMultiSelect: () => multiSelect = true,+ setDesktop: () => phablet = false,+ setMobile: () => mobile = true,+ };+};++test("keyboard resize restores the latest caret after layout and scroll cleanup", () => {+ const f = fixture();+ f.render();+ f.resize();+ assert.equal(f.rendered(), undefined);+ f.selection.focusNode = f.editable[1];+ f.ownerDocument.activeElement = f.editable[1];+ f.flushTimers();+ f.clearGutter();+ f.flushFrames();+ assert.equal(f.rendered(), f.blocks[1]);+ f.resize();+ f.flushTimers();+ f.flushFrames();+ assert.equal(f.rendered(), f.blocks[1], "keyboard dismissal also restores the current block");+});++test("block selection restores a visible selected block even when the caret is outside the selection", () => {+ const f = fixture();+ f.root.selected = [f.blocks[0], f.blocks[1]];+ f.selection.focusNode = f.editable[1];+ f.render();+ assert.equal(f.rendered(), f.blocks[1]);+ f.selection.focusNode = f.editable[2];+ f.blocks[0].bottom = -1;+ f.render();+ assert.equal(f.rendered(), f.blocks[1]);+ f.blocks[1].visible = false;+ f.clearGutter();+ f.render();+ assert.equal(f.rendered(), undefined);+});++test("pending restoration leaves another editor, a nested editor, and dialog inputs alone", () => {+ const f = fixture();+ for (const active of [new TestElement(undefined, false, true), new TestElement(f.root, false, true),+ new TestElement()]) {+ f.resize();+ f.flushTimers();+ f.ownerDocument.activeElement = active;+ f.flushFrames();+ assert.equal(f.rendered(), undefined);+ }+});++test("padding selection ending below the document restores its gutter without a native range", () => {+ const f = fixture();+ f.root.selected = [f.blocks[0], f.blocks[1]];+ f.selection.focusNode = undefined;+ f.ownerDocument.activeElement = f.ownerDocument.body;+ f.render(f.blocks[0]);+ assert.equal(f.rendered(), f.blocks[0]);+ f.clearGutter();+ f.selection.focusNode = new TestElement();+ f.render(f.blocks[0]);+ assert.equal(f.rendered(), undefined, "another selection takes precedence over the completed drag");+ f.selection.focusNode = undefined;+ f.root.selected = [];+ f.render(f.blocks[0]);+ assert.equal(f.rendered(), undefined, "a cleared selection must not be resurrected");+});++test("keyboard dismissal can leave focus on body while retaining this editor's selection", () => {+ const f = fixture();+ f.ownerDocument.activeElement = f.ownerDocument.body;+ f.render();+ assert.equal(f.rendered(), f.blocks[0]);+ f.clearGutter();+ f.selection.focusNode = new TestElement();+ f.render();+ assert.equal(f.rendered(), undefined);+});++test("restoration respects hidden editors, active drags, mobile multi-select, and disabled gutters", () => {+ const changes = [+ (f: ReturnType<typeof fixture>) => f.root.isConnected = false,+ (f: ReturnType<typeof fixture>) => f.root.visible = false,+ (f: ReturnType<typeof fixture>) => f.root.classes.add("fn__pointer-none"),+ (f: ReturnType<typeof fixture>) => f.root.classes.add("protyle-wysiwyg--hiderange"),+ (f: ReturnType<typeof fixture>) => f.setMultiSelect(),+ (f: ReturnType<typeof fixture>) => f.protyle.options.render.gutter = false,+ (f: ReturnType<typeof fixture>) => f.selection.focusNode = new TestElement(),+ ];+ changes.forEach(change => {+ const f = fixture();+ change(f);+ f.render();+ assert.equal(f.calls.length, 0);+ });+});++test("desktop hover behavior is preserved while the mobile interface supports keyboard restoration", () => {+ const f = fixture();+ f.setDesktop();+ f.render();+ assert.equal(f.calls.length, 0);+ f.setMobile();+ f.render();+ assert.equal(f.rendered(), f.blocks[0]);+});++test("embedded content restores its existing operation boundary", () => {+ const f = fixture();+ const embed = new TestElement(f.root, true);+ f.blocks[0].embed = embed;+ f.render();+ assert.equal(f.rendered(), embed);+ f.blocks[0].embedContext = true;+ f.render();+ assert.equal(f.rendered(), f.blocks[0]);+});diff --git a/app/src/protyle/gutter/restore.ts b/app/src/protyle/gutter/restore.tsnew file mode 100644index 0000000000..f61947c81b--- /dev/null+++ b/app/src/protyle/gutter/restore.ts@@ -0,0 +1,52 @@+import {isPhablet} from "../util/compatibility";+import {hasClosestBlock, isInEmbedBlock} from "../util/hasClosest";+import {BLOCK_SELECTION_CLASS} from "../wysiwyg/blockSelection";+import {getEmbedGutterOperationContext} from "../wysiwyg/getBlock";+import {isMobile} from "../../util/functions";++export const restoreGutterBySelection = (protyle: IProtyle, selectedElement?: Element) => {+ const root = protyle.wysiwyg.element;+ const ownerDocument = root.ownerDocument;+ const activeElement = ownerDocument.activeElement;+ // 触屏没有悬停事件,布局稳定后从当前焦点恢复块标,避免其他编辑器抢占块标。+ if ((!isPhablet() && !isMobile()) || !protyle.gutter || !protyle.options.render.gutter ||+ !root.isConnected || root.getClientRects().length === 0 ||+ protyle.toolbar.isMultiSelectMode() || root.classList.contains("fn__pointer-none") ||+ root.classList.contains("protyle-wysiwyg--hiderange") ||+ (activeElement && activeElement !== ownerDocument.body &&+ activeElement.closest(".protyle-wysiwyg") !== root)) {+ return;+ }+ const selection = ownerDocument.getSelection();+ const selected = Array.from(root.querySelectorAll<HTMLElement>(`.${BLOCK_SELECTION_CLASS}`))+ .filter(item => item.closest(".protyle-wysiwyg") === root);+ let pointerElement = selection?.focusNode?.nodeType === Node.ELEMENT_NODE ?+ selection.focusNode as Element : selection?.focusNode?.parentElement;+ if (pointerElement && pointerElement.closest(".protyle-wysiwyg") !== root) {+ return;+ }+ if (!pointerElement) {+ // 在文档末尾外侧结束框选时可能没有文字光标,使用仍然选中的块作为定位目标。+ if (!selectedElement || !selected.includes(selectedElement as HTMLElement)) {+ return;+ }+ pointerElement = selectedElement;+ }+ let block = hasClosestBlock(pointerElement);+ if (selected.length > 0) {+ const rect = protyle.contentElement.getBoundingClientRect();+ const visible = selected.filter(item => {+ const blockRect = item.getBoundingClientRect();+ return item.getClientRects().length > 0 && blockRect.bottom > rect.top && blockRect.top < rect.bottom;+ });+ block = visible.find(item => item.contains(pointerElement)) || visible[0];+ }+ if (!block || !root.contains(block)) {+ return;+ }+ const embed = isInEmbedBlock(block);+ if (embed && !getEmbedGutterOperationContext(block)) {+ block = embed;+ }+ protyle.gutter.render(protyle, block, block.contains(pointerElement) ? pointerElement : block);+};diff --git a/app/src/protyle/util/resize.ts b/app/src/protyle/util/resize.tsindex 87750951e1..fd394ca5e5 100644--- a/app/src/protyle/util/resize.ts+++ b/app/src/protyle/util/resize.ts@@ -7,6 +7,7 @@ import {lineNumberRender} from "../render/highlightRender";import {getAllModels} from "../../layout/getAll";/// #endifimport {stickyRow} from "../render/av/row";+import {restoreGutterBySelection} from "../gutter/restore";export const clearBeforeResizeTop = () => {/// #if !MOBILE@@ -90,5 +91,7 @@ export const resize = (protyle: IProtyle) => {}});restoreBeforeResizeTop(protyle);+ // 等待恢复滚动位置触发的 scroll 事件清理块标后,再按最新选区渲染。+ requestAnimationFrame(() => restoreGutterBySelection(protyle));}, Constants.TIMEOUT_TRANSITION + 100); // 等待 setPadding 动画结束};diff --git a/app/src/protyle/wysiwyg/boundedBlockDragSelect.test.ts b/app/src/protyle/wysiwyg/boundedBlockDragSelect.test.tsindex d8a9890fb3..b234edd677 100644--- a/app/src/protyle/wysiwyg/boundedBlockDragSelect.test.ts+++ b/app/src/protyle/wysiwyg/boundedBlockDragSelect.test.ts@@ -20,6 +20,8 @@ const fixture = (mobile = false) => {let focused: unknown;let modeElement: unknown;let toolbarCount = 0;+ let gutterRestored = 0;+ const frames: FrameRequestCallback[] = [];const states = [new Set<string>(), new Set<string>()];const blocks = states.map((state, index) => ({classList: {add: (name: string) => state.add(name), remove: (name: string) => state.delete(name)},@@ -59,11 +61,13 @@ const fixture = (mobile = false) => {getBlockRangeSelectElements: () => ({selectElements: blocks}),},"../ui/hideElements": {hideElements: () => {}},+ "../gutter/restore": {restoreGutterBySelection: () => gutterRestored++},"../../util/functions": {isMobile: () => mobile},"../../layout/status": {countBlockWord: () => {}},"../../mobile/util/multiSelectToolbar": {updateMultiSelectToolbar: (_element: unknown, count: number) => toolbarCount = count},};- runInNewContext(compiled, {exports, require: (name: string) => modules[name], window: {siyuan: {}}});+ runInNewContext(compiled, {exports, require: (name: string) => modules[name], window: {siyuan: {}},+ requestAnimationFrame: (callback: FrameRequestCallback) => frames.push(callback)});// 构造 WYSIWYG 时实例尚未赋给 protyle,绑定阶段不能从 protyle 读取编辑器元素。exports.bindBoundedBlockDragSelect(protyle, element);protyle.wysiwyg = {element};@@ -84,7 +88,8 @@ const fixture = (mobile = false) => {setBacklink: () => backlink = true,detach: () => blockOwned = false,enterMultiSelect: () => multiSelect = true,- state: () => ({focused, modeElement, multiSelect, selectionCleared, toolbarCount}),+ flushFrames: () => frames.splice(0).forEach(callback => callback(0)),+ state: () => ({focused, modeElement, multiSelect, selectionCleared, toolbarCount, gutterRestored}),};};@@ -126,6 +131,9 @@ test("desktop completion uses existing block selection and a focusable block witassert.equal(f.state().modeElement, f.blocks[1]);assert.equal(f.classes.has("protyle-wysiwyg--hiderange"), false);assert.equal(f.options.canStart("mouse"), true);+ assert.equal(f.state().gutterRestored, 0);+ f.flushFrames();+ assert.equal(f.state().gutterRestored, 1);});test("mobile completion retains the multi-select toolbar and cancellation does not steal focus", () => {@@ -137,10 +145,22 @@ test("mobile completion retains the multi-select toolbar and cancellation does nf.options.select(f.blocks[0], f.blocks[1], "touch");assert.equal(f.state().toolbarCount, 2);f.options.finish("touch", true);+ f.flushFrames();+ assert.equal(f.state().gutterRestored, 0, "mobile keeps its multi-select toolbar");assert.equal(f.classes.has("protyle-wysiwyg--hiderange"), false);const removed = fixture();removed.options.select(removed.blocks[0], removed.blocks[1], "mouse");removed.detach();removed.options.finish("mouse", false);+ removed.flushFrames();+ assert.equal(removed.state().gutterRestored, 0);assert.equal(removed.state().focused, undefined);});++test("cancelled bounded selection does not restore a gutter after losing focus", () => {+ const f = fixture();+ f.options.select(f.blocks[0], f.blocks[1], "touch");+ f.options.finish("touch", true);+ f.flushFrames();+ assert.equal(f.state().gutterRestored, 0);+});diff --git a/app/src/protyle/wysiwyg/boundedBlockDragSelect.ts b/app/src/protyle/wysiwyg/boundedBlockDragSelect.tsindex 8757842323..1ab9b12ee8 100644--- a/app/src/protyle/wysiwyg/boundedBlockDragSelect.ts+++ b/app/src/protyle/wysiwyg/boundedBlockDragSelect.ts@@ -9,6 +9,7 @@ import {getBlockDragSelectBlock} from "./blockDragSelect";import {bindBlockDragSelectionGesture} from "./blockDragSelectionGesture";import {BLOCK_SELECTION_CLASS, clearBlockSelectionMode, setBlockSelectionModeElement} from "./blockSelection";import {isContainerBlock} from "./getBlock";+import {restoreGutterBySelection} from "../gutter/restore";export const bindBoundedBlockDragSelect = (protyle: IProtyle, element: HTMLElement) => {let selected: HTMLElement[] = [];@@ -98,6 +99,7 @@ export const bindBoundedBlockDragSelect = (protyle: IProtyle, element: HTMLEleme// 保留单块内的折叠光标,让复制、剪切和删除复用已有块选区处理。focusBlock(activeBlock);setBlockSelectionModeElement(element, activeBlock);+ requestAnimationFrame(() => restoreGutterBySelection(protyle));}}countBlockWord(selected.map(item => item.getAttribute("data-node-id")), protyle);diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.tsindex a5f4294c30..2e874ee19b 100644--- a/app/src/protyle/wysiwyg/index.ts+++ b/app/src/protyle/wysiwyg/index.ts@@ -230,6 +230,7 @@ import {resolveBlockDragSelectStart} from "./blockDragSelect";import {isCrossBlockTextRange} from "../gutter/multiSelect";+import {restoreGutterBySelection} from "../gutter/restore";import {bindTouchBlockDragSelect} from "./touchBlockDragSelect";import {formatPainter} from "../toolbar/FormatPainter";import {shouldFoldEmbeddedListByAlt, shouldOpenListItemAttr} from "./listContext";@@ -2993,6 +2994,9 @@ export class WYSIWYG {}const selectElement = protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select");+ if (startsFromPadding && selectElement.length > 0) {+ requestAnimationFrame(() => restoreGutterBySelection(protyle, selectElement[0]));+ }if (avDragSelectMode === "items" && avDragSelectElement) {setAVDragItemAnchor(avDragSelectElement);countBlockWord([], protyle);