Skip to content

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

:bug: Stabilize list gutters across marker hover https://github.com/siyuan-note/siyuan/issues/20500

Daniel147e80185b00
diff --git a/app/src/boot/globalEvent/mousemove.ts b/app/src/boot/globalEvent/mousemove.ts
index b6b314f98f..7388c91881 100644
--- a/app/src/boot/globalEvent/mousemove.ts
+++ b/app/src/boot/globalEvent/mousemove.ts
@@ -210,11 +210,19 @@ export const windowMouseMove = (event: MouseEvent) => {
if (!targetBlockElement) {
return;
}
+ const listElement = hasClosestBlock(eventPath0);
+ const renderGutter = (protyle: IProtyle) => {
+ // 经过列表序标或留白移向块标时,保留当前子块的操作入口。
+ if (!listElement || !isContainerGutterBridge(protyle.gutter.element, listElement, eventPath0,
+ event.clientX, event.clientY, button => protyle.gutter.getNodeElement(protyle, button))) {
+ protyle.gutter.render(protyle, targetBlockElement);
+ }
+ };
const allModels = getAllModels();
let findNode = false;
allModels.editor.find(item => {
if (item.editor.protyle.wysiwyg.element.contains(eventPath0)) {
- item.editor.protyle.gutter.render(item.editor.protyle, targetBlockElement);
+ renderGutter(item.editor.protyle);
findNode = true;
return true;
}
@@ -223,7 +231,7 @@ export const windowMouseMove = (event: MouseEvent) => {
window.siyuan.blockPanels.find(item => {
item.editors.find(eItem => {
if (eItem.protyle.wysiwyg.element.contains(eventPath0)) {
- eItem.protyle.gutter.render(eItem.protyle, targetBlockElement);
+ renderGutter(eItem.protyle);
findNode = true;
return true;
}
@@ -237,7 +245,7 @@ export const windowMouseMove = (event: MouseEvent) => {
allModels.backlink.find(item => {
item.editors.find(eItem => {
if (eItem.protyle.wysiwyg.element.contains(eventPath0)) {
- eItem.protyle.gutter.render(eItem.protyle, targetBlockElement);
+ renderGutter(eItem.protyle);
findNode = true;
return true;
}
diff --git a/app/src/protyle/gutter/container.test.ts b/app/src/protyle/gutter/container.test.ts
index 6b89e4dc46..e280435d72 100644
--- a/app/src/protyle/gutter/container.test.ts
+++ b/app/src/protyle/gutter/container.test.ts
@@ -37,7 +37,7 @@ const setup = (type = "NodeBlockquote") => {
describe("isContainerGutterBridge", () => {
it("preserves a child gutter while crossing nested container padding", () => {
- ["NodeBlockquote", "NodeCallout", "NodeSuperBlock"].forEach(type => {
+ ["NodeBlockquote", "NodeCallout", "NodeSuperBlock", "NodeList", "NodeListItem"].forEach(type => {
assert.equal(setup(type).hit(), true);
});
});
@@ -79,6 +79,9 @@ describe("isContainerGutterBridge", () => {
const fold = setup();
fold.button.dataset.type = "fold";
assert.equal(fold.hit(), false);
+ const row = setup("NodeListItem");
+ row.button.dataset.rowId = "row";
+ assert.equal(row.hit(), false, "database row actions must not become the list marker's block actions");
});
it("keeps callout titles directly accessible", () => {
diff --git a/app/src/protyle/gutter/container.ts b/app/src/protyle/gutter/container.ts
index c00f3e51de..9e7f5b25c3 100644
--- a/app/src/protyle/gutter/container.ts
+++ b/app/src/protyle/gutter/container.ts
@@ -18,13 +18,14 @@ export const getListItemGutterContainer = (element: Element) => {
export const isContainerGutterBridge = (gutter: HTMLElement, container: HTMLElement, target: HTMLElement,
x: number, y: number, getBlock: (button: HTMLElement) => Element) => {
if (gutter.classList.contains("fn__none") ||
- !["NodeBlockquote", "NodeCallout", "NodeSuperBlock", "NodeBlockQueryEmbed"].includes(container.dataset.type) ||
+ !["NodeBlockquote", "NodeCallout", "NodeSuperBlock", "NodeBlockQueryEmbed", "NodeList", "NodeListItem"]
+ .includes(container.dataset.type) ||
target.closest(".callout-info")) {
return false;
}
const gutterRect = gutter.getBoundingClientRect();
return Array.from(gutter.querySelectorAll<HTMLElement>("button[data-node-id]")).some(button => {
- if (button.dataset.type === "fold") {
+ if (button.dataset.type === "fold" || button.dataset.rowId) {
return false;
}
const block = getBlock(button);
diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.ts
index e47a83b240..7dff4a6d53 100644
--- a/app/src/protyle/gutter/index.ts
+++ b/app/src/protyle/gutter/index.ts
@@ -3822,7 +3822,8 @@ export class Gutter {
}
}
// - > # 1 \n > 2
- if (type === "NodeListItem" && index > 0 && nodeElement !== listItemContainer?.parentElement) {
+ const containsListItemContainer = listItemContainer && nodeElement.contains(listItemContainer);
+ if (type === "NodeListItem" && index > 0 && !containsListItemContainer) {
// 列表项内的块不显示块标
html = "";
}
@@ -3867,7 +3868,7 @@ data-type="fold"${viewOccurrenceID ? ` data-view-occurrence-id="${encodeURICompo
if (type === "NodeListItem" || type === "NodeList") {
listItem = nodeElement;
if (type === "NodeListItem" && nodeElement.childElementCount > 3) {
- html = nodeElement === listItemContainer?.parentElement ?
+ html = containsListItemContainer ?
html + foldHTML : buttonHTML + foldHTML;
}
}
@@ -3962,8 +3963,9 @@ data-type="fold"${viewOccurrenceID ? ` data-view-occurrence-id="${encodeURICompo
titleElement?.getBoundingClientRect().bottom,
);
}
- // 脑图中的原始列表项已隐藏,使用可见面板定位列表块标。
- let rect = (listItemContainer || mindmapElement || element).getBoundingClientRect();
+ // 数据库行操作跟随当前行,其余列表容器使用统一锚点,独立脑图使用可见面板。
+ let rect = (element.classList.contains("av__row") ? element :
+ listItemContainer || mindmapElement || element).getBoundingClientRect();
let marginHeight = 0;
const autoListDirection = getAutoListDirection(element);
const isRTL = autoListDirection ? autoListDirection === "rtl" :
@@ -4039,7 +4041,8 @@ data-type="fold"${viewOccurrenceID ? ` data-view-occurrence-id="${encodeURICompo
marginHeight = gutterMarginHeight;
} else if (
(nodeElement.getAttribute("data-type") === "NodeAttributeView" ||
- element.getAttribute("data-type") === "NodeAttributeView") &&
+ element.getAttribute("data-type") === "NodeAttributeView" ||
+ listItemContainer?.getAttribute("data-type") === "NodeAttributeView") &&
contentTop < rect.top) {
marginHeight = 8;
}
diff --git a/app/tests/listContainerGutter.test.js b/app/tests/listContainerGutter.test.js
index bfc0e0b70a..e065a1c6fe 100644
--- a/app/tests/listContainerGutter.test.js
+++ b/app/tests/listContainerGutter.test.js
@@ -11,40 +11,58 @@ const sources = (full = false) => {
const render = gutter.members.find(node => node.name?.getText(source) === "render");
const body = full ? render.body.getText(source) :
render.body.getText(source).split("const shouldRenderInsert")[0] + "return html; }";
- const helpers = ["protyle/gutter/container.ts", "protyle/wysiwyg/getBlock.ts", "protyle/gutter/layout.ts"].map(file => {
+ const helpers = ["protyle/gutter/container.ts", "protyle/wysiwyg/getBlock.ts", "protyle/gutter/layout.ts",
+ "protyle/util/hasClosest.ts", "protyle/render/autoDirection.ts"].map(file => {
const source = ts.createSourceFile(file, readFileSync(path.join(__dirname, "../src", file), "utf8"),
ts.ScriptTarget.Latest, true);
return source.statements.filter(node => ts.isVariableStatement(node) &&
node.declarationList.declarations.some(declaration => ["getListItemGutterContainer", "getTopAloneElement",
"getSbChildBlockCount", "getParentBlock", "getGutterMarginHeight", "getFixedGutterPosition",
- "getBacklinkGutterContentTop", "getListGutterAnchorLeft"].includes(declaration.name.getText(source))))
+ "getBacklinkGutterContentTop", "getListGutterAnchorLeft", "getContainerGutterSpace", "isContainerGutterBridge",
+ "hasClosestBlock", "isBlockElement", "hasClosestByClassName", "hasTopClosestByClassName", "hasClosestByTag",
+ "hasClosestByAttribute", "getAutoListDirection", "listSelector", "directionAttribute"].includes(declaration.name.getText(source))))
.map(node => node.getText(source)).join("\n");
}).join("\n").replace(/export const /g, "const ");
- return ts.transpileModule(helpers + `\nfunction render(protyle, element, target) ${body}`, {
+ const hoverSource = ts.createSourceFile("initUI.ts", readFileSync(path.join(__dirname,
+ "../src/protyle/ui/initUI.ts"), "utf8"), ts.ScriptTarget.Latest, true);
+ let hoverBinding;
+ const visit = node => {
+ if (ts.isCallExpression(node) && node.expression.getText(hoverSource) === "protyle.element.addEventListener" &&
+ node.arguments[0].getText(hoverSource).includes('"pointerover"')) {
+ hoverBinding = node.getText(hoverSource);
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(hoverSource);
+ assert.ok(hoverBinding);
+ const events = readFileSync(path.join(__dirname, "../src/boot/globalEvent/mousemove.ts"), "utf8")
+ .replace(/^import .*;\r?\n/gm, "").replace(/^export /gm, "") +
+ `\nfunction bindHover(protyle) { let overAttr = false; ${hoverBinding}; }`;
+ return ts.transpileModule(helpers + `\nfunction render(protyle, element, target) ${body}\n` + (full ? events : ""), {
compilerOptions: {target: ts.ScriptTarget.ES2021},
}).outputText;
};
-const cases = (source, fullSource) => {
+const cases = (source, fullSource, css) => {
const check = require("node:assert/strict");
const noop = () => false;
const dependencies = {
Constants: {CUSTOM_SY_LIST_MINDMAP: "custom-sy-list-mindmap"}, hideElements: noop, getCrossBlockTextRange: noop,
getGutterSelection: () => ({isMultiSelect: false, selectElements: []}),
getHorizontalSuperBlockChild: noop, getEmbedGutterOperationContext: noop, isInEmbedBlock: noop,
- isInAVBlock: noop, hasViewFoldContext: noop, getContainerGutterSpace: () => 0,
- hasClosestBlock: element => element.closest("[data-node-id]"),
- hasClosestByClassName: (element, name) => element?.closest("." + name),
- hasTopClosestByClassName: (element, name) => element?.closest("." + name),
- hasClosestByAttribute: (element, name, value) => element.closest(`[${name}="${value}"]`),
- getAutoListDirection: () => undefined, getGutterFixedContainerRect: noop,
+ isInAVBlock: noop, hasViewFoldContext: noop, getGutterFixedContainerRect: noop,
+ isMobile: () => mobile, isWindow: noop, isTabGutterBridge: noop, isMac: noop,
+ getAllModels: () => ({editor: [{editor: {protyle}}], backlink: []}), getAllEditor: () => [{protyle}],
isGutterInsertStateMatched: (count, insert) => count === (insert ? 4 : 0),
getBlockTypeName: type => type, getIconByType: () => "iconTest",
- genGutterBlockButtonHTML: data => `<button data-type="${data.type}" data-node-id="${data.nodeID}"></button>`,
+ genGutterBlockButtonHTML: data => `<button data-type="${data.type}" data-node-id="${data.nodeID}"><svg><use href="#iconTest"></use></svg></button>`,
};
const render = new Function(...Object.keys(dependencies), source + "\nreturn render;")(...Object.values(dependencies));
- const renderFull = new Function(...Object.keys(dependencies), fullSource + "\nreturn render;")(...Object.values(dependencies));
- window.siyuan = {languages: {fold: "Fold"}, config: {editor: {fontSize: 16, rtl: false}}};
+ const {render: renderFull, windowMouseMove, bindHover} = new Function(...Object.keys(dependencies),
+ fullSource + "\nreturn {render, windowMouseMove, bindHover};")(...Object.values(dependencies));
+ let mobile = false;
+ window.siyuan = {languages: {fold: "Fold", rowTip: "Row", addBelowAbove: "Add"}, layout: {}, blockPanels: [],
+ config: {editor: {fontSize: 16, rtl: false}}};
const style = document.createElement("style");
style.textContent = `body {margin:0; width:1000px; height:800px} .protyle-wysiwyg {margin:80px 180px;width:500px}
.li {position:relative;padding-left:34px} .protyle-action {position:absolute;left:0;top:0;width:24px;height:34px}
@@ -104,6 +122,117 @@ const cases = (source, fullSource) => {
check.ok(!render.call(gutter, protyle, root.querySelector('[data-node-id="p"]')).includes('data-type="NodeParagraph"'));
check.equal(render.call(gutter, protyle, root.querySelector(".protyle-action")),
render.call(gutter, protyle, root.querySelector('[data-node-id="p"]')));
+
+ // 使用实际样式与两条悬停入口,覆盖容器多子块及序标之间的连续移动。
+ style.textContent = css + `\n:root {--b3-font-size-editor:16px;--b3-font-family:Arial}
+ body {margin:0} .protyle {position:relative;width:1000px;height:700px}
+ .protyle-wysiwyg {padding:60px 180px;font-size:16px;line-height:1.625}
+ .mindmap-view {height:140px} .av__views {height:48px} .av__row {height:40px}
+ .av__body {height:160px} .iframe iframe {height:120px;width:240px}`;
+ const pane = document.createElement("div");
+ pane.className = "protyle";
+ document.body.append(pane);
+ pane.append(root, gutter.element);
+ Object.assign(protyle, {element: pane, contentElement: pane, options: {render: {gutter: true}},
+ selectElement: document.createElement("div"), gutter});
+ protyle.selectElement.className = "fn__none";
+ gutter.render = (...args) => renderFull.apply(gutter, args);
+ gutter.getNodeElement = (_owner, button) => root.querySelector(`[data-node-id="${button.dataset.nodeId}"]`);
+ const errors = [];
+ window.addEventListener("error", event => errors.push(event.message));
+ window.addEventListener("mousemove", windowMouseMove);
+ bindHover(protyle);
+ mobile = true;
+ bindHover(protyle);
+ const state = () => ({left: gutter.element.style.left, top: gutter.element.style.top,
+ ids: Array.from(gutter.element.querySelectorAll("button[data-node-id]")).map(button => button.dataset.nodeId)});
+ const hover = (target, x, y) => {
+ const rect = target.getBoundingClientRect();
+ x ??= rect.left + Math.min(12, rect.width / 2);
+ y ??= rect.top + Math.min(16, rect.height / 2);
+ target.dispatchEvent(new PointerEvent(mobile ? "pointerover" : "mouseover",
+ {bubbles: true, pointerType: "mouse", clientX: x, clientY: y}));
+ target.dispatchEvent(new MouseEvent("mousemove", {bubbles: true, clientX: x, clientY: y}));
+ check.deepEqual(errors, []);
+ return state();
+ };
+ const p = (id, text = id) => `<div data-node-id="${id}" data-type="NodeParagraph" class="p"><div contenteditable="true">${text}</div>${attr}</div>`;
+ const fixtures = [
+ ["NodeSuperBlock", "sb", p("child") + p("child2")],
+ ["NodeSuperBlock", "sb", p("child") + p("child2"), "col"],
+ ["NodeAttributeView", "av", '<div class="av__views">Database</div><div class="av__body"><div class="av__row" data-id="row"><div class="av__cell">Cell</div></div></div>'],
+ ["NodeBlockquote", "bq", p("child") + p("child2")],
+ ["NodeCallout", "callout", `<div class="callout-info"><div class="callout-title">Title</div></div><div class="callout-content">${p("child")}${p("child2")}</div>`],
+ ["NodeTable", "table", "<table><tbody><tr><td>Cell</td></tr></tbody></table>"],
+ ["NodeCodeBlock", "code-block", '<div class="hljs">Line<br>Line<br>Line</div>'],
+ ["NodeMindmap", "list", '<div class="mindmap-view">Mindmap</div>'],
+ ["NodeList", "list", '<div class="mindmap-view">Legacy mindmap</div>'],
+ ["NodeList", "list", `<div data-node-id="nested-item" data-type="NodeListItem" class="li"><div class="protyle-action">-</div>${p("child")}${attr}</div>`],
+ ["NodeIFrame", "iframe", '<div><iframe src="about:blank"></iframe></div>'],
+ ["NodeTabs", "tabs", '<div class="tabs-header">Tab</div><div data-node-id="tab" data-type="NodeTabItem" class="tab-item">' + p("child") + "</div>"],
+ ];
+ const containerTypes = new Set(fixtures.map(([type]) => type));
+ fixtures.push(...[
+ ["NodeParagraph", "p"], ["NodeHeading", "h1"], ["NodeMathBlock", "render-node"],
+ ["NodeHTMLBlock", "render-node"], ["NodeWidget", "iframe"], ["NodeVideo", "video"],
+ ["NodeAudio", "audio"], ["NodeThematicBreak", "hr"], ["NodeBlockQueryEmbed", "render-node"],
+ ["NodeCustomBlock", "protyle-custom"], ["NodeYamlFrontMatter", "code-block"],
+ ].map(([type, cls]) => [type, cls, '<div contenteditable="true">Content</div>']));
+ const movements = [];
+ for (const platform of [false, true]) {
+ mobile = platform;
+ for (const [type, cls, content, layout = "row"] of fixtures) {
+ for (const variant of ["u", "o", "t", "nested"]) {
+ const subtype = variant === "nested" ? "u" : variant;
+ const legacyMindmap = type === "NodeList" && content.includes("mindmap-view");
+ root.innerHTML = `<div data-node-id="list" data-type="NodeList" data-subtype="${subtype}" class="list">
+<div data-node-id="item" data-type="NodeListItem" data-subtype="${subtype}" class="li"><div class="protyle-action">1.</div>
+<div data-node-id="container" data-type="${type}" class="${cls}" ${type === "NodeSuperBlock" ? `data-sb-layout="${layout}"` : ""}
+${legacyMindmap ? 'custom-sy-list-mindmap="1"' : ""}>${content}${attr}</div>${p("after")}${attr}</div>${attr}</div>`;
+ if (variant === "nested") {
+ root.innerHTML = `<div data-node-id="outer-list" data-type="NodeList" class="list"><div data-node-id="outer-item" data-type="NodeListItem" class="li"><div class="protyle-action">-</div>${root.innerHTML}${attr}</div>${attr}</div>`;
+ }
+ gutter.element.innerHTML = "";
+ gutter.element.classList.add("fn__none");
+ const container = root.querySelector('[data-node-id="container"]');
+ const marker = root.querySelector('[data-node-id="item"] > .protyle-action');
+ const child = container.querySelector('[data-node-id="child"]');
+ const target = container.querySelector(".callout-info, .av__views, .tabs-header") || child || container;
+ // 脑图控制器会直接以脑图根块显示块标。
+ if (type === "NodeMindmap" || legacyMindmap) {
+ gutter.render(protyle, container, container);
+ } else {
+ hover(target);
+ }
+ const before = state();
+ check.ok(before.ids.length > 0, `${type}: missing block gutter`);
+ if (type !== "NodeList" || legacyMindmap) {
+ const expectedID = containerTypes.has(type) ? "container" : variant === "nested" ? "outer-item" : "item";
+ check.ok(before.ids.includes(expectedID), `${type}: missing block gutter`);
+ }
+ const after = hover(marker);
+ if (JSON.stringify(after) !== JSON.stringify(before)) {
+ movements.push({type, subtype, mobile, before, after});
+ }
+ if (type === "NodeAttributeView") {
+ // 从隐藏状态先经过序标进入数据库,位置也应一致。
+ gutter.element.innerHTML = "";
+ gutter.element.classList.add("fn__none");
+ check.deepEqual(hover(marker), before, "database marker uses the same vertical offset on first entry");
+ check.deepEqual(hover(target), before, "entering the database from its marker does not move the gutter");
+ const row = container.querySelector(".av__row");
+ hover(row.firstElementChild);
+ check.equal(gutter.element.querySelector("button").dataset.rowId, "row");
+ check.equal(parseFloat(gutter.element.style.top), row.getBoundingClientRect().top,
+ "database row actions stay beside the hovered row");
+ check.deepEqual(hover(marker), before, "returning to the marker leaves database row actions");
+ }
+ hover(root.querySelector('[data-node-id="after"]'));
+ check.ok(!state().ids.includes("container"), `${type}: unrelated content must replace the retained gutter`);
+ }
+ }
+ }
+ check.deepEqual(movements, [], "moving to the marker must preserve gutters");
return "List container gutters passed";
};
@@ -114,8 +243,10 @@ if (process.versions.electron && process.type === "browser") {
await app.whenReady();
const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false}});
await win.loadURL("data:text/html,<html><body></body></html>");
+ const css = ["protyle/_wysiwyg.scss", "protyle/_protyle.scss", "util/_function.scss"].map(file =>
+ require("sass").compile(path.join(__dirname, "../src/assets/scss", file), {quietDeps: true}).css).join("\n");
const result = await win.webContents.executeJavaScript(`(() => {
- try { return {message: (${cases.toString()})(${JSON.stringify(sources())}, ${JSON.stringify(sources(true))})}; }
+ try { return {message: (${cases.toString()})(${JSON.stringify(sources())}, ${JSON.stringify(sources(true))}, ${JSON.stringify(css)})}; }
catch (error) { return {error: error.stack}; }
})()`);
assert.ok(!result.error, result.error);