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: Correct tab block deletion boundaries and list outdent
Daniel2e822672a89d
diff --git a/app/src/protyle/wysiwyg/list.ts b/app/src/protyle/wysiwyg/list.tsindex 4cb0655fcb..1322fed5f4 100644--- a/app/src/protyle/wysiwyg/list.ts+++ b/app/src/protyle/wysiwyg/list.ts@@ -1128,7 +1128,8 @@ export const listOutdent = async (protyle: IProtyle, liItemElements: Element[],});const movedListItemElements = [...liItemElements] as HTMLElement[];if (parentLiItemElement.classList.contains("protyle-wysiwyg") || parentLiItemElement.classList.contains("sb") ||- parentLiItemElement.classList.contains("bq") || parentLiItemElement.classList.contains("callout")) {+ parentLiItemElement.classList.contains("bq") || parentLiItemElement.classList.contains("callout") ||+ parentLiItemElement.classList.contains("tab-item")) {// 顶层列表const topDoOperations: IOperation[] = [];const topUndoOperations: IOperation[] = [];diff --git a/app/src/protyle/wysiwyg/listOutdent.test.ts b/app/src/protyle/wysiwyg/listOutdent.test.tsnew file mode 100644index 0000000000..3cddad5c28--- /dev/null+++ b/app/src/protyle/wysiwyg/listOutdent.test.ts@@ -0,0 +1,160 @@+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 compiled = transpileModule(readFileSync("src/protyle/wysiwyg/list.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+}).outputText;++class TestElement {+ parentElement: TestElement;+ children: TestElement[] = [];+ private attrs = new Map<string, string>();+ classList = {contains: (name: string) => this.attrs.get("class")?.split(" ").includes(name) || false};++ constructor(name: string, id?: string) {+ this.attrs.set("class", name);+ if (id) {+ this.attrs.set("data-node-id", id);+ }+ }++ append(...children: TestElement[]) {+ children.forEach(child => {+ child.remove();+ child.parentElement = this;+ this.children.push(child);+ });+ return this;+ }++ remove() {+ if (this.parentElement) {+ this.parentElement.children.splice(this.parentElement.children.indexOf(this), 1);+ this.parentElement = undefined;+ }+ }++ after(element: TestElement) {+ element.remove();+ element.parentElement = this.parentElement;+ this.parentElement.children.splice(this.parentElement.children.indexOf(this) + 1, 0, element);+ }++ get previousElementSibling(): TestElement {+ return this.parentElement?.children[this.parentElement.children.indexOf(this) - 1];+ }++ get nextElementSibling(): TestElement {+ return this.parentElement?.children[this.parentElement.children.indexOf(this) + 1];+ }++ get lastElementChild() {+ return this.children[this.children.length - 1];+ }++ get childElementCount() {+ return this.children.length;+ }++ get isConnected(): boolean {+ return this.classList.contains("protyle-wysiwyg") || !!this.parentElement?.isConnected;+ }++ get outerHTML(): string {+ const attrs = Array.from(this.attrs).map(([name, value]) => ` ${name}="${value}"`).join("");+ return `<div${attrs}>${this.children.map(child => child.outerHTML).join("")}</div>`;+ }++ getAttribute(name: string) {+ return this.attrs.get(name) || null;+ }++ removeAttribute(name: string) {+ this.attrs.delete(name);+ }++ contains(element: TestElement): boolean {+ return element === this || this.children.some(child => child.contains(element));+ }+}++const fixture = (single: boolean, containerClass = "tab-item") => {+ const attr = () => new TestElement("protyle-attr");+ const paragraph = new TestElement("p", "empty-paragraph").append(new TestElement("editable"), attr());+ const item = new TestElement("li", "empty-item").append(new TestElement("protyle-action"), paragraph, attr());+ const previousItem = new TestElement("li", "previous-item");+ const list = new TestElement("list", "list").append(...(single ? [] : [previousItem]), item, attr());+ const before = new TestElement("p", "before");+ const content = new TestElement("tab-item-content").append(before, list);+ const title = new TestElement("tab-item-info");+ const container = new TestElement(containerClass, "container").append(title, content, attr());+ const otherTab = new TestElement("tab-item", "other-tab");+ const tabs = new TestElement("tabs", "tabs").append(container, otherTab, attr());+ new TestElement("protyle-wysiwyg").append(tabs);+ const operations: {doOperations: IOperation[], undoOperations: IOperation[]}[] = [];+ let focused: TestElement;+ const exports: any = {};+ const dependencies = {+ getParentBlock: (element: TestElement) => element.parentElement === content ? container : element.parentElement,+ getPreviousBlockSibling: (element: TestElement) => element.previousElementSibling,+ getEmbedChildOperationContext: (): void => undefined,+ activateTrackedRangeInsertion: (): void => undefined,+ moveToPrevious: (): void => undefined,+ isBlockElement: (element: TestElement) => !!element.getAttribute("data-node-id"),+ transaction: (_protyle: IProtyle, doOperations: IOperation[], undoOperations: IOperation[]) =>+ operations.push({doOperations, undoOperations}),+ focusByWbr: (element: TestElement) => focused = element,+ };+ runInNewContext(compiled, {+ exports,+ require: () => dependencies,+ window: {siyuan: {config: {editor: {listLogicalOutdent: true}}}},+ document: {createElement: (name: string) => new TestElement(name)},+ });+ const range = {+ startContainer: paragraph.children[0],+ collapse: (): void => undefined,+ insertNode: (element: TestElement) => paragraph.children[0].append(element),+ };+ const protyle = {block: {id: "doc", parentID: "doc"}};+ return {+ paragraph, item, list, before, content, title, container, tabs, otherTab, operations,+ run: () => exports.listOutdent(protyle, [item], range),+ focused: () => focused,+ };+};++for (const single of [false, true]) {+ test(`页签内${single ? "唯一" : "末尾"}空列表项退出为同一页签的段落,并保留撤销父级`, async () => {+ const f = fixture(single);+ await f.run();+ assert.equal(f.paragraph.parentElement, f.content);+ assert.equal(f.content.lastElementChild, f.paragraph);+ assert.equal(f.item.parentElement, undefined);+ assert.equal(f.title.parentElement, f.container);+ assert.equal(f.otherTab.parentElement, f.tabs);+ assert.equal(f.tabs.childElementCount, 3);+ assert.equal(f.focused(), f.container);+ assert.equal(f.operations.length, 1);+ const {doOperations, undoOperations} = f.operations[0];+ assert.equal(doOperations[0].action, "move");+ assert.equal(doOperations[0].id, "empty-paragraph");+ assert.equal(doOperations[0].parentID, "container");+ assert.equal(doOperations[0].previousID, "list");+ assert.equal(undoOperations.find(op => op.action === "move").parentID, "empty-item");+ if (single) {+ assert.equal(f.list.parentElement, undefined);+ const restore = undoOperations.find(op => op.action === "insert");+ assert.equal(restore.id, "list");+ assert.equal(restore.parentID, "container");+ assert.equal(restore.previousID, "before");+ } else {+ assert.equal(f.list.parentElement, f.content);+ assert.equal(doOperations[1].action, "update");+ assert.equal(doOperations[1].id, "list");+ }+ });+}diff --git a/app/src/protyle/wysiwyg/tabsBoundary.test.ts b/app/src/protyle/wysiwyg/tabsBoundary.test.tsnew file mode 100644index 0000000000..67135b6f5a--- /dev/null+++ b/app/src/protyle/wysiwyg/tabsBoundary.test.ts@@ -0,0 +1,79 @@+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 compiled = transpileModule(readFileSync("src/protyle/wysiwyg/tabsBoundary.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+}).outputText;++const fixture = (sideIDs: string[], text = "", media = false) => {+ const content = {};+ const block = (id: string, parentElement: unknown) => ({+ parentElement,+ hasAttribute: (name: string) => name === "data-node-id",+ getAttribute: (name: string) => name === "data-node-id" ? id : null,+ });+ const list = block("list", content);+ const item = block("item", list);+ const paragraph = block("paragraph", item);+ const editable = {+ nodeType: 1,+ parentElement: paragraph,+ closest: (selector: string) => selector === ".tab-item-content" ? content : null,+ hasAttribute: () => false,+ };+ const fragment = {+ innerHTML: "",+ textContent: text,+ append: (): void => undefined,+ querySelectorAll: (selector: string) => selector === "[data-node-id]" ?+ sideIDs.map(id => block(id, null)) : [],+ querySelector: () => media ? {} : null,+ };+ const directions: string[] = [];+ const exports: any = {};+ runInNewContext(compiled, {+ exports,+ require: () => ({visibleTabsSelectionHTML: (html: string) => html}),+ Node: {ELEMENT_NODE: 1},+ document: {+ createElement: () => fragment,+ createRange: () => ({+ selectNodeContents: (): void => undefined,+ setEnd: () => directions.push("backward"),+ setStart: () => directions.push("forward"),+ cloneContents: () => fragment,+ }),+ },+ });+ const range = {collapsed: true, startContainer: editable, endContainer: editable, startOffset: 0, endOffset: 0};+ return {range, editable, directions, boundary: (backward: boolean) => exports.isTabTextBoundary(range, backward)};+};++for (const backward of [true, false]) {+ test(`${backward ? "退格" : "删除"}允许处理页签内的相邻空段落和空列表项`, () => {+ for (const siblingID of ["empty-paragraph", "empty-item", "empty-list"]) {+ const f = fixture(["list", "item", "paragraph", siblingID]);+ assert.equal(f.boundary(backward), false);+ assert.deepEqual(f.directions, [backward ? "backward" : "forward"]);+ }+ });++ test(`${backward ? "退格" : "删除"}仍保护仅包含光标祖先的页签正文边界`, () => {+ assert.equal(fixture(["list", "item", "paragraph"]).boundary(backward), true);+ assert.equal(fixture(["list", "item", "paragraph"], "\u200b").boundary(backward), true);+ assert.equal(fixture(["list", "item", "paragraph"], "text").boundary(backward), false);+ assert.equal(fixture(["list", "item", "paragraph"], "", true).boundary(backward), false);+ });+}++test("非折叠选区和页签外的正文不触发页签边界保护", () => {+ const selection = fixture([]);+ selection.range.collapsed = false;+ assert.equal(selection.boundary(true), false);+ const outside = fixture([]);+ outside.editable.closest = () => null;+ assert.equal(outside.boundary(true), false);+});diff --git a/app/src/protyle/wysiwyg/tabsBoundary.ts b/app/src/protyle/wysiwyg/tabsBoundary.tsindex 7031384e3b..5b57bb2c77 100644--- a/app/src/protyle/wysiwyg/tabsBoundary.ts+++ b/app/src/protyle/wysiwyg/tabsBoundary.ts@@ -24,6 +24,17 @@ export const isTabTextBoundary = (range: Range, backward: boolean) => {fragment.append(side.cloneContents());fragment.innerHTML = visibleTabsSelectionHTML(fragment.innerHTML);fragment.querySelectorAll(".protyle-attr, .tab-item-info, .protyle-action").forEach(item => item.remove());+ // 空块仍占据正文位置,只有光标所在的祖先块不构成可删除的相邻内容。+ const ancestorIDs = new Set<string>();+ for (let current = element; current && current !== content; current = current.parentElement) {+ if (current.hasAttribute("data-node-id")) {+ ancestorIDs.add(current.getAttribute("data-node-id"));+ }+ }+ if (Array.from(fragment.querySelectorAll("[data-node-id]")).some(item =>+ !ancestorIDs.has(item.getAttribute("data-node-id")))) {+ return false;+ }return fragment.textContent.replace(/\u200b/g, "") === "" &&!fragment.querySelector("img, video, audio, iframe, .render-node, .av, .hr");};