Skip to content

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

:bug: Preserve first container gutters in list items https://github.com/siyuan-note/siyuan/issues/20404

Daniel7f911d3212df
diff --git a/app/src/protyle/gutter/container.ts b/app/src/protyle/gutter/container.ts
index 396e4a6020..906cd7f9cb 100644
--- a/app/src/protyle/gutter/container.ts
+++ b/app/src/protyle/gutter/container.ts
@@ -1,3 +1,13 @@
+// 列表项的首个容器保留独立块标,段落仍沿用列表项的合并操作。
+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))) {
+ return first;
+ }
+};
+
// 鼠标经过祖先容器留白移向子块块标时,保留当前块标及其选区。
export const isContainerGutterBridge = (gutter: HTMLElement, container: HTMLElement, target: HTMLElement,
x: number, y: number, getBlock: (button: HTMLElement) => Element) => {
diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.ts
index deebf8d100..b777bf2599 100644
--- a/app/src/protyle/gutter/index.ts
+++ b/app/src/protyle/gutter/index.ts
@@ -142,6 +142,7 @@ import {CALLOUT_PRESETS, updateCalloutType, updateCustomCalloutType} from "../wy
import {setTabsPosition, toggleTabsTasks, unwrapTabs} from "../wysiwyg/tabs";
import {getTaskStatusItems} from "../wysiwyg/taskStatusDialog";
import {hasTabsTasks} from "../render/tabsRender";
+import {getListItemGutterContainer} from "./container";
const restoreGutterRange = (protyle: IProtyle) => {
// 多选块菜单只操作选中的块,不恢复旧文本光标,避免编辑器滚动到光标位置。
@@ -3702,6 +3703,10 @@ export class Gutter {
}
let html = "";
let nodeElement = selectedElement || element;
+ const listItemContainer = isMultiSelect ? undefined : getListItemGutterContainer(nodeElement);
+ if (listItemContainer && nodeElement === listItemContainer.parentElement) {
+ nodeElement = listItemContainer;
+ }
const mindmapElement = (nodeElement.getAttribute("data-type") === "NodeMindmap" ||
nodeElement.getAttribute("data-type") === "NodeList" &&
nodeElement.getAttribute(Constants.CUSTOM_SY_LIST_MINDMAP) === "1") ?
@@ -3751,7 +3756,7 @@ export class Gutter {
}
if (index === 0) {
// 不单独显示,要不然在块的间隔中,gutter 会跳来跳去的
- if (!isMultiSelect && !mindmapElement &&
+ if (!isMultiSelect && !mindmapElement && !listItemContainer &&
["NodeBlockquote", "NodeList", "NodeCallout", "NodeSuperBlock"].includes(type)) {
if (target && type === "NodeCallout") {
// Callout 标题需显示
@@ -3767,6 +3772,9 @@ export class Gutter {
}
let topElement = selectedElement || (tabsHeader || mindmapElement ? nodeElement : getTopAloneElement(nodeElement));
+ if (listItemContainer && topElement.contains(listItemContainer)) {
+ topElement = nodeElement === listItemContainer.parentElement ? nodeElement : listItemContainer;
+ }
if (embedContext && !embedContext.boundaryElement.contains(topElement)) {
// 单独查询列表项时,渲染器生成的无 ID 列表包装节点不属于可操作边界。
topElement = embedContext.targetElement || nodeElement;
@@ -3789,7 +3797,8 @@ export class Gutter {
listItem = undefined;
}
// 标题(除列表下的)、提示下的块必须显示
- if (topElement !== nodeElement && type !== "NodeHeading" && !hasClosestByClassName(nodeElement, "callout")) {
+ if (topElement !== nodeElement && type !== "NodeHeading" &&
+ (topElement === listItemContainer || !hasClosestByClassName(nodeElement, "callout"))) {
while (nodeElement !== topElement) {
nodeElement = nodeElement.parentElement;
// > > > > 1 left 位置
@@ -3803,7 +3812,7 @@ export class Gutter {
}
}
// - > # 1 \n > 2
- if (type === "NodeListItem" && index > 0) {
+ if (type === "NodeListItem" && index > 0 && nodeElement !== listItemContainer?.parentElement) {
// 列表项内的块不显示块标
html = "";
}
@@ -3848,7 +3857,8 @@ data-type="fold"${viewOccurrenceID ? ` data-view-occurrence-id="${encodeURICompo
if (type === "NodeListItem" || type === "NodeList") {
listItem = nodeElement;
if (type === "NodeListItem" && nodeElement.childElementCount > 3) {
- html = buttonHTML + foldHTML;
+ html = nodeElement === listItemContainer?.parentElement ?
+ html + foldHTML : buttonHTML + foldHTML;
}
}
if (type === "NodeHeading") {
diff --git a/app/tests/listContainerGutter.test.js b/app/tests/listContainerGutter.test.js
new file mode 100644
index 0000000000..149558f683
--- /dev/null
+++ b/app/tests/listContainerGutter.test.js
@@ -0,0 +1,98 @@
+const assert = require("node:assert/strict");
+const {readFileSync, mkdtempSync, rmSync} = require("node:fs");
+const path = require("node:path");
+const os = require("node:os");
+
+const sources = () => {
+ 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 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))))
+ .map(node => node.getText(source)).join("\n");
+ }).join("\n").replace(/export const /g, "const ");
+ return ts.transpileModule(helpers + `\nfunction render(protyle, element, target) ${body}`, {
+ compilerOptions: {target: ts.ScriptTarget.ES2021},
+ }).outputText;
+};
+
+const cases = source => {
+ const check = require("node:assert/strict");
+ const noop = () => false;
+ const dependencies = {
+ Constants: {}, 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),
+ getBlockTypeName: type => type, getIconByType: () => "iconTest",
+ genGutterBlockButtonHTML: data => `<button data-type="${data.type}"></button>`,
+ };
+ const render = new Function(...Object.keys(dependencies), source + "\nreturn render;")(...Object.values(dependencies));
+ window.siyuan = {languages: {fold: "Fold"}};
+ 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: {}};
+ 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"]]) {
+ 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>`;
+ 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="NodeListItem"'), `${type}/${id}/${!!extra}: ${html}`);
+ }
+ }
+ }
+ 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="p" data-type="NodeParagraph">Text</div>${attr}</div>${attr}</div>`;
+ check.ok(!render.call(gutter, protyle, root.querySelector('[data-node-id="p"]')).includes('data-type="NodeParagraph"'));
+ return "List container gutters passed";
+};
+
+if (process.versions.electron && process.type === "browser") {
+ (async () => {
+ const {app, BrowserWindow} = require("electron");
+ app.setPath("userData", process.argv[2]);
+ await app.whenReady();
+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false}});
+ await win.loadURL("data:text/html,<html><body></body></html>");
+ console.log(await win.webContents.executeJavaScript(`(${cases.toString()})(${JSON.stringify(sources())})`));
+ win.destroy();
+ app.exit(0);
+ })().catch(error => { console.error(error); require("electron").app.exit(1); });
+} else {
+ require("node:test").test("first list containers retain both container and list item gutters", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
+ timeout: 30000,
+ }, async () => {
+ const profile = mkdtempSync(path.join(os.tmpdir(), "siyuan-list-gutter-"));
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ try {
+ const {stdout} = await require("node:util").promisify(require("node:child_process").execFile)(
+ require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 25000});
+ assert.match(stdout, /List container gutters passed/);
+ } finally {
+ assert.equal(path.dirname(path.resolve(profile)), path.resolve(os.tmpdir()));
+ assert.ok(path.basename(profile).startsWith("siyuan-list-gutter-"));
+ rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});
+ }
+ });
+}