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: Preserve inline boundary ownership during input and line breaks https://github.com/siyuan-note/siyuan/issues/20052
Danieleabe43aec7a9
diff --git a/app/src/protyle/util/inlineElementBoundary.dom.test.ts b/app/src/protyle/util/inlineElementBoundary.dom.test.tsnew file mode 100644index 0000000000..68cd29b177--- /dev/null+++ b/app/src/protyle/util/inlineElementBoundary.dom.test.ts@@ -0,0 +1,231 @@+import * as assert from "node:assert/strict";+import {execFile} from "node:child_process";+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";+import {tmpdir} from "node:os";+import * as path from "node:path";+import {test} from "node:test";+import {promisify} from "node:util";+import {createSourceFile, isVariableStatement, ModuleKind, ScriptTarget, transpileModule} from "typescript";++const browserCases = async (sources: Record<string, string>, entrySource: string, selectionSource: string,+ siblingSource: string) => {+ const check: typeof assert = require("node:assert/strict");+ const {ipcRenderer} = require("electron");+ const modules: Record<string, {exports: any}> = {};+ const load = (name: string) => {+ if (modules[name]) {+ return modules[name].exports;+ }+ const module = {exports: {}};+ modules[name] = module;+ new Function("require", "module", "exports", sources[name])((dependency: string) => {+ const parts = name.split("/");+ parts.pop();+ dependency.split("/").forEach(part => {+ if (part === "..") {+ parts.pop();+ } else if (part !== ".") {+ parts.push(part);+ }+ });+ return load(parts.join("/"));+ }, module, module.exports);+ return module.exports;+ };+ const marker: typeof import("./inlineElementMarker") = load("util/inlineElementMarker");+ const boundary: typeof import("./inlineElementBoundary") = load("util/inlineElementBoundary");+ const Constants = {ZWSP: "\u200b", WORD_JOINER: "\u2060", ATTRIBUTE_EDITING: "data-editing"};+ const siblings = new Function(siblingSource + "return {hasPreviousSibling, hasNextSibling};")();+ const focusByRange = (range: Range) => {+ getSelection().removeAllRanges();+ getSelection().addRange(range);+ };+ const selectionDeps = {Constants, ...marker, ...siblings, focusByRange,+ selectIsEditor: (element: Element, range: Range) => element.contains(range.startContainer)};+ const selection = new Function(...Object.keys(selectionDeps), selectionSource ++ "return {getSelectionOffset, focusByWbr};")(...Object.values(selectionDeps));+ const lute = boundary.protectLuteInlineElementBoundaries(Lute.New());+ lute.SetTextMark(true);+ lute.SetTag(true);+ lute.SetKramdownIAL(true);+ lute.SetProtyleWYSIWYG(true);+ lute.SetSpin(true);+ const paragraph = (html: string) => `<div data-type="NodeParagraph" class="p" data-node-id="${Lute.NewNodeID()}">` ++ `<div contenteditable="true">${html}</div><div class="protyle-attr" contenteditable="false"></div></div>`;+ const dependencies = {+ Constants, ...marker, ...boundary, ...selection, ...siblings,+ BLOCK_SELECTION_CLASS: "protyle-wysiwyg--select", getBlockSelectionModeElement: (): undefined => undefined,+ hasClosestByClassName: (element: Element, name: string) => element.closest("." + name),+ hasClosestByAttribute: (node: Node, name: string, value: string) =>+ (node.nodeType === 1 ? node as Element : node.parentElement).closest(`[${name}~="${value}"]`),+ getEmbedChildOperationContext: (): undefined => undefined, isNotEditBlock: () => false,+ getContenteditableElement: (element: Element) => element.querySelector('[contenteditable="true"]'),+ canEnterCodeBlock: () => false, getParentBlock: (element: Element) => element.parentElement,+ getPreviousBlockSibling: (element: Element) => element.previousElementSibling,+ getUndoFocusContext: () => ({}), activateTrackedRangeInsertion() {},+ genEmptyElement: (_plain: boolean, withWbr: boolean) => {+ const element = document.createElement("div");+ element.innerHTML = paragraph(withWbr ? "<wbr>" : "");+ return element.firstElementChild;+ },+ genEmptyBlock: (_plain: boolean, withWbr: boolean) => paragraph(withWbr ? "<wbr>" : ""),+ isEmptyListItemBlock: () => false, shouldCreateListItemChildOnEnter: () => false,+ getFocusedParentOrderedList: async () => {+ await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));+ return document.createElement("div");+ },+ getFocusedOrderedListInsertOperations: (): {doOperations: IOperation[], undoOperations: IOperation[]} =>+ ({doOperations: [], undoOperations: []}),+ updateListOrder() {}, blockRender() {}, processRender() {}, updateTransaction() {},+ hasCodeBlockFence: () => false, transaction() {}, mathRender() {}, scrollCenter() {},+ };+ const {enter, softEnter} = new Function(...Object.keys(dependencies), entrySource ++ "return {enter, softEnter};")(...Object.values(dependencies));+ Object.assign(window, {siyuan: {config: {editor: {markdown: {}}}}});++ for (const type of ["code", "kbd", "tag"]) {+ for (const action of ["text", "enter", "soft-enter"]) {+ for (const location of ["text", "parent", "wbr", "selected"]) {+ if (action === "soft-enter" && location === "selected") {+ continue;+ }+ const editor = document.createElement("div");+ editor.className = "protyle-wysiwyg";+ editor.contentEditable = "true";+ editor.innerHTML = paragraph(`<span data-type="${type}">one</span>`);+ document.body.append(editor);+ const block = editor.firstElementChild;+ const content = block.firstElementChild;+ marker.normalizeSemanticInlineElements(content);+ const inline = content.querySelector("span");+ const range = document.createRange();+ if (location === "selected") {+ range.selectNode(inline);+ } else {+ if (location === "wbr") {+ inline.before(document.createElement("wbr"));+ }+ if (location === "text") {+ range.setStart(content.firstChild, 1);+ } else {+ range.setStartBefore(inline);+ }+ range.collapse(true);+ }+ editor.focus();+ focusByRange(range);+ if (action === "text") {+ editor.addEventListener("beforeinput", () =>+ boundary.prepareInlineElementBoundaryMutation(getSelection().getRangeAt(0)));+ editor.addEventListener("input", () => marker.normalizeSemanticInlineElements(editor));+ await ipcRenderer.invoke("type-text", "x");+ check.equal(marker.getTextWithoutSemanticMarkers(content).replace(/\u200b/g, ""),+ location === "selected" ? "x" : "xone", `${type}/${action}/${location}`);+ } else if (action === "enter") {+ await enter(block, range, {wysiwyg: {element: editor}, lute});+ const firstContent = editor.querySelector('[contenteditable="true"]');+ check.equal(firstContent.textContent, "", `${type}/${action}/${location}`);+ check.equal(marker.getTextWithoutSemanticMarkers(editor).replace(/\u200b/g, ""),+ location === "selected" ? "" : "one");+ for (const [text, blockType] of [["- item", "NodeList"], ["> quote", "NodeBlockquote"]]) {+ check.ok(lute.SpinBlockDOM(paragraph(firstContent.textContent + text)).includes(`data-type="${blockType}"`));+ }+ } else {+ check.equal(softEnter(range, block, {wysiwyg: {element: editor}, lute}), true);+ check.equal(editor.children.length, 1);+ check.equal(marker.getTextWithoutSemanticMarkers(content).replace(/\u200b/g, ""), "one");+ }+ editor.remove();+ }+ }+ }+ // 聚焦有序列表会异步读取父列表,等待期间恢复的显示边界仍需在分割前清理。+ for (const focused of [false, true]) {+ const editor = document.createElement("div");+ editor.className = "protyle-wysiwyg";+ editor.contentEditable = "true";+ editor.innerHTML = lute.Md2BlockDOM("1. `one`");+ if (focused) {+ const item = editor.querySelector('[data-type="NodeListItem"]');+ editor.replaceChildren(item);+ }+ document.body.append(editor);+ marker.normalizeSemanticInlineElements(editor);+ const block = editor.querySelector('[data-type="NodeParagraph"]');+ const range = document.createRange();+ range.selectNode(block.querySelector("span"));+ focusByRange(range);+ await enter(block, range, {wysiwyg: {element: editor}, lute});+ const contents = editor.querySelectorAll('[contenteditable="true"]');+ check.equal(contents.length, 2);+ contents.forEach(content => check.equal(content.textContent, ""));+ editor.remove();+ }+ const authored = document.createElement("div");+ authored.textContent = "before\u2060after";+ const range = document.createRange();+ range.selectNodeContents(authored);+ boundary.prepareInlineElementBoundaryMutation(range);+ check.equal(authored.textContent, "before\u2060after");+ return "Inline boundary mutation cases passed";+};++test("input and line breaks preserve semantic inline boundary ownership", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 45000,+}, async () => {+ const compile = (text: string) => transpileModule(text, {+ compilerOptions: {target: ScriptTarget.ES2021, module: ModuleKind.CommonJS},+ }).outputText;+ const read = (name: string) => readFileSync(path.join(__dirname, "..", name + ".ts"), "utf8");+ const extract = (file: string, names: string[]) => {+ const source = createSourceFile(file, read(file), ScriptTarget.Latest, true);+ return compile(names.map(name => {+ const declaration = source.statements.filter(isVariableStatement).flatMap(statement =>+ Array.from(statement.declarationList.declarations)).find(item => item.name.getText(source) === name);+ return `const ${name} = ${declaration.initializer.getText(source)};`;+ }).join("\n"));+ };+ const sources = Object.fromEntries(["wysiwyg/compositionInput", "util/longTextWrap", "util/inlineElementBoundary",+ "util/inlineElementMarker"].map(name => [name, compile(read(name))]));+ const args = [sources, extract("wysiwyg/enter", ["enter", "softEnter", "listEnter", "removeEmptyNode"]) ++ extract("wysiwyg/list", ["genListItemElement"]),+ extract("util/selection", ["getSelectionOffset", "focusByWbr"]),+ extract("wysiwyg/getBlock", ["hasPreviousSibling", "hasNextSibling"])];+ const source = `const __name = value => value; (${browserCases.toString()})(${args.map(value => JSON.stringify(value)).join(",")})`;+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-inline-boundary-test-"));+ const script = path.join(temporary, "run.cjs");+ const lutePath = path.resolve(__dirname, "../../../stage/protyle/js/lute/lute.min.js");+ writeFileSync(script, `const {app, BrowserWindow, ipcMain} = require("electron");+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});+app.commandLine.appendSwitch("disable-gpu");+app.whenReady().then(async () => {+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});+ ipcMain.handle("type-text", async (_event, keyCode) => {+ win.webContents.sendInputEvent({type: "char", keyCode});+ await new Promise(resolve => setTimeout(resolve, 20));+ });+ try {+ await win.loadURL("about:blank");+ await win.webContents.executeJavaScript(require("node:fs").readFileSync(${JSON.stringify(lutePath)}, "utf8"));+ console.log(await win.webContents.executeJavaScript(${JSON.stringify(source)}));+ win.destroy();+ app.exit(0);+ } catch (error) {+ console.error(error);+ win.destroy();+ app.exit(1);+ }+});`, "utf8");+ const env = {...process.env};+ delete env.ELECTRON_RUN_AS_NODE;+ try {+ const result = await promisify(execFile)(require("electron") as unknown as string, [script],+ {env, timeout: 40000, windowsHide: true});+ assert.match(result.stdout, /Inline boundary mutation cases passed/);+ } finally {+ assert.equal(path.dirname(path.resolve(temporary)), path.resolve(tmpdir()));+ assert.ok(path.basename(temporary).startsWith("siyuan-inline-boundary-test-"));+ rmSync(temporary, {recursive: true, force: true});+ }+});diff --git a/app/src/protyle/util/inlineElementBoundary.ts b/app/src/protyle/util/inlineElementBoundary.tsindex b26625c203..c3d6bc24ca 100644--- a/app/src/protyle/util/inlineElementBoundary.ts+++ b/app/src/protyle/util/inlineElementBoundary.ts@@ -98,6 +98,21 @@ export const restoreInlineElementBoundaries = (root: ParentNode) => {elements.forEach(restoreInlineElementBoundary);};+const getInlineBoundaryAtPoint = (container: Node, offset: number) => {+ let previous = container.nodeType === Node.TEXT_NODE ? container : container.childNodes[offset - 1];+ while (previous?.nodeName === "WBR") {+ previous = previous.previousSibling;+ }+ if (!previous || getInlineElementBoundaryOffset(previous) < 0) {+ return;+ }+ let next = previous.nextSibling;+ while (next?.nodeName === "WBR") {+ next = next.nextSibling;+ }+ return next as HTMLElement;+};+export const prepareInlineElementBoundaryMutation = (range: Range) => {const ancestor = range.commonAncestorContainer;const root = ancestor.nodeType === Node.ELEMENT_NODE ? ancestor as HTMLElement : ancestor.parentElement;@@ -109,7 +124,10 @@ export const prepareInlineElementBoundaryMutation = (range: Range) => {if (inline) {elements.unshift(inline);}- const selected = elements.filter(element => range.intersectsNode(element));+ // 光标位于元素外部占位符时,输入或分段也会改变该占位符与元素的相邻关系。+ const boundaries = [getInlineBoundaryAtPoint(range.startContainer, range.startOffset),+ getInlineBoundaryAtPoint(range.endContainer, range.endOffset)];+ const selected = elements.filter(element => boundaries.includes(element) || range.intersectsNode(element));if (selected.length === 0) {return;}diff --git a/app/src/protyle/wysiwyg/enter.ts b/app/src/protyle/wysiwyg/enter.tsindex 919114f351..aeaa87c1f8 100644--- a/app/src/protyle/wysiwyg/enter.ts+++ b/app/src/protyle/wysiwyg/enter.ts@@ -39,6 +39,7 @@ import {getBlockSelectionModeElement} from "./blockSelection";import {getTextWithoutSemanticMarkers} from "../util/inlineElementMarker";+import {prepareInlineElementBoundaryMutation} from "../util/inlineElementBoundary";import {activateTrackedRangeInsertion,setTrackedRangeInsertionResult,@@ -87,6 +88,7 @@ export const enter = async (blockElement: HTMLElement, range: Range, protyle: IPreturn;}const editableElement = getContenteditableElement(blockElement) as HTMLElement;+ prepareInlineElementBoundaryMutation(range);// 选中图片后回车,应取消图片的选中状态 https://ld246.com/article/1650357135043editableElement.querySelectorAll(".img--select").forEach(item => {item.classList.remove("img--select");@@ -567,6 +569,7 @@ const listEnter = async (protyle: IProtyle, blockElement: HTMLElement, range: Raif (!listItemElement.isConnected) {return true;}+ prepareInlineElementBoundaryMutation(range);activateTrackedRangeInsertion(trackedRangeInsertion);const subListElement = listItemElement.querySelector(".list");let newElement;@@ -759,6 +762,7 @@ const removeEmptyNode = (newElement: Element) => {export const softEnter = (range: Range, nodeElement: HTMLElement, protyle: IProtyle,trackedRangeInsertion?: ITrackedRangeInsertion) => {+ prepareInlineElementBoundaryMutation(range);if (range.collapsed && nodeElement.getAttribute("data-type") === "NodeParagraph") {const editableElement = getContenteditableElement(nodeElement);if (editableElement?.contains(range.startContainer)) {