Skip to content

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

:bug: Preserve nested block gutters in list items https://github.com/siyuan-note/siyuan/issues/20500

Danieldab9716c6686
diff --git a/app/src/protyle/gutter/container.test.ts b/app/src/protyle/gutter/container.test.ts
index ebd5809bf7..6b89e4dc46 100644
--- a/app/src/protyle/gutter/container.test.ts
+++ b/app/src/protyle/gutter/container.test.ts
@@ -1,6 +1,18 @@
import {describe, it} from "node:test";
import * as assert from "node:assert/strict";
-import {isContainerGutterBridge} from "./container";
+
+const buildGlobals = ["SIYUAN_VERSION", "NODE_ENV"].map(name => ({
+ name, descriptor: Object.getOwnPropertyDescriptor(globalThis, name),
+}));
+buildGlobals.forEach(({name}) => Object.defineProperty(globalThis, name, {value: "test", configurable: true}));
+const {isContainerGutterBridge} = require("./container") as typeof import("./container");
+buildGlobals.forEach(({name, descriptor}) => {
+ if (descriptor) {
+ Object.defineProperty(globalThis, name, descriptor);
+ } else {
+ Reflect.deleteProperty(globalThis, name);
+ }
+});
const setup = (type = "NodeBlockquote") => {
const block = {
diff --git a/app/src/protyle/gutter/container.ts b/app/src/protyle/gutter/container.ts
index d3ff01740c..c00f3e51de 100644
--- a/app/src/protyle/gutter/container.ts
+++ b/app/src/protyle/gutter/container.ts
@@ -1,9 +1,14 @@
+import {Constants} from "../../constants";
+
// 列表项的首个容器保留独立块标,段落仍沿用列表项的合并操作。
export const getListItemGutterContainer = (element: Element) => {
const item = element.closest('[data-type="NodeListItem"]');
const first = item?.querySelector(":scope > [data-node-id]");
- if (first && ["NodeTable", "NodeBlockquote", "NodeCallout", "NodeSuperBlock", "NodeTabs"]
- .includes(first.getAttribute("data-type")) && (element === item || first.contains(element) ||
+ const type = first?.getAttribute("data-type");
+ if (first && (["NodeTable", "NodeBlockquote", "NodeCallout", "NodeSuperBlock", "NodeTabs",
+ "NodeMindmap", "NodeAttributeView", "NodeCodeBlock", "NodeIFrame"].includes(type) ||
+ type === "NodeList" && first.getAttribute(Constants.CUSTOM_SY_LIST_MINDMAP) === "1") &&
+ (element === item || first.contains(element) ||
element.parentElement === item && element.classList.contains("protyle-action"))) {
return first;
}
diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.ts
index 92cc1bb361..fd4b6331e6 100644
--- a/app/src/protyle/gutter/index.ts
+++ b/app/src/protyle/gutter/index.ts
@@ -3967,12 +3967,12 @@ data-type="fold"${viewOccurrenceID ? ` data-view-occurrence-id="${encodeURICompo
);
}
// 脑图中的原始列表项已隐藏,使用可见面板定位列表块标。
- let rect = (mindmapElement || element).getBoundingClientRect();
+ let rect = (listItemContainer || mindmapElement || element).getBoundingClientRect();
let marginHeight = 0;
const autoListDirection = getAutoListDirection(element);
const isRTL = autoListDirection ? autoListDirection === "rtl" :
window.siyuan.config.editor.rtl || getComputedStyle(element).direction === "rtl";
- if (mindmapElement) {
+ if (mindmapElement && !listItemContainer) {
space = 0;
} else if (listItem && !isRTL) {
rect = listItem.firstElementChild.getBoundingClientRect();
diff --git a/app/tests/listContainerGutter.test.js b/app/tests/listContainerGutter.test.js
index 5ccd54098a..bfc0e0b70a 100644
--- a/app/tests/listContainerGutter.test.js
+++ b/app/tests/listContainerGutter.test.js
@@ -3,19 +3,21 @@ const {readFileSync, mkdtempSync, rmSync} = require("node:fs");
const path = require("node:path");
const os = require("node:os");
-const sources = () => {
+const sources = (full = false) => {
const ts = require("typescript");
const source = ts.createSourceFile("index.ts", readFileSync(path.join(__dirname,
"../src/protyle/gutter/index.ts"), "utf8"), ts.ScriptTarget.Latest, true);
const gutter = source.statements.find(node => ts.isClassDeclaration(node) && node.name.text === "Gutter");
const render = gutter.members.find(node => node.name?.getText(source) === "render");
- const body = render.body.getText(source).split("const shouldRenderInsert")[0] + "return html; }";
- const helpers = ["protyle/gutter/container.ts", "protyle/wysiwyg/getBlock.ts"].map(file => {
+ 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 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"].includes(declaration.name.getText(source))))
+ "getSbChildBlockCount", "getParentBlock", "getGutterMarginHeight", "getFixedGutterPosition",
+ "getBacklinkGutterContentTop", "getListGutterAnchorLeft"].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}`, {
@@ -23,40 +25,59 @@ const sources = () => {
}).outputText;
};
-const cases = source => {
+const cases = (source, fullSource) => {
const check = require("node:assert/strict");
const noop = () => false;
const dependencies = {
- Constants: {}, hideElements: noop, getCrossBlockTextRange: noop,
+ 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,
+ 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>`,
};
const render = new Function(...Object.keys(dependencies), source + "\nreturn render;")(...Object.values(dependencies));
- window.siyuan = {languages: {fold: "Fold"}};
+ 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 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}
+ .mindmap-view {margin:12px;height:160px} .protyle-gutters {position:fixed;display:flex}
+ .protyle-gutters > button {box-sizing:border-box;width:24px;height:24px;padding:0}`;
+ document.head.append(style);
const root = document.createElement("div");
root.className = "protyle-wysiwyg";
document.body.append(root);
const gutter = {element: document.createElement("div"), gutterTip: "${x}"};
- const protyle = {element: root, wysiwyg: {element: root}, options: {}};
+ gutter.element.className = "protyle-gutters";
+ document.body.append(gutter.element);
+ const protyle = {element: root, contentElement: root, wysiwyg: {element: root}, options: {}};
const attr = '<div class="protyle-attr"></div>';
for (const extra of ["", '<div data-node-id="second" data-type="NodeParagraph">Second</div>']) {
for (const [type, cls] of [["NodeTable", "table"], ["NodeBlockquote", "bq"], ["NodeCallout", "callout"],
- ["NodeSuperBlock", "sb"], ["NodeTabs", "tabs"]]) {
+ ["NodeSuperBlock", "sb"], ["NodeTabs", "tabs"], ["NodeMindmap", "list"],
+ ["NodeList", "list"], ["NodeAttributeView", "av"], ["NodeCodeBlock", "code-block"],
+ ["NodeIFrame", "iframe"]]) {
const child = '<div data-node-id="child" data-type="NodeParagraph">Child</div>';
const content = type === "NodeCallout" ? `<div class="callout-info"><div class="callout-title">Title</div></div><div class="callout-content">${child}</div>` : child;
root.innerHTML = `<div data-node-id="list" data-type="NodeList" class="list">
<div data-node-id="item" data-type="NodeListItem" class="li"><div class="protyle-action"></div>
<div data-node-id="container" data-type="${type}" class="${cls}">${content}${attr}</div>${extra}${attr}</div>${attr}</div>`;
+ if (type === "NodeMindmap" || type === "NodeList") {
+ const container = root.querySelector('[data-node-id="container"]');
+ container.setAttribute("custom-sy-list-mindmap", "1");
+ container.insertAdjacentHTML("afterbegin", '<div class="mindmap-view"></div>');
+ }
for (const id of ["container", "child", "item"]) {
const element = root.querySelector(`[data-node-id="${id}"]`);
const html = render.call(gutter, protyle, element, element);
- check.ok(html?.includes(`data-type="${type}"`), `${type}/${id}/${!!extra}: ${html}`);
+ check.ok(html?.includes(`data-type="${type}" data-node-id="container"`), `${type}/${id}/${!!extra}: ${html}`);
check.ok(html?.includes('data-type="NodeListItem"'), `${type}/${id}/${!!extra}: ${html}`);
}
for (const subtype of ["u", "o", "t"]) {
@@ -66,6 +87,16 @@ const cases = source => {
const marker = root.querySelector(".protyle-action");
check.equal(render.call(gutter, protyle, marker, marker),
render.call(gutter, protyle, container, container), `${type}/${subtype}/${!!extra}: marker gutters`);
+ const positions = [container, marker, root.querySelector('[data-node-id="item"]')].map(element => {
+ renderFull.call(gutter, protyle, element, element);
+ return [gutter.element.style.left, gutter.element.style.top];
+ });
+ check.deepEqual(positions[0], positions[1], `${type}/${subtype}/${!!extra}: marker position`);
+ check.deepEqual(positions[0], positions[2], `${type}/${subtype}/${!!extra}: item position`);
+ check.ok(parseFloat(positions[0][0]) < marker.getBoundingClientRect().left,
+ `${type}: gutter must stay left of the list marker`);
+ check.ok(gutter.element.getBoundingClientRect().right <= marker.getBoundingClientRect().left,
+ `${type}: gutter must not overlap the list marker`);
}
}
}
@@ -84,7 +115,7 @@ if (process.versions.electron && process.type === "browser") {
const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false}});
await win.loadURL("data:text/html,<html><body></body></html>");
const result = await win.webContents.executeJavaScript(`(() => {
- try { return {message: (${cases.toString()})(${JSON.stringify(sources())})}; }
+ try { return {message: (${cases.toString()})(${JSON.stringify(sources())}, ${JSON.stringify(sources(true))})}; }
catch (error) { return {error: error.stack}; }
})()`);
assert.ok(!result.error, result.error);