Skip to content

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

:bug: Remove browser theme styles when pasting HTML https://github.com/siyuan-note/siyuan/issues/19155

Danielf03dde568a7e
diff --git a/kernel/api/lute.go b/kernel/api/lute.go
index 13604696e3..5136347ca4 100644
--- a/kernel/api/lute.go
+++ b/kernel/api/lute.go
@@ -351,7 +351,11 @@ func prepareHTMLClipboardContent(luteEngine *lute.Lute, dom, text, mathML, offic
}
// 将 Word 和 WPS 批注转换为行级备注 https://github.com/siyuan-note/siyuan/issues/18748
resolvedDOM = normalizeWPSComments(resolvedDOM, text, wps)
- return normalizeMSWordComments(resolvedDOM), true
+ resolvedDOM = normalizeMSWordComments(resolvedDOM)
+ if office == "" && officeMathHTML == "" && wps == "" {
+ resolvedDOM = normalizeBrowserClipboardStyle(resolvedDOM)
+ }
+ return resolvedDOM, true
}
func resolveHTMLClipboardContent(luteEngine *lute.Lute, dom, mathML, office, officeMathHTML, wps string,
diff --git a/kernel/api/lute_clipboard_style.go b/kernel/api/lute_clipboard_style.go
new file mode 100644
index 0000000000..55b029b32b
--- /dev/null
+++ b/kernel/api/lute_clipboard_style.go
@@ -0,0 +1,185 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package api
+
+import (
+ "strings"
+
+ "github.com/88250/lute/parse"
+ "github.com/PuerkitoBio/goquery"
+ nethtml "golang.org/x/net/html"
+)
+
+var clipboardThemeProperties = []string{"color", "background-color", "font-family", "font-size"}
+
+// normalizeBrowserClipboardStyle 移除浏览器复制正文时附带的共同主题样式,保留局部格式差异。
+func normalizeBrowserClipboardStyle(dom string) 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, "-webkit-text-stroke-width") {
+ return dom
+ }
+ doc, err := goquery.NewDocumentFromReader(strings.NewReader(dom))
+ if err != nil {
+ return dom
+ }
+ var roots []*nethtml.Node
+ var baseline map[string]string
+ ambiguous := false
+ var collect func(*nethtml.Node)
+ collect = func(n *nethtml.Node) {
+ if n.Type == nethtml.ElementNode {
+ switch n.Data {
+ case "p", "div", "span", "body":
+ decl := parse.HTMLStyleDeclarations(clipboardNodeStyle(n))
+ if isBrowserClipboardTheme(decl) {
+ if baseline == nil {
+ baseline = decl
+ } else {
+ for _, key := range clipboardThemeProperties {
+ if decl[key] != baseline[key] {
+ ambiguous = true
+ }
+ }
+ }
+ roots = append(roots, n)
+ return
+ }
+ }
+ }
+ for child := n.FirstChild; child != nil; child = child.NextSibling {
+ collect(child)
+ }
+ }
+ collect(doc.Find("body").Get(0))
+ if len(roots) == 0 || ambiguous {
+ return dom
+ }
+ var clean func(*nethtml.Node, map[string]string)
+ clean = func(n *nethtml.Node, inherited map[string]string) {
+ decl := parse.HTMLStyleDeclarations(clipboardNodeStyle(n))
+ effective := make(map[string]string, len(clipboardThemeProperties))
+ remove := map[string]bool{}
+ var resets strings.Builder
+ for _, key := range clipboardThemeProperties {
+ effective[key] = inherited[key]
+ if value := decl[key]; value != "" && value != "inherit" && value != "unset" {
+ effective[key] = value
+ if value == baseline[key] {
+ remove[key] = true
+ // 局部格式之后恢复正文基准时,显式重置,避免继续继承局部格式。
+ if inherited[key] != "" && inherited[key] != baseline[key] {
+ resets.WriteString(key + ": initial;")
+ }
+ }
+ }
+ }
+ for i := range n.Attr {
+ if n.Attr[i].Key == "style" && len(remove) > 0 {
+ n.Attr[i].Val = filterClipboardStyle(n.Attr[i].Val, remove) + resets.String()
+ }
+ }
+ for child := n.FirstChild; child != nil; child = child.NextSibling {
+ clean(child, effective)
+ }
+ }
+ for _, root := range roots {
+ clean(root, nil)
+ }
+ ret, err := doc.Find("body").Html()
+ if err != nil {
+ return dom
+ }
+ return ret
+}
+
+func clipboardNodeStyle(n *nethtml.Node) string {
+ for _, attr := range n.Attr {
+ if attr.Key == "style" {
+ return attr.Val
+ }
+ }
+ return ""
+}
+
+func isBrowserClipboardTheme(decl map[string]string) bool {
+ // 同时要求浏览器序列化特征及完整正文基准,避免把普通手写样式识别为页面主题。
+ for _, key := range []string{"-webkit-text-stroke-width", "font-variant-caps", "letter-spacing", "orphans", "widows", "text-indent", "text-transform", "word-spacing", "white-space", "color", "background-color", "font-family", "font-size"} {
+ if decl[key] == "" {
+ return false
+ }
+ }
+ return true
+}
+
+// filterClipboardStyle 仅移除目标声明,原样保留其他声明的优先级、引号和函数内容。
+func filterClipboardStyle(style string, remove map[string]bool) string {
+ var ret strings.Builder
+ start, depth := 0, 0
+ var quote rune
+ escaped := false
+ style += ";"
+ for i, c := range style {
+ if escaped {
+ escaped = false
+ continue
+ }
+ if c == '\\' {
+ escaped = true
+ continue
+ }
+ if quote != 0 {
+ if c == quote {
+ quote = 0
+ }
+ continue
+ }
+ if c == '\'' || c == '"' {
+ quote = c
+ continue
+ }
+ if c == '(' {
+ depth++
+ } else if c == ')' {
+ depth--
+ }
+ if c != ';' || depth != 0 {
+ continue
+ }
+ part := style[start : i+1]
+ start = i + 1
+ decl := parse.HTMLStyleDeclarations(part)
+ keep := true
+ for key := range decl {
+ if remove[key] {
+ keep = false
+ }
+ }
+ if keep && strings.TrimSpace(part) != ";" {
+ ret.WriteString(part)
+ }
+ }
+ if start < len(style)-1 {
+ ret.WriteString(style[start : len(style)-1])
+ }
+ return ret.String()
+}
diff --git a/kernel/api/lute_clipboard_style_test.go b/kernel/api/lute_clipboard_style_test.go
new file mode 100644
index 0000000000..495fe17f29
--- /dev/null
+++ b/kernel/api/lute_clipboard_style_test.go
@@ -0,0 +1,149 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package api
+
+import (
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/88250/lute/parse"
+ "github.com/88250/lute/render"
+ "github.com/PuerkitoBio/goquery"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func githubClipboardFixture(t *testing.T) string {
+ t.Helper()
+ data, err := os.ReadFile("testdata/github-theme-clipboard.html")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(data)
+}
+
+func TestBrowserClipboardTheme(t *testing.T) {
+ input := render.Sanitize(githubClipboardFixture(t))
+ output := normalizeBrowserClipboardStyle(input)
+ doc, _ := goquery.NewDocumentFromReader(strings.NewReader(output))
+ doc.Find("p").Each(func(_ int, p *goquery.Selection) {
+ style, _ := p.Attr("style")
+ decl := parse.HTMLStyleDeclarations(style)
+ for _, key := range clipboardThemeProperties {
+ if decl[key] != "" {
+ t.Errorf("theme property %s survived: %s", key, style)
+ }
+ }
+ })
+ lute := util.NewLute()
+ lute.SetHTMLTag2TextMark(true)
+ blockDOM := lute.HTML2BlockDOM(output)
+ if strings.Contains(blockDOM, "rgb(") || strings.Contains(blockDOM, "font-size:") || strings.Contains(blockDOM, "font-family:") {
+ t.Fatalf("theme leaked into BlockDOM: %s", blockDOM)
+ }
+ if !strings.Contains(blockDOM, "感谢分享经验") || !strings.Contains(blockDOM, "欢迎提供") {
+ t.Fatalf("content lost: %s", blockDOM)
+ }
+ if again := normalizeBrowserClipboardStyle(output); again != output {
+ t.Fatal("normalization is not idempotent")
+ }
+}
+
+func TestBrowserClipboardLocalStyles(t *testing.T) {
+ doc, _ := goquery.NewDocumentFromReader(strings.NewReader(githubClipboardFixture(t)))
+ style, _ := doc.Find("p").First().Attr("style")
+ 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)
+ lute := util.NewLute()
+ lute.SetHTMLTag2TextMark(true)
+ blockDOM := lute.HTML2BlockDOM(output)
+ for _, expected := range []string{"color: red", "background-color: yellow", "font-family: serif", "font-size: 20.000000px", "strong", "em", "https://example.com", "code", "font-size: 0.833333em"} {
+ if !strings.Contains(blockDOM, expected) {
+ t.Errorf("missing %q in %s", expected, blockDOM)
+ }
+ }
+ if strings.Contains(blockDOM, "rgb(240") || strings.Contains(blockDOM, "rgb(13") {
+ t.Fatalf("theme survived nested reset: %s", blockDOM)
+ }
+}
+
+func TestBrowserClipboardThemeVariants(t *testing.T) {
+ doc, _ := goquery.NewDocumentFromReader(strings.NewReader(githubClipboardFixture(t)))
+ style, _ := doc.Find("p").First().Attr("style")
+ for _, tag := range []string{"p", "span", "div"} {
+ for _, light := range []bool{false, true} {
+ baseline := style
+ if light {
+ baseline = strings.ReplaceAll(baseline, "rgb(240, 246, 252)", "rgb(31, 35, 40)")
+ 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)
+ lute := util.NewLute()
+ lute.SetHTMLTag2TextMark(true)
+ blockDOM := lute.HTML2BlockDOM(output)
+ if strings.Contains(blockDOM, "rgb(") || strings.Contains(blockDOM, "font-size:") || strings.Contains(blockDOM, "font-family:") || !strings.Contains(blockDOM, "plainrepeated") {
+ t.Errorf("theme variant %s light=%v: %s", tag, light, blockDOM)
+ }
+ }
+ }
+}
+
+func TestBrowserClipboardPreservesExplicitStyles(t *testing.T) {
+ fixture := githubClipboardFixture(t)
+ for _, input := range []string{
+ `<p style="color: white; background-color: black; font-family: serif; font-size: 14px">explicit</p>`,
+ `<div data-lark-html-role="root">` + fixture + `</div>`,
+ `<div style="mso-style-name: normal">` + fixture + `</div>`,
+ `<div data-type="NodeParagraph">` + fixture + `</div>`,
+ strings.Replace(fixture, "rgb(240, 246, 252)", "red", 1),
+ } {
+ if output := normalizeBrowserClipboardStyle(input); output != input {
+ t.Errorf("explicit or ambiguous formatting changed: %s", output)
+ }
+ }
+ noMath := func(string, string, string) (string, bool) { return "", false }
+ noOffice := func(string) (string, bool) { return "", false }
+ normalized, _ := prepareHTMLClipboardContent(util.NewLute(), fixture, "", "", "", "", "", false, noMath, noOffice)
+ if strings.Contains(normalized, "rgb(240, 246, 252)") {
+ t.Fatal("clipboard preparation did not normalize browser styles")
+ }
+ frozen, _ := prepareHTMLClipboardContent(util.NewLute(), normalized, "", "", "", "", "", true, noMath, noOffice)
+ if frozen != normalized {
+ t.Fatal("normalized HTML changed during the second conversion stage")
+ }
+ for _, office := range [][3]string{{"office", "", ""}, {"", "officeHTML", ""}, {"", "", "wps"}} {
+ output, _ := prepareHTMLClipboardContent(util.NewLute(), fixture, "", "", office[0], office[1], office[2], false, noMath, noOffice)
+ if !strings.Contains(output, "rgb(240, 246, 252)") {
+ t.Fatal("Office theme-like formatting was removed")
+ }
+ }
+ prepared, _ := prepareHTMLClipboardContent(util.NewLute(), fixture, "", "", "", "", "", true, noMath, noOffice)
+ if prepared != fixture {
+ t.Fatal("prepared HTML was processed again")
+ }
+}
+
+func TestFilterClipboardStyle(t *testing.T) {
+ input := `color: red !important; color: blue; font-family: "a;b"; background-image: url("a;b"); margin: 0 !important;`
+ output := filterClipboardStyle(input, map[string]bool{"color": true})
+ if strings.Contains(output, "color:") || !strings.Contains(output, `font-family: "a;b";`) || !strings.Contains(output, `background-image: url("a;b");`) || !strings.Contains(output, "margin: 0 !important;") {
+ t.Fatal(output)
+ }
+}
diff --git a/kernel/api/testdata/github-theme-clipboard.html b/kernel/api/testdata/github-theme-clipboard.html
new file mode 100644
index 0000000000..a0c0dbd3ec
--- /dev/null
+++ b/kernel/api/testdata/github-theme-clipboard.html
@@ -0,0 +1 @@
+<p dir="auto" style="box-sizing: border-box; margin-top: 0px !important; margin-bottom: 16px; color: rgb(240, 246, 252); font-family: &quot;Mona Sans VF&quot;, -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Noto Sans Backtick Fix&quot;, &quot;Noto Sans&quot;, Helvetica, Arial, sans-serif, &quot;Apple Color Emoji&quot;, &quot;Segoe UI Emoji&quot;; font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(13, 17, 23); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">感谢分享经验。本次已补充颜色、背景色、字体和字号的保留,并修复了 WPS 样例中的背景色丢失及下划线样式异常。</p><p dir="auto" style="box-sizing: border-box; margin-top: 0px; margin-bottom: 0px !important; color: rgb(240, 246, 252); font-family: &quot;Mona Sans VF&quot;, -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Noto Sans Backtick Fix&quot;, &quot;Noto Sans&quot;, Helvetica, Arial, sans-serif, &quot;Apple Color Emoji&quot;, &quot;Segoe UI Emoji&quot;; font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(13, 17, 23); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">目前倾向于默认尽量保留源格式,暂不增加粘贴格式选项。你提到的容器背景与文字高亮难以区分,确实是需要继续完善的边界。后续会结合 Office 和网页的实际样例改进,也欢迎提供容易出现问题的剪贴板 HTML。</p>
\ No newline at end of file