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: Refine theme cleanup for document clipboard content https://github.com/siyuan-note/siyuan/issues/19155
Daniele32949e90d28
diff --git a/kernel/api/lute.go b/kernel/api/lute.goindex 5136347ca4..92ac9742cc 100644--- a/kernel/api/lute.go+++ b/kernel/api/lute.go@@ -352,9 +352,7 @@ func prepareHTMLClipboardContent(luteEngine *lute.Lute, dom, text, mathML, offic// 将 Word 和 WPS 批注转换为行级备注 https://github.com/siyuan-note/siyuan/issues/18748resolvedDOM = normalizeWPSComments(resolvedDOM, text, wps)resolvedDOM = normalizeMSWordComments(resolvedDOM)- if office == "" && officeMathHTML == "" && wps == "" {- resolvedDOM = normalizeBrowserClipboardStyle(resolvedDOM)- }+ resolvedDOM = normalizeBrowserClipboardStyle(resolvedDOM, office != "" || officeMathHTML != "" || wps != "")return resolvedDOM, true}diff --git a/kernel/api/lute_clipboard_style.go b/kernel/api/lute_clipboard_style.goindex 55b029b32b..ab1d5e44dc 100644--- a/kernel/api/lute_clipboard_style.go+++ b/kernel/api/lute_clipboard_style.go@@ -27,13 +27,10 @@ import (var clipboardThemeProperties = []string{"color", "background-color", "font-family", "font-size"}// normalizeBrowserClipboardStyle 移除浏览器复制正文时附带的共同主题样式,保留局部格式差异。-func normalizeBrowserClipboardStyle(dom string) string {+func normalizeBrowserClipboardStyle(dom string, documentSource bool) string {lower := strings.ToLower(dom)- // 文档编辑器的样式由作者指定,不按网页正文的主题基准清理。- for _, marker := range []string{"mso-", "class=\"mso", "urn:schemas-microsoft-com:office", "data-lark", "data-type="} {- if strings.Contains(lower, marker) {- return dom- }+ if strings.Contains(lower, "data-type=") {+ return dom}if !strings.Contains(lower, "-webkit-text-stroke-width") {return dom@@ -42,6 +39,11 @@ func normalizeBrowserClipboardStyle(dom string) string {if err != nil {return dom}+ doc.Find("*").Each(func(_ int, selection *goquery.Selection) {+ if isClipboardDocumentBoundary(selection.Get(0)) {+ documentSource = true+ }+ })var roots []*nethtml.Nodevar baseline map[string]stringambiguous := false@@ -51,7 +53,7 @@ func normalizeBrowserClipboardStyle(dom string) string {switch n.Data {case "p", "div", "span", "body":decl := parse.HTMLStyleDeclarations(clipboardNodeStyle(n))- if isBrowserClipboardTheme(decl) {+ if isBrowserClipboardTheme(decl) && (!documentSource || isClipboardDocumentThemeWrapper(n)) {if baseline == nil {baseline = decl} else {@@ -65,6 +67,10 @@ func normalizeBrowserClipboardStyle(dom string) string {return}}+ // 文档正文内部的统一字体、字号也可能是作者主动设置,不能用重复次数推断默认格式。+ if documentSource && isClipboardDocumentBoundary(n) {+ return+ }}for child := n.FirstChild; child != nil; child = child.NextSibling {collect(child)@@ -98,6 +104,10 @@ func normalizeBrowserClipboardStyle(dom string) string {n.Attr[i].Val = filterClipboardStyle(n.Attr[i].Val, remove) + resets.String()}}+ // 文档来源只清理外层浏览器包装;即使子元素与主题同色,也保留其显式格式。+ if documentSource {+ return+ }for child := n.FirstChild; child != nil; child = child.NextSibling {clean(child, effective)}@@ -112,6 +122,57 @@ func normalizeBrowserClipboardStyle(dom string) string {return ret}+func isClipboardDocumentBoundary(n *nethtml.Node) bool {+ for _, attr := range n.Attr {+ key, value := strings.ToLower(attr.Key), strings.ToLower(attr.Val)+ if strings.HasPrefix(key, "data-lark") || strings.Contains(value, "urn:schemas-microsoft-com:office") {+ return true+ }+ if key == "style" && strings.Contains(value, "mso-") {+ return true+ }+ if key == "class" {+ for _, class := range strings.Fields(value) {+ if strings.HasPrefix(class, "mso") {+ return true+ }+ }+ }+ }+ return false+}++func isClipboardDocumentThemeWrapper(n *nethtml.Node) bool {+ if n.Data != "div" && n.Data != "body" {+ return false+ }+ if isClipboardDocumentBoundary(n) {+ // 飞书仅允许根容器参与浏览器样式识别;正文节点和 Office 样式节点不作为主题基准。+ larkRoot := false+ for _, attr := range n.Attr {+ if attr.Key == "data-lark-html-role" && attr.Val == "root" {+ larkRoot = true+ }+ if attr.Key == "style" && strings.Contains(strings.ToLower(attr.Val), "mso-") {+ return false+ }+ }+ if !larkRoot {+ return false+ }+ }+ hasContent := false+ for child := n.FirstChild; child != nil; child = child.NextSibling {+ if child.Type == nethtml.TextNode && strings.TrimSpace(child.Data) != "" {+ return false+ }+ if child.Type == nethtml.ElementNode {+ hasContent = true+ }+ }+ return hasContent+}+func clipboardNodeStyle(n *nethtml.Node) string {for _, attr := range n.Attr {if attr.Key == "style" {diff --git a/kernel/api/lute_clipboard_style_test.go b/kernel/api/lute_clipboard_style_test.goindex 495fe17f29..0bcd130a8f 100644--- a/kernel/api/lute_clipboard_style_test.go+++ b/kernel/api/lute_clipboard_style_test.go@@ -38,7 +38,7 @@ func githubClipboardFixture(t *testing.T) string {func TestBrowserClipboardTheme(t *testing.T) {input := render.Sanitize(githubClipboardFixture(t))- output := normalizeBrowserClipboardStyle(input)+ output := normalizeBrowserClipboardStyle(input, false)doc, _ := goquery.NewDocumentFromReader(strings.NewReader(output))doc.Find("p").Each(func(_ int, p *goquery.Selection) {style, _ := p.Attr("style")@@ -58,7 +58,7 @@ func TestBrowserClipboardTheme(t *testing.T) {if !strings.Contains(blockDOM, "感谢分享经验") || !strings.Contains(blockDOM, "欢迎提供") {t.Fatalf("content lost: %s", blockDOM)}- if again := normalizeBrowserClipboardStyle(output); again != output {+ if again := normalizeBrowserClipboardStyle(output, false); again != output {t.Fatal("normalization is not idempotent")}}@@ -69,7 +69,7 @@ func TestBrowserClipboardLocalStyles(t *testing.T) {input := `<div style='` + style + `'>plain <strong>bold</strong><em>italic</em><a href="https://example.com">link</a>` +`<span style="color: red; background: yellow; font-family: serif; font-size: 20px">highlight` +`<span style="color: rgb(240, 246, 252)">reset</span></span><small>small</small><code>code</code></div>`- output := normalizeBrowserClipboardStyle(input)+ output := normalizeBrowserClipboardStyle(input, false)lute := util.NewLute()lute.SetHTMLTag2TextMark(true)blockDOM := lute.HTML2BlockDOM(output)@@ -94,7 +94,7 @@ func TestBrowserClipboardThemeVariants(t *testing.T) {baseline = strings.ReplaceAll(baseline, "rgb(13, 17, 23)", "rgb(255, 255, 255)")}input := "<" + tag + " style='" + baseline + "'>plain<span style='" + baseline + "'>repeated</span></" + tag + ">"- output := normalizeBrowserClipboardStyle(input)+ output := normalizeBrowserClipboardStyle(input, false)lute := util.NewLute()lute.SetHTMLTag2TextMark(true)blockDOM := lute.HTML2BlockDOM(output)@@ -114,7 +114,7 @@ func TestBrowserClipboardPreservesExplicitStyles(t *testing.T) {`<div data-type="NodeParagraph">` + fixture + `</div>`,strings.Replace(fixture, "rgb(240, 246, 252)", "red", 1),} {- if output := normalizeBrowserClipboardStyle(input); output != input {+ if output := normalizeBrowserClipboardStyle(input, false); output != input {t.Errorf("explicit or ambiguous formatting changed: %s", output)}}@@ -147,3 +147,62 @@ func TestFilterClipboardStyle(t *testing.T) {t.Fatal(output)}}++func TestDocumentClipboardThemeWrapper(t *testing.T) {+ doc, _ := goquery.NewDocumentFromReader(strings.NewReader(githubClipboardFixture(t)))+ theme, _ := doc.Find("p").First().Attr("style")+ noMath := func(string, string, string) (string, bool) { return "", false }+ noOffice := func(string) (string, bool) { return "", false }+ for _, tc := range []struct {+ name, root, content, office, officeHTML, wps string+ }{+ {"wps", "", `<p class=MsoNormal><span style="font-family:宋体;font-size:12pt">正文</span><u><span style="color:red;background:yellow">强调</span></u></p>`, "", "", "wps"},+ {"office", "", `<p class='MsoNormal'><span style="font-family:Calibri;font-size:11pt">正文</span><strong>强调</strong></p>`, "office", "", ""},+ {"officeHTML", "", `<p><span style="font-family:Calibri;font-size:11pt">正文</span></p>`, "", "officeHTML", ""},+ {"feishu", `data-lark-html-role="root"`, `<div>正文<span style="color:red;background-color:yellow">强调</span></div>`, "", "", ""},+ {"officeDetected", "", `<p class='MsoNormal'><span style="font-family:Calibri;font-size:11pt">正文</span></p>`, "", "", ""},+ {"sameAsTheme", `data-lark-html-role="root"`, `<p><span style='` + theme + `'>显式格式</span></p>`, "", "", ""},+ } {+ t.Run(tc.name, func(t *testing.T) {+ input := `<div id="wrapper" ` + tc.root + ` style='` + theme + `'>` + tc.content + `</div>`+ output, useHTML := prepareHTMLClipboardContent(util.NewLute(), input, "", "", tc.office, tc.officeHTML, tc.wps, false, noMath, noOffice)+ if !useHTML {+ t.Fatal("HTML conversion was skipped")+ }+ actual, _ := goquery.NewDocumentFromReader(strings.NewReader(output))+ wrapper := actual.Find("#wrapper")+ style, _ := wrapper.Attr("style")+ decl := parse.HTMLStyleDeclarations(style)+ for _, key := range clipboardThemeProperties {+ if decl[key] != "" {+ t.Errorf("wrapper retained %s: %s", key, output)+ }+ }+ before, _ := goquery.NewDocumentFromReader(strings.NewReader(input))+ want, _ := before.Find("#wrapper").Html()+ got, _ := wrapper.Html()+ if got != want {+ t.Errorf("explicit content formatting changed:\nwant %s\ngot %s", want, got)+ }+ if again := normalizeBrowserClipboardStyle(output, tc.office != "" || tc.officeHTML != "" || tc.wps != ""); again != output {+ t.Fatal("document normalization is not idempotent")+ }+ })+ }+}++func TestDocumentClipboardAmbiguousStyles(t *testing.T) {+ doc, _ := goquery.NewDocumentFromReader(strings.NewReader(githubClipboardFixture(t)))+ theme, _ := doc.Find("p").First().Attr("style")+ for _, input := range []string{+ `<div style='` + theme + `'>direct text</div>`,+ `<div class='MsoNormal' style='` + theme + `'><span>text</span></div>`,+ `<div style='` + theme + `mso-style-name:Normal'><span>text</span></div>`,+ `<div data-lark-html-role="paragraph" style='` + theme + `'><span>text</span></div>`,+ `<div><span style="font-family:宋体;font-size:12pt">text</span></div>`,+ } {+ if output := normalizeBrowserClipboardStyle(input, true); output != input {+ t.Errorf("ambiguous document style changed: %s", output)+ }+ }+}