Skip to content

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

:bug: Preserve database titles and layout in image exports https://github.com/siyuan-note/siyuan/issues/20104

Liang Dingf5d34dcb1126
diff --git a/app/src/protyle/export/imageLayout.test.ts b/app/src/protyle/export/imageLayout.test.ts
index f0e5945c95..80951acef1 100644
--- a/app/src/protyle/export/imageLayout.test.ts
+++ b/app/src/protyle/export/imageLayout.test.ts
@@ -34,16 +34,20 @@ const browserCases = async (layoutSource: string, exportSource: string, mobile:
class ExportDialog {
element: HTMLElement;
resize: () => void;
- constructor(options: {content: string, width: string, height: string, resizeCallback: () => void}) {
+ private onDestroy: () => void;
+ constructor(options: {content: string, width: string, height: string, resizeCallback: () => void,
+ destroyCallback: () => void}) {
this.element = document.createElement("div");
this.element.classList.add("b3-dialog--open");
this.element.innerHTML = `<div class="b3-dialog"><div class="b3-dialog__container" style="width:${options.width};height:${options.height}">
<div class="b3-dialog__body">${options.content}</div></div></div>`;
document.body.append(this.element);
this.resize = options.resizeCallback;
+ this.onDestroy = options.destroyCallback;
dialog = {element: this.element, resize: options.resizeCallback};
}
destroy() {
+ this.onDestroy?.();
this.element.remove();
}
}
@@ -167,6 +171,10 @@ ${index === columns - 1 ? '<span class="marker" style="display:block;width:20px;
check.equal(getComputedStyle(wide.querySelector("table")).transform, "none");
check.ok(wide.querySelector("table").getBoundingClientRect().right <= imageElement.getBoundingClientRect().right,
"Image must cover the whole table");
+ wide.querySelector<HTMLElement>("table").style.width = "2200px";
+ await new Promise(resolve => setTimeout(resolve, 100));
+ check.ok(wide.querySelector("table").getBoundingClientRect().right <= imageElement.getBoundingClientRect().right,
+ "Preview border must follow table width changes without resizing the dialog");
wide.scrollLeft = wide.scrollWidth - wide.clientWidth;
const oldScroll = wide.scrollLeft;
await capture();
@@ -176,6 +184,20 @@ ${index === columns - 1 ? '<span class="marker" style="display:block;width:20px;
dialog.resize();
check.equal(imageElement.style.minWidth, "");
+ const database = await open(`<div class="table"><div><table>
+<caption>Database &amp; title</caption><colgroup><col style="width: 120px"><col style="width: 240px"></colgroup>
+<thead><tr><th style="white-space: nowrap">Long database property name</th><th style="white-space: nowrap">Second property</th></tr></thead>
+<tbody><tr><td>first line<br>second line</td><td><span class="marker" style="display:block;width:20px;height:20px;background:red"></span></td></tr></tbody>
+</table></div></div>`);
+ check.equal(database.querySelector("caption").textContent, "Database & title");
+ const header = database.querySelector<HTMLElement>("th");
+ const range = document.createRange();
+ range.selectNodeContents(header);
+ check.equal(range.getClientRects().length, 1, "Database headers must stay on one line");
+ check.ok(database.querySelector("td").getBoundingClientRect().height > header.getBoundingClientRect().height,
+ "Database cells must retain explicit line breaks");
+ await capture();
+
const nested = await open(`<div class="sb" data-node-id="columns" data-sb-layout="col">${table(2)}${table(2)}</div>`);
const nestedTables = nested.querySelectorAll("table");
const firstTable = nestedTables[0].getBoundingClientRect();
diff --git a/app/src/protyle/export/imageLayout.ts b/app/src/protyle/export/imageLayout.ts
index f0d7416618..6ea35c436f 100644
--- a/app/src/protyle/export/imageLayout.ts
+++ b/app/src/protyle/export/imageLayout.ts
@@ -2,6 +2,27 @@ const MAX_IMAGE_SIZE = 16384;
// 限制位图面积,避免单个 RGBA 画布占用超过 256 MiB。
const MAX_IMAGE_PIXELS = 64 * 1024 * 1024;
+export const observeExportImageLayout = (imageElement: HTMLElement) => {
+ let frame = 0;
+ const observer = new ResizeObserver(() => {
+ cancelAnimationFrame(frame);
+ frame = requestAnimationFrame(() => {
+ frame = 0;
+ if (imageElement.isConnected) {
+ updateExportImageLayout(imageElement);
+ }
+ });
+ });
+ observer.observe(imageElement.parentElement);
+ observer.observe(imageElement.querySelector(".protyle-wysiwyg"));
+ imageElement.querySelectorAll("table").forEach(element => observer.observe(element));
+ updateExportImageLayout(imageElement);
+ return () => {
+ observer.disconnect();
+ cancelAnimationFrame(frame);
+ };
+};
+
export const updateExportImageLayout = (imageElement: HTMLElement) => {
const scrollElement = imageElement.parentElement;
const scrollLeft = scrollElement.scrollLeft;
diff --git a/app/src/protyle/export/util.ts b/app/src/protyle/export/util.ts
index 1bebc86b6d..4e7ce8d4f1 100644
--- a/app/src/protyle/export/util.ts
+++ b/app/src/protyle/export/util.ts
@@ -16,7 +16,7 @@ import {isInAndroid, isIPad, isIPhone, isSafari, saveExportFile, setStorageVal}
import {useShell} from "../../util/pathName";
import {getHostCapabilities, sanitizeKernelHTML} from "../../util/hostCapabilities";
import {copyPNGByLink, writePNGBlob} from "../../menus/util";
-import {getExportImageSize, isExportImageSizeSupported, updateExportImageLayout} from "./imageLayout";
+import {getExportImageSize, isExportImageSizeSupported, observeExportImageLayout, updateExportImageLayout} from "./imageLayout";
const IMAGE_PLACEHOLDER = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
@@ -36,8 +36,12 @@ export const exportImage = (id: string, copyOnly = false) => {
if (!getHostCapabilities().documentImportExport) {
return;
}
+ let stopObservingLayout: () => void;
const exportDialog = new Dialog({
disableAnimation: true,
+ destroyCallback() {
+ stopObservingLayout?.();
+ },
title: copyOnly ? window.siyuan.languages.copyAsPNG : window.siyuan.languages.exportAsImage,
content: `<div class="b3-dialog__content" style="${isMobile() ? "padding:8px;" : ""};background-color: var(--b3-theme-background)">
<div style="${isMobile() ? "margin: 8px 0" : "padding: 48px;margin: 8px 0"}" class="export-img">
@@ -325,7 +329,8 @@ export const exportImage = (id: string, copyOnly = false) => {
});
processRender(previewElement);
highlightRender(previewElement);
- updateExportImageLayout(exportDialog.element.querySelector(".export-img"));
+ stopObservingLayout?.();
+ stopObservingLayout = observeExportImageLayout(exportDialog.element.querySelector(".export-img"));
await updateWatermark();
if (revision !== previewRevision) {
diff --git a/kernel/model/export.go b/kernel/model/export.go
index c7fa8566ea..b83b924d5f 100644
--- a/kernel/model/export.go
+++ b/kernel/model/export.go
@@ -3634,6 +3634,24 @@ func exportTree(tree *parse.Tree, wysiwyg, richTableCells, keepFold, avHiddenCol
aligns := getAttrViewTableAligns(table, avHiddenCol)
mdTable := &ast.Node{Type: ast.NodeTable, TableAligns: aligns}
+ if wysiwyg {
+ if !view.HideAttrViewName && "" != strings.TrimSpace(attrView.Name) {
+ caption := "<caption>" + html.EscapeHTMLStr(attrView.Name) + "</caption>"
+ mdTable.SetIALAttr("caption", html.EscapeHTMLStr(caption))
+ }
+ var colStyles []string
+ for _, col := range table.Columns {
+ if avHiddenCol && col.Hidden {
+ continue
+ }
+ style := ""
+ if width := av.FilterWidthValue(col.Width); "" != width {
+ style = "width: " + width + ";"
+ }
+ colStyles = append(colStyles, style)
+ }
+ mdTable.SetIALAttr("colgroup", strings.Join(colStyles, "|"))
+ }
mdTableHead := &ast.Node{Type: ast.NodeTableHead}
mdTable.AppendChild(mdTableHead)
mdTableHeadRow := &ast.Node{Type: ast.NodeTableRow, TableAligns: aligns}
@@ -3646,6 +3664,9 @@ func exportTree(tree *parse.Tree, wysiwyg, richTableCells, keepFold, avHiddenCol
}
cell := &ast.Node{Type: ast.NodeTableCell, TableCellAlign: aligns[alignIndex]}
+ if wysiwyg {
+ cell.SetIALAttr("style", "white-space: nowrap;")
+ }
alignIndex++
name := col.Name
if !wysiwyg {
diff --git a/kernel/model/export_attribute_view_test.go b/kernel/model/export_attribute_view_test.go
index 2cfd30b968..c953e3bb42 100644
--- a/kernel/model/export_attribute_view_test.go
+++ b/kernel/model/export_attribute_view_test.go
@@ -19,9 +19,12 @@ package model
import (
"bytes"
"reflect"
+ "strings"
"testing"
"github.com/88250/lute/ast"
+ "github.com/88250/lute/html"
+ "github.com/88250/lute/render"
"github.com/emirpasic/gods/sets/hashset"
"github.com/siyuan-note/siyuan/kernel/av"
"github.com/siyuan-note/siyuan/kernel/conf"
@@ -29,6 +32,99 @@ import (
"github.com/siyuan-note/siyuan/kernel/util"
)
+func TestAttributeViewExportTablePresentation(t *testing.T) {
+ const boxID = "20261004000000-box0001"
+ setupExportRelatedTest(t, boxID)
+ Conf.Editor = conf.NewEditor()
+ oldLang, oldAttrViewLangs := util.Lang, util.AttrViewLangs
+ util.Lang = "en"
+ util.AttrViewLangs = map[string]map[string]any{
+ "en": {"key": "Key", "select": "Select", "table": "Table"},
+ }
+ t.Cleanup(func() { util.Lang, util.AttrViewLangs = oldLang, oldAttrViewLangs })
+
+ attrView := av.NewAttributeView("20261004000001-av00001")
+ primary := attrView.GetBlockKey()
+ primary.Name = "Long database property name"
+ hidden := av.NewKey(ast.NewNodeID(), "Hidden", "", av.KeyTypeText)
+ visible := av.NewKey(ast.NewNodeID(), "Visible", "", av.KeyTypeText)
+ invalid := av.NewKey(ast.NewNodeID(), "Invalid width", "", av.KeyTypeText)
+ for _, key := range []*av.Key{hidden, visible, invalid} {
+ attrView.KeyValues = append(attrView.KeyValues, &av.KeyValues{Key: key})
+ }
+ view := attrView.Views[0]
+ view.Table.Columns = []*av.ViewTableColumn{
+ {BaseField: &av.BaseField{ID: primary.ID}, Width: "160px"},
+ {BaseField: &av.BaseField{ID: hidden.ID, Hidden: true}, Width: "80px"},
+ {BaseField: &av.BaseField{ID: visible.ID}, Width: "120px", Align: av.TableColumnAlignRight},
+ {BaseField: &av.BaseField{ID: invalid.ID}, Width: "1px; color: red"},
+ }
+ const title = `Database <img src=x onerror=alert(1)> & "title"`
+ for _, tc := range []struct {
+ name, title string
+ hideTitle, wysiwyg, hiddenCol bool
+ }{
+ {"visible title", title, false, true, true},
+ {"hidden title", title, true, true, true},
+ {"empty title", "", false, true, true},
+ {"all columns", title, false, true, false},
+ {"markdown", title, false, false, true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ attrView.Name, view.HideAttrViewName = tc.title, tc.hideTitle
+ if err := av.SaveAttributeView(attrView); err != nil {
+ t.Fatal(err)
+ }
+ tree := treenode.NewTree(boxID, "/20261004000002-doc0001.sy", "/Export", "Export")
+ database := &ast.Node{Type: ast.NodeAttributeView, ID: "20261004000003-avnode1",
+ AttributeViewID: attrView.ID, AttributeViewType: string(av.LayoutTypeTable)}
+ database.SetIALAttr(av.NodeAttrView, view.ID)
+ tree.Root.AppendChild(database)
+ exported, err := exportTree(tree, tc.wysiwyg, false, false, tc.hiddenCol, 0, 0, 0,
+ "", "", "", "", false, "", false, false, nil, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ tables := exported.Root.ChildrenByType(ast.NodeTable)
+ if len(tables) != 1 {
+ t.Fatalf("expected one exported table, got %d", len(tables))
+ }
+ table := tables[0]
+ if !tc.wysiwyg {
+ if table.IALAttr("caption") != "" || table.IALAttr("colgroup") != "" ||
+ table.FirstChild.FirstChild.FirstChild.IALAttr("style") != "" {
+ t.Fatal("Markdown export should not gain HTML presentation attributes")
+ }
+ return
+ }
+ colgroup := "width: 160px;|width: 120px;|"
+ if !tc.hiddenCol {
+ colgroup = "width: 160px;|width: 80px;|width: 120px;|"
+ }
+ if got := table.IALAttr("colgroup"); got != colgroup {
+ t.Fatalf("column widths must match exported columns: %q", got)
+ }
+ engine := NewLute()
+ content := string(render.NewProtyleExportRenderer(exported, engine.RenderOptions, engine.ParseOptions).Render())
+ wantCaption := !tc.hideTitle && tc.title != ""
+ if strings.Contains(content, "<caption>") != wantCaption {
+ t.Fatalf("unexpected caption visibility: %s", content)
+ }
+ if wantCaption && !strings.Contains(content, "<caption>"+html.EscapeHTMLStr(tc.title)+"</caption>") {
+ t.Fatalf("database caption must preserve escaped text: %s", content)
+ }
+ if strings.Contains(content, "<img") || strings.Contains(content, "color: red") {
+ t.Fatalf("title or column width was interpreted as markup: %s", content)
+ }
+ for cell := table.FirstChild.FirstChild.FirstChild; cell != nil; cell = cell.Next {
+ if cell.IALAttr("style") != "white-space: nowrap;" {
+ t.Fatal("exported database headers must not wrap")
+ }
+ }
+ })
+ }
+}
+
func TestGetAttrViewTableAligns(t *testing.T) {
table := &av.Table{Columns: []*av.TableColumn{
{BaseInstanceField: &av.BaseInstanceField{ID: "default"}},