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 HTML formatting pasted into table cells https://github.com/siyuan-note/siyuan/issues/19777
Danielfcf8c3817a8c
diff --git a/app/src/protyle/render/av/richText.ts b/app/src/protyle/render/av/richText.tsindex 4a633241eb..cffcdeb358 100644--- a/app/src/protyle/render/av/richText.ts+++ b/app/src/protyle/render/av/richText.ts@@ -77,6 +77,8 @@ const ALLOWED_INLINE_TYPES = new Set(["text","u",]);+const TABLE_CELL_CUSTOM_INLINE_TYPE = /^custom_[A-Za-z0-9_-]{1,128}$/;+const TABLE_CELL_CUSTOM_STYLE_PROPERTY = /^--custom-[a-z0-9-]{1,128}$/;const previewCache = new Map<string, string>();const PREVIEW_CACHE_LIMIT = 256;let richTextLute: Lute | undefined;@@ -101,6 +103,33 @@ const replaceWithText = (element: Element) => {element.replaceWith(document.createTextNode(element.textContent || ""));};+const sanitizeTableCellCustomStyle = (style: string) => {+ if (style.length > 2048) {+ return "";+ }+ const declarations: string[] = [];+ style.split(";").forEach(declaration => {+ const separator = declaration.indexOf(":");+ if (separator < 0) {+ return;+ }+ const property = declaration.slice(0, separator).trim();+ const value = declaration.slice(separator + 1).trim();+ if (!TABLE_CELL_CUSTOM_STYLE_PROPERTY.test(property)) {+ return;+ }+ if (/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(value)) {+ declarations.push(`${property}: ${value};`);+ return;+ }+ const rgb = value.match(/^rgba?\(\s*(\d{1,3})(?:,\s*|\s+)(\d{1,3})(?:,\s*|\s+)(\d{1,3})(?:\s*[,/]\s*(0(?:\.\d+)?|1(?:\.0+)?))?\s*\)$/i);+ if (rgb && [rgb[1], rgb[2], rgb[3]].every(channel => Number(channel) <= 255)) {+ declarations.push(`${property}: ${value};`);+ }+ });+ return declarations.join(" ");+};+const removeUnsupportedBlockAttributes = (element: HTMLElement, codeSettings: boolean) => {Array.from(element.attributes).forEach((attribute) => {if (codeSettings && element.dataset.type === "NodeCodeBlock" &&@@ -146,7 +175,7 @@ export const getAVRichTextUnsupportedPasteBlocks = (blockDOM: string, images = freturn Array.from(names);};-export const sanitizeAVRichTextBlockDOM = (blockDOM: string, images = false) => {+export const sanitizeAVRichTextBlockDOM = (blockDOM: string, images = false, tableCellCustomInline = false) => {const template = document.createElement("template");template.innerHTML = blockDOM;// 在过滤临时属性前恢复边界,避免把显示占位符当成富文本内容保存。@@ -178,11 +207,15 @@ export const sanitizeAVRichTextBlockDOM = (blockDOM: string, images = false) =>if (images && types.length === 1 && types[0] === "img") {return;}- if (types.some((type) => !ALLOWED_INLINE_TYPES.has(type))) {+ if (types.some((type) => !ALLOWED_INLINE_TYPES.has(type) &&+ !(tableCellCustomInline && TABLE_CELL_CUSTOM_INLINE_TYPE.test(type)))) {replaceWithText(element);return;}- const style = types.includes("text") ? sanitizeAVRichTextInlineStyle(element.getAttribute("style")) : "";+ const hasCustomType = tableCellCustomInline && types.some(type => TABLE_CELL_CUSTOM_INLINE_TYPE.test(type));+ const sourceStyle = element.getAttribute("style") || "";+ const style = [types.includes("text") || hasCustomType ? sanitizeAVRichTextInlineStyle(sourceStyle) : "",+ hasCustomType ? sanitizeTableCellCustomStyle(sourceStyle) : ""].filter(Boolean).join(" ");if (style) {element.setAttribute("style", style);} else {@@ -335,8 +368,9 @@ const getAVRichTextPlainContent = (blockDOM: string, lute: Lute) => {return projectAVRichTextPlainBlocks(blocks, lute.BlockDOM2Content(blockDOM));};-export const serializeAVRichTextBlockDOM = (blockDOM: string, lute = getAVRichTextLute(), images = false) => {- const sanitizedBlockDOM = sanitizeAVRichTextBlockDOM(blockDOM, images);+export const serializeAVRichTextBlockDOM = (blockDOM: string, lute = getAVRichTextLute(), images = false,+ tableCellCustomInline = false) => {+ const sanitizedBlockDOM = sanitizeAVRichTextBlockDOM(blockDOM, images, tableCellCustomInline);let cleanBlockDOM = cleanAVRichTextBlockDOMStructure(sanitizedBlockDOM);const template = document.createElement("template");template.innerHTML = cleanBlockDOM;@@ -354,7 +388,8 @@ export const serializeAVRichTextBlockDOM = (blockDOM: string, lute = getAVRichTeconst protectedBlockDOM = protectAVRichTextStyleBackslashes(cleanBlockDOM, styleBackslashEncoding);const markdown = protectedBlockDOM ?styleBackslashEncoding.encodeMarkdown(lute.BlockDOM2Md(protectedBlockDOM).trim()) : "";- const normalizedBlockDOM = markdown ? sanitizeAVRichTextBlockDOM(parseAVRichTextKramdown(markdown, lute), images) : "";+ const normalizedBlockDOM = markdown ?+ sanitizeAVRichTextBlockDOM(parseAVRichTextKramdown(markdown, lute), images, tableCellCustomInline) : "";return {blockDOM: normalizedBlockDOM,markdown,@@ -362,8 +397,8 @@ export const serializeAVRichTextBlockDOM = (blockDOM: string, lute = getAVRichTe};};-export const getAVRichTextBlockDOM = (markdown: string, images = false) => markdown ?- sanitizeAVRichTextBlockDOM(parseAVRichTextKramdown(markdown), images) : "";+export const getAVRichTextBlockDOM = (markdown: string, images = false, tableCellCustomInline = false) => markdown ?+ sanitizeAVRichTextBlockDOM(parseAVRichTextKramdown(markdown), images, tableCellCustomInline) : "";const getAVRichTextPreviewBlockDOM = (blockDOM: string) => {const template = document.createElement("template");diff --git a/app/src/protyle/render/tableCellRichEditor.ts b/app/src/protyle/render/tableCellRichEditor.tsindex 773baf9bba..bc2cc1eaee 100644--- a/app/src/protyle/render/tableCellRichEditor.ts+++ b/app/src/protyle/render/tableCellRichEditor.ts@@ -48,8 +48,9 @@ export const applyTableCellRichInlineMark = (owner: IProtyle, cells: HTMLTableCeupload: false, websocket: false, pluginExtensions: false, customBlockRender: false,lute: getTableCellEditorLute(getAVRichTextLute(),window.siyuan.config.editor.markdown.blockFullWidthTaskList !== false),- sanitizeBlockDOM: html => sanitizeAVRichTextBlockDOM(html, true),+ sanitizeBlockDOM: html => sanitizeAVRichTextBlockDOM(html, true, true),getUnsupportedPasteBlocks: html => getAVRichTextUnsupportedPasteBlocks(html, true),+ richHTMLPaste: true,restoreLuteMarkdownSyntax: configureAVRichTextLute,},});@@ -175,8 +176,9 @@ export const openTableCellRichEditor = (owner: IProtyle, cell: HTMLTableCellElemlute: getTableCellEditorLute(getAVRichTextLute(),window.siyuan.config.editor.markdown.blockFullWidthTaskList !== false),lockedOptions: {toolbar, hint},- sanitizeBlockDOM: html => sanitizeAVRichTextBlockDOM(html, true),+ sanitizeBlockDOM: html => sanitizeAVRichTextBlockDOM(html, true, true),getUnsupportedPasteBlocks: html => getAVRichTextUnsupportedPasteBlocks(html, true),+ richHTMLPaste: true,restoreLuteMarkdownSyntax: configureAVRichTextLute,},afterSetContent: (protyle, element) => {diff --git a/app/src/protyle/runtimeCapabilities.ts b/app/src/protyle/runtimeCapabilities.tsindex acf362f0b2..f7ef828ddf 100644--- a/app/src/protyle/runtimeCapabilities.ts+++ b/app/src/protyle/runtimeCapabilities.ts@@ -11,6 +11,7 @@ export interface ProtyleRuntimeCapabilities {listItemFragment?: boolean;sanitizeBlockDOM?: (blockDOM: string) => string;getUnsupportedPasteBlocks?: (blockDOM: string) => string[];+ richHTMLPaste?: boolean;restoreLuteMarkdownSyntax?: (lute: Lute) => void;}@@ -54,6 +55,9 @@ export const getProtyleBlockDOMSanitizer = (protyle: IProtyle) =>export const getProtyleUnsupportedPasteBlocks = (protyle: IProtyle) =>protyleRuntimeCapabilities.get(protyle)?.getUnsupportedPasteBlocks;+export const isProtyleRichHTMLPasteEnabled = (protyle: IProtyle) =>+ protyleRuntimeCapabilities.get(protyle)?.richHTMLPaste === true;+export const restoreProtyleLuteMarkdownSyntax = (protyle: IProtyle, restoreDefault: (lute: Lute) => void) => {const restore = protyleRuntimeCapabilities.get(protyle)?.restoreLuteMarkdownSyntax || restoreDefault;restore(protyle.lute);diff --git a/app/src/protyle/util/paste.test.ts b/app/src/protyle/util/paste.test.tsindex 191a6e8e84..aca01571db 100644--- a/app/src/protyle/util/paste.test.ts+++ b/app/src/protyle/util/paste.test.ts@@ -11,19 +11,26 @@ const source = ts.transpileModule(readFileSync(join(process.cwd(), "src/protyle/compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022},}).outputText;-const createHarness = (disabled = false) => {+const createHarness = (disabled = false, richPaste = false) => {const uploads: Array<{files: unknown; options: {document: {rootID: string}; insertPosition: unknown}}> = [];const position = {range: {startContainer: {}}};let available = true;let localFiles: unknown[] = [];+ let convertedHTML = "";+ let convertedBy = "";+ let checkedBlockDOM = "";const restrictedFallback = new Error("restricted fallback");const mocks: Record<string, unknown> = {"../../constants": {Constants: {SIYUAN_ASSETS_IMAGE: [".png", ".jpg"]}},"../runtimeCapabilities": {getProtyleBlockDOMSanitizer: () => (html: string) => html,+ isProtyleRichHTMLPasteEnabled: () => richPaste,isProtyleUploadDisabled: () => disabled,areProtylePluginExtensionsEnabled: () => false,- getProtyleUnsupportedPasteBlocks: () => { throw restrictedFallback; },+ getProtyleUnsupportedPasteBlocks: () => (blockDOM: string) => {+ checkedBlockDOM = blockDOM;+ throw restrictedFallback;+ },},"../upload/insertPosition": {createUploadInsertPosition: () => position,@@ -33,7 +40,8 @@ const createHarness = (disabled = false) => {"./selection": {getEditorRange: () => position.range},"./hasClosest": {hasClosestBlock: (): undefined => undefined},"./wpsPresentation": {extractWPSPresentationClipboard: (): undefined => undefined},- "./compatibility": {getLocalFiles: async () => localFiles, isInHarmony: () => false},+ "./compatibility": {getLocalFiles: async () => localFiles, isInHarmony: () => false,+ getTextSiyuanFromTextHTML: (html: string) => ({textSiyuan: "", textHtml: html})},"../upload": {uploadFiles: (_protyle: unknown, files: unknown, _element: unknown, _success: unknown,_complete: unknown, options: typeof uploads[number]["options"]) => uploads.push({files, options}),@@ -42,13 +50,29 @@ const createHarness = (disabled = false) => {},};const module = {exports: {}};- runInNewContext(source, {module, exports: module.exports, require: (id: string) => mocks[id] || {}});+ runInNewContext(source, {module, exports: module.exports, require: (id: string) => mocks[id] || {},+ document: {createElement: () => ({content: {querySelector: (): null => null}})},+ });const api = module.exports as typeof import("./paste");- const paste = (files: unknown[] = [], siyuanHTML = "") => api.paste({wysiwyg: {element: {}}} as IProtyle, {+ const paste = (files: unknown[] = [], siyuanHTML = "", textPlain = "", textHTML = "") => api.paste({+ wysiwyg: {element: {}},+ lute: {Md2BlockDOM: (html: string) => {+ convertedHTML = html;+ convertedBy = "markdown";+ return `<div data-type="NodeParagraph">${html}</div>`;+ }, HTML2BlockDOM: (html: string) => {+ convertedHTML = html;+ convertedBy = "html";+ return `<div data-type="NodeParagraph">${html}</div>`;+ }},+ } as IProtyle, {target: {}, stopPropagation() {}, preventDefault() {},- clipboardData: {files, types: [], getData: (type: string) => type === "text/siyuan" ? siyuanHTML : ""},+ clipboardData: {files, types: [], getData: (type: string) => type === "text/siyuan" ? siyuanHTML :+ type === "text/plain" ? textPlain : type === "text/html" ? textHTML : ""},} as unknown as ClipboardEvent & {target: HTMLElement});return {paste, uploads, position, restrictedFallback, api: module.exports as typeof import("./paste"),+ getConvertedHTML: () => convertedHTML, getConvertedBy: () => convertedBy,+ getCheckedBlockDOM: () => checkedBlockDOM,setLocalFiles: (files: unknown[]) => { localFiles = files; },invalidate: () => { available = false; }};};@@ -92,6 +116,27 @@ describe("restricted cell image paste", () => {assert.equal(harness.uploads.length, 0);});}++ it("converts pasted HTML source before validating table cell content", async () => {+ const harness = createHarness(false, true);+ const html = '<span data-type="custom_example" style="--custom-example: #abc;">text</span>';+ await assert.rejects(harness.paste([], "", html), harness.restrictedFallback);+ assert.equal(harness.getConvertedHTML(), html);+ assert.equal(harness.getConvertedBy(), "markdown");+ assert.equal(harness.getCheckedBlockDOM(), `<div data-type="NodeParagraph">${html}</div>`);+ });++ it("retains custom spans in HTML clipboard content without changing ordinary HTML conversion", async () => {+ const custom = '<span data-type="custom_example" style="--custom-example: #abc;">text</span>';+ const customHarness = createHarness(false, true);+ await assert.rejects(customHarness.paste([], "", "text", custom), customHarness.restrictedFallback);+ assert.equal(customHarness.getConvertedBy(), "markdown");+ assert.equal(customHarness.getCheckedBlockDOM(), `<div data-type="NodeParagraph">${custom}</div>`);+ const ordinaryHarness = createHarness(false, true);+ await assert.rejects(ordinaryHarness.paste([], "", "bold", "<strong>bold</strong>"),+ ordinaryHarness.restrictedFallback);+ assert.equal(ordinaryHarness.getConvertedBy(), "html");+ });});describe("strip pasted IAL data attributes", () => {@@ -130,6 +175,7 @@ describe("restricted cell selected text paste", () => {"../../constants": {Constants: {ZWSP: "\u200b"}},"../runtimeCapabilities": {getProtyleBlockDOMSanitizer: () => (html: string) => html,+ isProtyleRichHTMLPasteEnabled: () => false,getProtyleUnsupportedPasteBlocks: () => () => options.unsupported ? ["Table"] : [],getProtyleRestrictedPlainTextHTML: (text: string) => "plain:" + text,isProtyleUploadDisabled: () => true,diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.tsindex 902930b0a7..8c90d24a70 100644--- a/app/src/protyle/util/paste.ts+++ b/app/src/protyle/util/paste.ts@@ -73,6 +73,7 @@ import {getProtyleBlockDOMSanitizer,getProtyleUnsupportedPasteBlocks,getProtyleRestrictedPlainTextHTML,+ isProtyleRichHTMLPasteEnabled,isProtyleUploadDisabled,restoreProtyleLuteMarkdownSyntax,} from "../runtimeCapabilities";@@ -802,6 +803,19 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEvenreturn;}}+ if (blockDOMSanitizer && isProtyleRichHTMLPasteEnabled(protyle) && !siyuanHTML && !files?.length &&+ (textHTML || /<[a-z][^>]*>/i.test(textPlain))) {+ // 表格单元格将可解析的富文本转换为块 DOM,再统一检查不支持的块和净化行内标记。+ const richBlockDOM = textHTML ?+ (/^<span\b[^>]*\bdata-type\s*=\s*["']custom_[^>]*>[\s\S]*<\/span>$/i.test(textHTML.trim()) ?+ protyle.lute.Md2BlockDOM(textHTML) : protyle.lute.HTML2BlockDOM(textHTML)) :+ protyle.lute.Md2BlockDOM(textPlain);+ const richTemplate = document.createElement("template");+ richTemplate.innerHTML = richBlockDOM;+ if (!richTemplate.content.querySelector(".img, img")) {+ siyuanHTML = richBlockDOM;+ }+ }if (blockDOMSanitizer) {// 在清洗和修改选区前检查完整载荷,避免不支持的块被静默删除后只粘贴部分内容。const getUnsupportedBlocks = getProtyleUnsupportedPasteBlocks(protyle);diff --git a/app/src/protyle/util/tableCellRich.ts b/app/src/protyle/util/tableCellRich.tsindex 805899238d..4f275404d6 100644--- a/app/src/protyle/util/tableCellRich.ts+++ b/app/src/protyle/util/tableCellRich.ts@@ -50,7 +50,7 @@ export const getTableCellInlineHTML = (blockDOM: string): string | null => {export const getTableCellRichBlockDOM = (cell: Element) => {const encoded = cell.getAttribute(TABLE_CELL_RICH_ATTRIBUTE);// 普通单元格先转换已有的行级 DOM,文字中的 Markdown 标记保持字面含义。- const blockDOM = encoded !== null ? getAVRichTextBlockDOM(decodeTableCellRich(encoded).content, true) :+ const blockDOM = encoded !== null ? getAVRichTextBlockDOM(decodeTableCellRich(encoded).content, true, true) :`<div class="p" data-type="NodeParagraph" data-node-id="${Lute.NewNodeID()}"><div contenteditable="true">` +`${(cell.getAttribute(TABLE_CELL_INLINE_ATTRIBUTE) ?? cell.innerHTML) || "\u200b"}</div></div>`;const template = document.createElement("template");@@ -81,7 +81,7 @@ export const getTableCellRichBlockDOM = (cell: Element) => {export const serializeTableCellRich = (blockDOM: string) => {const template = document.createElement("template");- template.innerHTML = sanitizeAVRichTextBlockDOM(blockDOM, true);+ template.innerHTML = sanitizeAVRichTextBlockDOM(blockDOM, true, true);// 光标由事务选区单独记录,不能将临时定位节点序列化为正文。template.content.querySelectorAll("wbr").forEach(marker => marker.remove());let prefix = "SYTABLECELLWHITESPACE";@@ -122,13 +122,13 @@ export const serializeTableCellRich = (blockDOM: string) => {}}const lute = getAVRichTextLute();- const value = serializeAVRichTextBlockDOM(template.innerHTML, lute, true);+ const value = serializeAVRichTextBlockDOM(template.innerHTML, lute, true, true);if (whitespace.length === 0) {return value;}const markdown = value.markdown.replace(new RegExp(`${prefix}(\\d+)END`, "g"),(_token, index) => whitespace[Number(index)]);- const normalizedBlockDOM = getAVRichTextBlockDOM(markdown, true);+ const normalizedBlockDOM = getAVRichTextBlockDOM(markdown, true, true);return {blockDOM: normalizedBlockDOM, markdown, plainText: lute.BlockDOM2Content(normalizedBlockDOM)};};diff --git a/app/src/protyle/util/tableCellRichLute.test.ts b/app/src/protyle/util/tableCellRichLute.test.tsindex fbf5b11df3..830f91f838 100644--- a/app/src/protyle/util/tableCellRichLute.test.ts+++ b/app/src/protyle/util/tableCellRichLute.test.ts@@ -22,6 +22,33 @@ const browserCases = async (source: string, enterSource: string, hintSource: strconst base = api.configureAVRichTextLute(api.getAgentLute({emojiSite: "/emojis", emojis: {},headingAnchor: false, listStyle: false, paragraphBeginningSpace: true, sanitize: true}));const lute = api.getTableCellEditorLute(base);+ const customHTML = '<span data-type="custom_symble_strong_CJK_rectangle_yin" ' ++ 'style="--custom-symble-strong: rgb(0 166 240 / 1);">test</span>';+ const customBlockDOM = base.Md2BlockDOM(customHTML + "\n\nsecond");+ const customCell = document.createElement("td");+ const customValue = api.serializeTableCellRich(customBlockDOM);+ api.updateTableCellEditingValue(customCell, customValue);+ check.ok(customCell.hasAttribute("data-sy-table-cell-rich"));+ const reopenedCustom = api.getTableCellRichBlockDOM(customCell);+ check.match(reopenedCustom, /data-type="custom_symble_strong_CJK_rectangle_yin"/);+ check.match(reopenedCustom, /--custom-symble-strong: rgb\(0 166 240 \/ 1\)/);+ check.match(reopenedCustom, /second/);+ check.doesNotMatch(api.sanitizeAVRichTextBlockDOM(customBlockDOM, true), /custom_symble/);+ const unsafeCustom = api.sanitizeAVRichTextBlockDOM(+ '<div data-type="NodeParagraph"><div contenteditable="true">' ++ '<span data-type="custom_bad" style="--custom-bad: url(javascript:alert(1)); ' ++ '--custom-safe: #abc;" onclick="alert(1)">safe</span></div></div>', true, true);+ check.match(unsafeCustom, /--custom-safe: #abc;/);+ check.doesNotMatch(unsafeCustom, /url\(|onclick|javascript:/);+ const externalCustom = api.serializeTableCellRich(base.Md2BlockDOM(customHTML));+ check.match(externalCustom.blockDOM, /data-type="custom_symble_strong_CJK_rectangle_yin"/);+ check.match(externalCustom.blockDOM, /--custom-symble-strong: rgb\(0 166 240 \/ 1\)/);+ const inlineCustomCell = document.createElement("td");+ api.updateTableCellEditingValue(inlineCustomCell, externalCustom);+ check.equal(inlineCustomCell.hasAttribute("data-sy-table-cell-rich"), false);+ check.match(api.getTableCellRichBlockDOM(inlineCustomCell), /custom_symble_strong_CJK_rectangle_yin/);+ const externalBold = api.serializeTableCellRich(base.HTML2BlockDOM("<strong>bold</strong>"));+ check.match(externalBold.blockDOM, /data-type="strong"/);const editable = document.createElement("div");for (const text of ["```", "```go", "~~~~shell", " ```js", "before\n\n```ts"]) {editable.textContent = text;@@ -498,7 +525,7 @@ test("table cells insert code through slash and Enter without losing soft breaksconst hint = createSourceFile("hint.ts", read("../hint/index.ts"), ScriptTarget.Latest, true);const hintClass = hint.statements.find(isClassDeclaration);const fill = hintClass.members.find(member => isMethodDeclaration(member) && member.name.getText(hint) === "fill");- const hintSource = compile("class Hint {" + fill.getText(hint) + "}");+ const hintSource = compile("const isProtyleListItemFragment = () => false; class Hint {" + fill.getText(hint) + "}");const editor = read("../render/tableCellRichEditor.ts");const start = editor.indexOf('host.addEventListener("keydown", event => {');const end = editor.indexOf("}, {capture: true, signal});", start) + "}, {capture: true, signal});".length;