An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Improve primary key display templates in database relation fields https://github.com/siyuan-note/siyuan/issues/19857
Danielb5e3f96491ea
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.syindex 53683f46b6..63ba99a021 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy@@ -3497,7 +3497,7 @@"Children": [{"Type": "NodeText",- "Data": "A display template reads each field's original stored value, not the display result produced by another display template. Filters, sorts, and groups can use either the original value or the template-rendered value. Clear the display template to restore the field's original display."+ "Data": "A display template reads each field's original stored value, not the display result produced by another display template. Filters, sorts, and groups can use either the original value or the template-rendered value. Clear the display template to restore the field's original display. Relation fields follow the display template of the target database's primary key, including empty results, while preserving the original primary key value and relation."}]},diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.syindex cd1fc8ef2a..c4da33cf87 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy@@ -3497,7 +3497,7 @@"Children": [{"Type": "NodeText",- "Data": "显示模板读取各字段的原始存储值,不会读取其他字段的显示模板结果。过滤、排序和分组可选择使用原始值或模板渲染值。清空显示模板即可恢复字段原有的展示方式。"+ "Data": "显示模板读取各字段的原始存储值,不会读取其他字段的显示模板结果。过滤、排序和分组可选择使用原始值或模板渲染值。清空显示模板即可恢复字段原有的展示方式。关联字段会跟随目标数据库主键的显示模板,包括空结果,原始主键值和关联关系保持不变。"}]},diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.syindex b56ffa3743..e844c1e8cf 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy@@ -3497,7 +3497,7 @@"Children": [{"Type": "NodeText",- "Data": "顯示範本讀取各欄位的原始儲存值,不會讀取其他欄位的顯示範本結果。篩選、排序和分組可選擇使用原始值或範本渲染值。清空顯示範本即可還原欄位原本的顯示方式。"+ "Data": "顯示範本讀取各欄位的原始儲存值,不會讀取其他欄位的顯示範本結果。篩選、排序和分組可選擇使用原始值或範本渲染值。清空顯示範本即可還原欄位原本的顯示方式。關聯欄位會依照目標資料庫主鍵的顯示範本呈現,包括空結果,原始主鍵值和關聯關係保持不變。"}]},diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.syindex 97f23a307f..85d0eab9c4 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy@@ -3507,7 +3507,7 @@"Children": [{"Type": "NodeText",- "Data": "表示テンプレートが読み取るのは各フィールドの元の保存値であり、他の表示テンプレートが生成した表示結果ではありません。フィルター、ソート、グループ化では、元の値またはテンプレートレンダリング値を選択できます。表示テンプレートを空にすると、フィールド本来の表示に戻ります。"+ "Data": "表示テンプレートが読み取るのは各フィールドの元の保存値であり、他の表示テンプレートが生成した表示結果ではありません。フィルター、ソート、グループ化では、元の値またはテンプレートレンダリング値を選択できます。表示テンプレートを空にすると、フィールド本来の表示に戻ります。リレーションフィールドには、関連先データベースの主キーの表示テンプレートの結果が表示されます。結果が空の場合もそのまま表示され、元の主キーの値と関連付けは変更されません。"}]},diff --git a/app/src/protyle/render/av/attributeValue.ts b/app/src/protyle/render/av/attributeValue.tsindex b9e9dcc039..7a9a85eb23 100644--- a/app/src/protyle/render/av/attributeValue.ts+++ b/app/src/protyle/render/av/attributeValue.ts@@ -23,6 +23,22 @@ export const getAVTemplateHTML = (content: string) => {return window.DOMPurify.sanitize(content);};+export const genAVRelationHTML = (item: IAVCellValue, rowID: string, showIcon = true, attributePanel = false) => {+ if (!item?.block) {+ return "";+ }+ const useTemplate = hasAVRenderTemplateResult(item);+ const content = useTemplate ? getAVTemplateHTML(item.renderedContent || "") :+ Lute.EscapeHTMLStr(item.block.content || window.siyuan.languages.untitled);+ const templateClass = useTemplate ? " av__celltext--template" : "";+ const storedValue = escapeAttr(encodeURIComponent(JSON.stringify(cloneAVCellValueSnapshot(item))));+ const attributes = `data-row-id="${escapeAttr(rowID)}" data-relation-value="${storedValue}" class="av__cell--relation"`;+ if (item.isDetached) {+ return `<span ${attributes}><span${showIcon ? "" : ' class="fn__none"'}><svg${attributePanel ? ' style="height: 26px"' : ""}><use xlink:href="#iconLine"></use></svg><span class="fn__space--5"></span></span><span class="av__celltext${templateClass}">${content}</span></span>`;+ }+ return `<span ${attributes} data-block-id="${item.block.id}"><span class="b3-menu__avemoji${showIcon ? "" : " fn__none"}" data-unicode="${escapeAttr(item.block.icon || "")}">${getFileTreeIconHTML(item.block.icon, "file")}</span><span data-type="block-ref" data-id="${item.block.id}" data-subtype="${getAVBlockRefSubtype(item)}" class="av__celltext av__celltext--ref${templateClass}">${content}</span></span>`;+};+const AV_TEMPLATE_INTERACTIVE_SELECTOR = ["a[href]","button",@@ -188,14 +204,7 @@ export const genAVValueHTML = (value: IAVCellValue, dateFormat: TAVDateFormat =break;case "relation":value?.relation?.contents?.forEach((item, index) => {- if (item && item.block) {- const rowID = value.relation.blockIDs[index];- if (item?.isDetached) {- html += `<span data-row-id="${rowID}" class="av__cell--relation"><span><svg style="height: 26px"><use xlink:href="#iconLine"></use></svg><span class="fn__space--5"></span></span><span class="av__celltext">${Lute.EscapeHTMLStr(item.block.content || window.siyuan.languages.untitled)}</span></span>`;- } else {- html += `<span data-row-id="${rowID}" class="av__cell--relation" data-block-id="${item.block.id}"><span class="b3-menu__avemoji" data-unicode="${escapeAttr(item.block.icon || "")}">${getFileTreeIconHTML(item.block.icon, "file")}</span><span data-type="block-ref" data-id="${item.block.id}" data-subtype="${getAVBlockRefSubtype(item)}" class="av__celltext av__celltext--ref">${Lute.EscapeHTMLStr(item.block.content || window.siyuan.languages.untitled)}</span></span>`;- }- }+ html += genAVRelationHTML(item, value.relation.blockIDs[index], true, true);});if (html && html.endsWith(", ")) {html = html.substring(0, html.length - 2);diff --git a/app/src/protyle/render/av/cell.ts b/app/src/protyle/render/av/cell.tsindex 38e1c7d364..c6efd8528f 100644--- a/app/src/protyle/render/av/cell.ts+++ b/app/src/protyle/render/av/cell.ts@@ -12,7 +12,7 @@ import * as dayjs from "dayjs";import {unicode2Emoji} from "../../../emoji";import {getFileTreeIconHTML} from "../../../emoji/fileTreeIcon";import {getColIconByType, getColId} from "./col";-import {genAVValueHTML, getAVTemplateHTML} from "./attributeValue";+import {genAVRelationHTML, genAVValueHTML, getAVTemplateHTML} from "./attributeValue";import {Constants} from "../../../constants";import {hintRef} from "../../hint/extend";import {getAssetExtension, getAssetName} from "../../../util/pathName";@@ -169,6 +169,10 @@ export const genCellValueByElement = (colType: TAVCol, cellElement: HTMLElement)Array.from(cellElement.querySelectorAll(".av__cell--relation")).forEach((relationItem: HTMLElement) => {const item = relationItem.querySelector(".av__celltext") as HTMLElement;blockIDs.push(relationItem.dataset.rowId);+ if (relationItem.dataset.relationValue) {+ contents.push(JSON.parse(decodeURIComponent(relationItem.dataset.relationValue)));+ return;+ }contents.push({isDetached: !item.classList.contains("av__celltext--ref"),block: {@@ -1341,15 +1345,7 @@ export const renderCell = (cellValue: IAVCellValue, rowIndex = 0, showIcon = tru}} else if (cellValue.type === "relation") {cellValue?.relation?.contents?.forEach((item, index) => {- if (item && item.block) {- const rowID = cellValue.relation.blockIDs[index];- if (item?.isDetached) {- text += `<span data-row-id="${rowID}" class="av__cell--relation"><span${showIcon ? "" : ' class="fn__none"'}><svg><use xlink:href="#iconLine"></use></svg><span class="fn__space--5"></span></span><span class="av__celltext">${Lute.EscapeHTMLStr(item.block.content || window.siyuan.languages.untitled)}</span></span>`;- } else {- // data-block-id 用于更新 emoji- text += `<span data-row-id="${rowID}" class="av__cell--relation" data-block-id="${item.block.id}"><span class="b3-menu__avemoji${showIcon ? "" : " fn__none"}" data-unicode="${escapeAttr(item.block.icon || "")}">${getFileTreeIconHTML(item.block.icon, "file")}</span><span data-type="block-ref" data-id="${item.block.id}" data-subtype="${getAVBlockRefSubtype(item)}" class="av__celltext av__celltext--ref">${Lute.EscapeHTMLStr(item.block.content || window.siyuan.languages.untitled)}</span></span>`;- }- }+ text += genAVRelationHTML(item, cellValue.relation.blockIDs[index], showIcon);});if (text && text.endsWith(", ")) {text = text.substring(0, text.length - 2);diff --git a/app/src/protyle/render/av/cellValue.ts b/app/src/protyle/render/av/cellValue.tsindex 6433c41afb..6815e9918f 100644--- a/app/src/protyle/render/av/cellValue.ts+++ b/app/src/protyle/render/av/cellValue.ts@@ -43,7 +43,7 @@ export const createEmptyAVValue = (keyID: string, type: TAVCol, blockID?: stringexport const hasAVRenderTemplateResult = (value: IAVCellValue, renderTemplate?: string) =>value.type !== "template" &&- (typeof value.renderedContent === "string" || Boolean(renderTemplate?.trim()));+ (value.hasRenderTemplate || typeof value.renderedContent === "string" || Boolean(renderTemplate?.trim()));export const cellValueIsEmpty = (value: IAVCellValue, useRenderedContent = false, renderTemplate?: string) => {if (useRenderedContent && hasAVRenderTemplateResult(value, renderTemplate)) {@@ -129,7 +129,8 @@ export const genEmptyAVCellValue = (colType: TAVCol): IAVCellValue => {};export const cloneAVCellValueSnapshot = (value: IAVCellValue): IAVCellValue => {- const snapshot = JSON.parse(JSON.stringify(value, (key, item) => key === "renderedContent" ? undefined : item)) as IAVCellValue;+ const snapshot = JSON.parse(JSON.stringify(value, (key, item) =>+ ["renderedContent", "hasRenderTemplate"].includes(key) ? undefined : item)) as IAVCellValue;if ((snapshot.type === "mSelect" || snapshot.type === "select") && !snapshot.mSelect) {snapshot.mSelect = [];} else if (snapshot.type === "mAsset" && !snapshot.mAsset) {diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex dec0ac3cf9..f64cc7107e 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -396,7 +396,7 @@ export type AVUnavailableNotebook = { "unavailableNotebook": true; };export type AVUpdated = { "includeTime": boolean; };-export type AVValue = { "block"?: AVValueBlock; "blockID"?: string; "checkbox"?: AVValueCheckbox; "created"?: AVValueCreated; "createdAt"?: number; "date"?: AVValueDate; "email"?: AVValueEmail; "id"?: string; "isDetached"?: boolean; "keyID"?: string; "mAsset"?: Array<AVValueAsset | null>; "mSelect"?: Array<AVValueSelect | null>; "number"?: AVValueNumber; "phone"?: AVValuePhone; "relation"?: AVValueRelation; "renderedContent"?: string; "rollup"?: AVValueRollup; "template"?: AVValueTemplate; "text"?: AVValueText; "type"?: "block" | "text" | "number" | "date" | "select" | "mSelect" | "url" | "email" | "phone" | "mAsset" | "template" | "created" | "updated" | "checkbox" | "relation" | "rollup" | "lineNumber"; "updated"?: AVValueUpdated; "updatedAt"?: number; "url"?: AVValueURL; };+export type AVValue = { "block"?: AVValueBlock; "blockID"?: string; "checkbox"?: AVValueCheckbox; "created"?: AVValueCreated; "createdAt"?: number; "date"?: AVValueDate; "email"?: AVValueEmail; "hasRenderTemplate"?: boolean; "id"?: string; "isDetached"?: boolean; "keyID"?: string; "mAsset"?: Array<AVValueAsset | null>; "mSelect"?: Array<AVValueSelect | null>; "number"?: AVValueNumber; "phone"?: AVValuePhone; "relation"?: AVValueRelation; "renderedContent"?: string; "rollup"?: AVValueRollup; "template"?: AVValueTemplate; "text"?: AVValueText; "type"?: "block" | "text" | "number" | "date" | "select" | "mSelect" | "url" | "email" | "phone" | "mAsset" | "template" | "created" | "updated" | "checkbox" | "relation" | "rollup" | "lineNumber"; "updated"?: AVValueUpdated; "updatedAt"?: number; "url"?: AVValueURL; };export type AVValueAsset = { "content": string; "name": string; "type": "file" | "image"; };@@ -424,7 +424,7 @@ export type AVValueEmail = { "content": string; };export type AVValueEmailInput = { "content"?: string | null; };-export type AVValueInput = { "block"?: AVValueBlockInput | null; "blockID"?: string | null; "checkbox"?: AVValueCheckboxInput | null; "created"?: AVValueCreatedInput | null; "createdAt"?: number | null; "date"?: AVValueDateInput | null; "email"?: AVValueEmailInput | null; "id"?: string | null; "isDetached"?: boolean | null; "keyID"?: string | null; "mAsset"?: Array<AVValueAssetInput | null> | null; "mSelect"?: Array<AVValueSelectInput | null> | null; "number"?: AVValueNumberInput | null; "phone"?: AVValuePhoneInput | null; "relation"?: AVValueRelationInput | null; "renderedContent"?: string | null; "rollup"?: AVValueRollupInput | null; "template"?: AVValueTemplateInput | null; "text"?: AVValueTextInput | null; "type"?: "block" | "text" | "number" | "date" | "select" | "mSelect" | "url" | "email" | "phone" | "mAsset" | "template" | "created" | "updated" | "checkbox" | "relation" | "rollup" | "lineNumber"; "updated"?: AVValueUpdatedInput | null; "updatedAt"?: number | null; "url"?: AVValueURLInput | null; };+export type AVValueInput = { "block"?: AVValueBlockInput | null; "blockID"?: string | null; "checkbox"?: AVValueCheckboxInput | null; "created"?: AVValueCreatedInput | null; "createdAt"?: number | null; "date"?: AVValueDateInput | null; "email"?: AVValueEmailInput | null; "hasRenderTemplate"?: boolean | null; "id"?: string | null; "isDetached"?: boolean | null; "keyID"?: string | null; "mAsset"?: Array<AVValueAssetInput | null> | null; "mSelect"?: Array<AVValueSelectInput | null> | null; "number"?: AVValueNumberInput | null; "phone"?: AVValuePhoneInput | null; "relation"?: AVValueRelationInput | null; "renderedContent"?: string | null; "rollup"?: AVValueRollupInput | null; "template"?: AVValueTemplateInput | null; "text"?: AVValueTextInput | null; "type"?: "block" | "text" | "number" | "date" | "select" | "mSelect" | "url" | "email" | "phone" | "mAsset" | "template" | "created" | "updated" | "checkbox" | "relation" | "rollup" | "lineNumber"; "updated"?: AVValueUpdatedInput | null; "updatedAt"?: number | null; "url"?: AVValueURLInput | null; };export type AVValueNumber = { "content": number; "format": string; "formattedContent": string; "isNotEmpty": boolean; };diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.tsindex 5cbe4c937b..9027a3c226 100644--- a/app/src/types/index.d.ts+++ b/app/src/types/index.d.ts@@ -1431,6 +1431,7 @@ interface IAVCellValue {blockID?: string // 为 row idtype?: TAVCol,renderedContent?: string,+ hasRenderTemplate?: boolean,isDetached?: boolean,text?: {content: string,diff --git a/app/tests/avRelationTemplate.test.js b/app/tests/avRelationTemplate.test.jsnew file mode 100644index 0000000000..728e2d1927--- /dev/null+++ b/app/tests/avRelationTemplate.test.js@@ -0,0 +1,117 @@+const assert = require("node:assert/strict");+const {readFileSync, mkdtempSync, rmSync} = require("node:fs");+const path = require("node:path");+const os = require("node:os");++const runCases = sources => {+ const assert = require("node:assert/strict");+ const escape = text => String(text).replace(/&/g, "&").replace(/</g, "<")+ .replace(/>/g, ">").replace(/"/g, """);+ window.Lute = {EscapeHTMLStr: escape};+ window.siyuan = {languages: {untitled: "Untitled"}, config: {editor: {allowHTMLBLockScript: false}}};+ const sanitized = [];+ window.DOMPurify = {sanitize: content => {+ sanitized.push(content);+ return content;+ }};+ const dependencies = {+ "../../../util/escape": {escapeAttr: escape, escapeHtml: escape},+ "../../../emoji/fileTreeIcon": {getFileTreeIconHTML: () => ""},+ "../../../util/hostCapabilities": {getHostCapabilities: () => ({remoteKernel: true})},+ };+ const load = name => {+ if (!dependencies[name]) {+ const exports = {};+ dependencies[name] = exports;+ if (sources[name]) {+ new Function("require", "exports", sources[name])(load, exports);+ }+ }+ return dependencies[name];+ };+ const {renderCell, genCellValueByElement} = load("./cell");+ const {genAVValueHTML, getAVTemplateInteractiveElement} = load("./attributeValue");+ for (const isDetached of [true, false]) {+ for (const renderedContent of [undefined, "", '<b>Formatted</b><a href="https://example.com">Link</a>']) {+ const item = {type: "block", id: "value", keyID: "primary", blockID: "row", isDetached,+ block: {content: "Raw <title>", id: "bound-block", refSubtype: "s"},+ ...(renderedContent === undefined ? {} : {hasRenderTemplate: true}),+ ...(renderedContent ? {renderedContent} : {})};+ const relation = {type: "relation", relation: {blockIDs: ["row"], contents: [item]}};+ for (const layout of ["table", "list", "calendar", "gallery", "kanban", "attributes"]) {+ const cell = document.createElement("div");+ cell.innerHTML = layout === "attributes" ? genAVValueHTML(relation) :+ renderCell(relation, 0, true, layout);+ document.body.replaceChildren(cell);+ const label = cell.querySelector(".av__celltext");+ assert.equal(label.textContent, renderedContent === undefined ? "Raw <title>" :+ renderedContent ? "FormattedLink" : "");+ assert.equal(label.classList.contains("av__celltext--template"), renderedContent !== undefined);+ const recovered = genCellValueByElement("relation", cell);+ assert.deepEqual(recovered.relation.blockIDs, ["row"]);+ assert.equal(recovered.relation.contents[0].block.content, "Raw <title>");+ assert.equal(recovered.relation.contents[0].blockID, "row");+ assert.equal(recovered.relation.contents[0].hasRenderTemplate, undefined);+ assert.equal(recovered.relation.contents[0].renderedContent, undefined);+ if (!isDetached) {+ assert.equal(label.dataset.id, "bound-block");+ assert.equal(label.dataset.subtype, "s");+ }+ if (renderedContent) {+ assert.equal(getAVTemplateInteractiveElement(label.querySelector("a")), label.querySelector("a"));+ }+ }+ }+ }+ assert.ok(sanitized.includes(""));+ assert.ok(sanitized.some(content => content.includes("<b>Formatted</b>")));+};++const runElectron = async () => {+ const {app, BrowserWindow} = require("electron");+ app.setPath("userData", process.argv[2]);+ app.commandLine.appendSwitch("disable-gpu");+ await app.whenReady();+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false}});+ let exitCode = 0;+ try {+ const ts = require("typescript");+ const sources = Object.fromEntries(["cell", "cellValue", "attributeValue"].map(name => ["./" + name,+ ts.transpileModule(readFileSync(path.join(__dirname, `../src/protyle/render/av/${name}.ts`), "utf8"),+ {compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020}}).outputText]));+ await win.loadURL("data:text/html,<html><body></body></html>");+ await win.webContents.executeJavaScript(`(${runCases.toString()})(${JSON.stringify(sources)})`);+ console.log("AV relation template cases passed");+ } catch (error) {+ console.error(error);+ exitCode = 1;+ } finally {+ win.destroy();+ app.exit(exitCode);+ }+};++if (process.versions.electron && process.type === "browser") {+ runElectron().catch(error => {+ console.error(error);+ require("electron").app.exit(1);+ });+} else {+ require("node:test").it("renders related primary templates while retaining raw values and navigation", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 45000,+ }, async () => {+ const env = {...process.env};+ delete env.ELECTRON_RUN_AS_NODE;+ const profile = mkdtempSync(path.join(os.tmpdir(), "siyuan-av-relation-template-"));+ try {+ const {stdout} = await require("node:util").promisify(require("node:child_process").execFile)(+ require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 40000});+ assert.match(stdout, /AV relation template cases passed/);+ } finally {+ assert.equal(path.dirname(path.resolve(profile)), path.resolve(os.tmpdir()));+ assert.ok(path.basename(profile).startsWith("siyuan-av-relation-template-"));+ rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});+ }+ });+}diff --git a/kernel/api/av_contract_mapping.go b/kernel/api/av_contract_mapping.goindex ddf3ad19a6..033fc8f327 100644--- a/kernel/api/av_contract_mapping.go+++ b/kernel/api/av_contract_mapping.go@@ -119,29 +119,30 @@ func toContractAVValue(value *av.Value) *apicontract.AVValue {return nil}return &apicontract.AVValue{- ID: value.ID,- KeyID: value.KeyID,- BlockID: value.BlockID,- Type: string(value.Type),- IsDetached: value.IsDetached,- CreatedAt: value.CreatedAt,- UpdatedAt: value.UpdatedAt,- Block: toContractAVValueBlock(value.Block),- Text: toContractAVValueText(value.Text),- Number: toContractAVValueNumber(value.Number),- Date: toContractAVValueDate(value.Date),- MSelect: avContractSlice(value.MSelect, func(value *av.ValueSelect) *apicontract.AVValueSelect { return toContractAVValueSelect(value) }),- URL: toContractAVValueURL(value.URL),- Email: toContractAVValueEmail(value.Email),- Phone: toContractAVValuePhone(value.Phone),- MAsset: avContractSlice(value.MAsset, func(value *av.ValueAsset) *apicontract.AVValueAsset { return toContractAVValueAsset(value) }),- Template: toContractAVValueTemplate(value.Template),- Created: toContractAVValueCreated(value.Created),- Updated: toContractAVValueUpdated(value.Updated),- Checkbox: toContractAVValueCheckbox(value.Checkbox),- Relation: toContractAVValueRelation(value.Relation),- Rollup: toContractAVValueRollup(value.Rollup),- RenderedContent: value.RenderedContent,+ ID: value.ID,+ KeyID: value.KeyID,+ BlockID: value.BlockID,+ Type: string(value.Type),+ IsDetached: value.IsDetached,+ CreatedAt: value.CreatedAt,+ UpdatedAt: value.UpdatedAt,+ Block: toContractAVValueBlock(value.Block),+ Text: toContractAVValueText(value.Text),+ Number: toContractAVValueNumber(value.Number),+ Date: toContractAVValueDate(value.Date),+ MSelect: avContractSlice(value.MSelect, func(value *av.ValueSelect) *apicontract.AVValueSelect { return toContractAVValueSelect(value) }),+ URL: toContractAVValueURL(value.URL),+ Email: toContractAVValueEmail(value.Email),+ Phone: toContractAVValuePhone(value.Phone),+ MAsset: avContractSlice(value.MAsset, func(value *av.ValueAsset) *apicontract.AVValueAsset { return toContractAVValueAsset(value) }),+ Template: toContractAVValueTemplate(value.Template),+ Created: toContractAVValueCreated(value.Created),+ Updated: toContractAVValueUpdated(value.Updated),+ Checkbox: toContractAVValueCheckbox(value.Checkbox),+ Relation: toContractAVValueRelation(value.Relation),+ Rollup: toContractAVValueRollup(value.Rollup),+ RenderedContent: value.RenderedContent,+ HasRenderTemplate: value.HasRenderTemplate,}}func fromContractAVValue(value *apicontract.AVValue) *av.Value {diff --git a/kernel/api/contract_av_test.go b/kernel/api/contract_av_test.goindex 36980c0145..b08a2a5656 100644--- a/kernel/api/contract_av_test.go+++ b/kernel/api/contract_av_test.go@@ -88,6 +88,11 @@ func TestAVContractTransportMapping(t *testing.T) {assertAVContractJSONEqual(t, view, avContractView(view))}assertAVContractJSONEqual(t, value, toContractAVValue(value))+ for _, content := range []string{"", "<b>display</b>"} {+ value.Relation.Contents = []*av.Value{{Type: av.KeyTypeBlock, Block: &av.ValueBlock{Content: "original"},+ HasRenderTemplate: true, RenderedContent: content}}+ assertAVContractJSONEqual(t, value, toContractAVValue(value))+ }assertAVContractJSONEqual(t, &av.ViewTableColumn{BaseField: &av.BaseField{ID: "key", Calc: &av.FieldCalc{}}, Calc: nil}, toContractAVViewTableColumn(&av.ViewTableColumn{BaseField: &av.BaseField{ID: "key", Calc: &av.FieldCalc{}}, Calc: nil}))fixture := setupAttributeViewContextFilterAPITest(t)assertAVContractJSONEqual(t, model.NewAttributeViewData(fixture.attrView), toContractAVAttributeViewData(model.NewAttributeViewData(fixture.attrView)))diff --git a/kernel/apicontract/av_types.go b/kernel/apicontract/av_types.goindex 8612d22353..aab5d0ff0a 100644--- a/kernel/apicontract/av_types.go+++ b/kernel/apicontract/av_types.go@@ -71,6 +71,9 @@ type AVValue struct {Relation *AVValueRelation `json:"relation,omitempty" api:"optional,nullable"`Rollup *AVValueRollup `json:"rollup,omitempty" api:"optional,nullable"`RenderedContent string `json:"renderedContent,omitempty" api:"optional,nullable"`+ // 显示模板已计算时为 true,空结果仍以模板显示;关联内容使用目标主键模板,原始 block 内容和标识不变。+ // 这是运行时显示信息,不写入数据库文件;旧响应未包含此字段时沿用 renderedContent 和字段模板配置。+ HasRenderTemplate bool `json:"hasRenderTemplate,omitempty" api:"optional,nullable"`}type AVValueBlock struct {diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex d83be06015..54ab5d92d7 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -11070,6 +11070,9 @@"email": {"$ref": "#/$defs/AVValueEmail"},+ "hasRenderTemplate": {+ "type": "boolean"+ },"id": {"type": "string"},@@ -11669,6 +11672,16 @@}]},+ "hasRenderTemplate": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },"id": {"anyOf": [{diff --git a/kernel/av/render_template.go b/kernel/av/render_template.goindex ecb2c69e00..58b5913d4a 100644--- a/kernel/av/render_template.go+++ b/kernel/av/render_template.go@@ -17,8 +17,9 @@package avtype renderedContentBinding struct {- value *Value- content string+ value *Value+ content string+ hasTemplate bool}// CloneStoredValue 复制字段存储值,并递归剥离运行时显示模板结果。@@ -28,6 +29,7 @@ func CloneStoredValue(value *Value) (ret *Value) {}cloned := *valuecloned.RenderedContent = ""+ cloned.HasRenderTemplate = falseret = &clonedif nil != value.Relation {relation := *value.Relation@@ -58,16 +60,19 @@ func (av *AttributeView) suspendRenderedContents() (restore func()) {var bindings []renderedContentBindingif nil != av {av.visitPersistedValues(func(value *Value) {- if "" == value.RenderedContent {+ if "" == value.RenderedContent && !value.HasRenderTemplate {return}- bindings = append(bindings, renderedContentBinding{value: value, content: value.RenderedContent})+ bindings = append(bindings, renderedContentBinding{value: value, content: value.RenderedContent,+ hasTemplate: value.HasRenderTemplate})value.RenderedContent = ""+ value.HasRenderTemplate = false})}return func() {for _, binding := range bindings {binding.value.RenderedContent = binding.content+ binding.value.HasRenderTemplate = binding.hasTemplate}}}diff --git a/kernel/av/render_template_test.go b/kernel/av/render_template_test.goindex bc9d4fe6a9..51e015d1a6 100644--- a/kernel/av/render_template_test.go+++ b/kernel/av/render_template_test.go@@ -29,7 +29,8 @@ func TestSuspendRenderedContents(t *testing.T) {RenderedContent: "<strong>rendered</strong>",}nestedValue := &Value{Type: KeyTypeText, Text: &ValueText{Content: "nested"}, RenderedContent: "nested rendered"}- storedValue.Relation = &ValueRelation{Contents: []*Value{nestedValue}}+ emptyValue := &Value{Type: KeyTypeBlock, Block: &ValueBlock{Content: "original"}, HasRenderTemplate: true}+ storedValue.Relation = &ValueRelation{Contents: []*Value{nestedValue, emptyValue}}filterValue := &Value{Type: KeyTypeText, Text: &ValueText{Content: "filter"}, RenderedContent: "filter rendered"}attrView := &AttributeView{KeyValues: []*KeyValues{{Key: &Key{ID: "key", Type: KeyTypeText}, Values: []*Value{storedValue}}},@@ -51,7 +52,7 @@ func TestSuspendRenderedContents(t *testing.T) {if nil != err {t.Fatal(err)}- if bytes.Contains(data, []byte("renderedContent")) {+ if bytes.Contains(data, []byte("renderedContent")) || bytes.Contains(data, []byte("hasRenderTemplate")) {t.Fatalf("rendered content leaked into persisted attribute view: %s", data)}if "" != storedValue.RenderedContent || "" != nestedValue.RenderedContent || "" != filterValue.RenderedContent {@@ -59,6 +60,9 @@ func TestSuspendRenderedContents(t *testing.T) {}restore()+ if !emptyValue.HasRenderTemplate {+ t.Fatal("empty template result marker was not restored")+ }if "<strong>rendered</strong>" != storedValue.RenderedContent || "nested rendered" != nestedValue.RenderedContent ||"filter rendered" != filterValue.RenderedContent {t.Fatal("rendered content was not restored after serialization")@@ -70,12 +74,13 @@ func TestCloneStoredValueRemovesRenderedContents(t *testing.T) {Type: KeyTypeRollup,RenderedContent: "outer",Rollup: &ValueRollup{Contents: []*Value{{- Type: KeyTypeText, Text: &ValueText{Content: "stored"}, RenderedContent: "inner",+ Type: KeyTypeText, Text: &ValueText{Content: "stored"}, RenderedContent: "inner", HasRenderTemplate: true,}}},}cloned := CloneStoredValue(value)- if nil == cloned || "" != cloned.RenderedContent || "" != cloned.Rollup.Contents[0].RenderedContent {+ if nil == cloned || "" != cloned.RenderedContent || "" != cloned.Rollup.Contents[0].RenderedContent ||+ cloned.Rollup.Contents[0].HasRenderTemplate {t.Fatalf("rendered content leaked into stored clone: %+v", cloned)}if "outer" != value.RenderedContent || "inner" != value.Rollup.Contents[0].RenderedContent {diff --git a/kernel/av/value.go b/kernel/av/value.goindex a13c46f871..40285899f5 100644--- a/kernel/av/value.go+++ b/kernel/av/value.go@@ -66,8 +66,9 @@ type Value struct {Relation *ValueRelation `json:"relation,omitempty"`Rollup *ValueRollup `json:"rollup,omitempty"`- RenderedContent string `json:"renderedContent,omitempty"` // 显示模板的运行时渲染结果,保存时剥离- IsRenderAutoFill bool `json:"-"` // 标识是否是渲染阶段自动填充的值,保存数据的时候要删掉+ RenderedContent string `json:"renderedContent,omitempty"` // 显示模板的运行时渲染结果,保存时剥离+ HasRenderTemplate bool `json:"hasRenderTemplate,omitempty"` // 标识已计算显示模板,包括空结果,保存时剥离+ IsRenderAutoFill bool `json:"-"` // 标识是否是渲染阶段自动填充的值,保存数据的时候要删掉}func (value *Value) SetUpdatedAt(mills int64) {diff --git a/kernel/sql/av.go b/kernel/sql/av.goindex bcfcfd535b..255ff9f38b 100644--- a/kernel/sql/av.go+++ b/kernel/sql/av.go@@ -45,8 +45,9 @@ type GroupViewRenderSource struct {// AttributeViewRenderContext 收集一次属性视图渲染期间产生的模板错误。type AttributeViewRenderContext struct {- templateErrors map[string]*attributeViewTemplateRenderError- ReadOnly bool // 预览只允许修正内存副本,不保存缺失字段等订正结果。+ templateErrors map[string]*attributeViewTemplateRenderError+ renderingRelationTemplates bool+ ReadOnly bool // 预览只允许修正内存副本,不保存缺失字段等订正结果。}type attributeViewTemplateRenderError struct {@@ -702,6 +703,7 @@ func fillAttributeViewAutoGeneratedValues(attrView *av.AttributeView, collection// 渲染关联blocksCache := map[string]map[string]*av.Value{}+ relationValues := map[string][]*av.Value{}normalizedBlockRefSubtypes := map[string]bool{attrView.ID: true}for _, item := range collection.GetItems() {for _, value := range item.GetValues() {@@ -714,6 +716,7 @@ func fillAttributeViewAutoGeneratedValues(attrView *av.AttributeView, collectionif nil != relKey && nil != relKey.Relation {destAv := loadRelatedAttributeView(attrView, relKey.Relation.AvID, cachedAttrViews)if nil != destAv {+ relationValues[destAv.ID] = append(relationValues[destAv.ID], value)if !normalizedBlockRefSubtypes[destAv.ID] {fillAttributeViewBlockRefSubtypes(destAv, nil)normalizedBlockRefSubtypes[destAv.ID] = true@@ -739,6 +742,13 @@ func fillAttributeViewAutoGeneratedValues(attrView *av.AttributeView, collection}}+ // 在目标行上下文中计算关联主键显示,模板读取的关联值仍保持原始内容。+ if !renderContext.renderingRelationTemplates {+ for destAvID, values := range relationValues {+ fillRelationPrimaryTemplates(cachedAttrViews[destAvID], values, depth, cachedAttrViews, renderContext)+ }+ }+// 渲染汇总rollupRenderContexts := map[string]*av.RollupRenderContext{}for _, field := range collection.GetFields() {@@ -994,6 +1004,7 @@ func fillAttributeViewTemplateValues(attrView *av.AttributeView, view *av.View,for _, value := range item.GetValues() {if nil != value {value.RenderedContent = ""+ value.HasRenderTemplate = false}}}@@ -1052,6 +1063,7 @@ func fillAttributeViewTemplateValues(attrView *av.AttributeView, view *av.View,if isRenderTemplate {value.RenderedContent = content+ value.HasRenderTemplate = true} else {value.Template.Content = contentitems[item.GetID()] = append(keyValues, &av.KeyValues{Key: templateKey, Values: []*av.Value{value}})diff --git a/kernel/sql/av_relation_template.go b/kernel/sql/av_relation_template.gonew file mode 100644index 0000000000..efff0ae261--- /dev/null+++ b/kernel/sql/av_relation_template.go@@ -0,0 +1,77 @@+package sql++import (+ "strings"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/av"+)++// fillRelationPrimaryTemplates 只为已关联条目计算目标主键显示模板,不受目标视图布局、过滤和分页影响。+func fillRelationPrimaryTemplates(target *av.AttributeView, relations []*av.Value, depth *int,+ cachedAttrViews map[string]*av.AttributeView, context *AttributeViewRenderContext) {+ if nil == target || context.renderingRelationTemplates {+ return+ }+ primary := target.GetBlockKey()+ if nil == primary || "" == strings.TrimSpace(primary.RenderTemplate) {+ return+ }++ itemIDs := map[string]bool{}+ for _, relation := range relations {+ for _, content := range relation.Relation.Contents {+ itemIDs[content.BlockID] = true+ }+ }+ if 0 == len(itemIDs) {+ return+ }++ // 使用独立副本,避免自关联的嵌套渲染修改外层正在计算的字段值。+ cloned := *target+ cloned.KeyValues = nil+ cloned.RenderedViewables = nil+ view := &av.View{ID: ast.NewNodeID(), LayoutType: av.LayoutTypeTable, Table: av.NewLayoutTable()}+ for itemID := range itemIDs {+ view.GroupItemIDs = append(view.GroupItemIDs, itemID)+ }+ for _, keyValues := range target.KeyValues {+ key := *keyValues.Key+ if primary.ID != key.ID {+ key.RenderTemplate = ""+ }+ copied := &av.KeyValues{Key: &key}+ for _, value := range keyValues.Values {+ copied.Values = append(copied.Values, av.CloneStoredValue(value).Clone())+ }+ cloned.KeyValues = append(cloned.KeyValues, copied)+ view.Table.Columns = append(view.Table.Columns, &av.ViewTableColumn{BaseField: &av.BaseField{ID: key.ID}})+ }+ cache := make(map[string]*av.AttributeView, len(cachedAttrViews))+ for id, attrView := range cachedAttrViews {+ cache[id] = attrView+ }+ cache[target.ID] = &cloned++ // 显示模板只能读取原始值,计算目标模板时无需再次展开关联主键显示模板。+ context.renderingRelationTemplates = true+ defer func() { context.renderingRelationTemplates = false }()+ nestedDepth := *depth+ rendered := renderView(&cloned, view, "", &nestedDepth, cache, false, false, context)+ if nil == rendered {+ return+ }+ collection := rendered.(av.Collection)+ values := map[string]*av.Value{}+ for _, item := range collection.GetItems() {+ values[item.GetID()] = item.GetBlockValue()+ }+ for _, relation := range relations {+ for i, content := range relation.Relation.Contents {+ if value := values[content.BlockID]; nil != value {+ relation.Relation.Contents[i] = value+ }+ }+ }+}diff --git a/kernel/sql/av_relation_template_test.go b/kernel/sql/av_relation_template_test.gonew file mode 100644index 0000000000..9827cd3417--- /dev/null+++ b/kernel/sql/av_relation_template_test.go@@ -0,0 +1,76 @@+package sql++import (+ "testing"++ "github.com/siyuan-note/siyuan/kernel/av"+)++func TestRelationPrimaryRenderTemplate(t *testing.T) {+ const firstID = "20260926000000-first01"+ const secondID = "20260926000000-second1"+ for _, templateContent := range []string{+ "<b>.action{.Computed}</b> .action{index .Related 0}",+ ".action{if false}hidden.action{end}",+ ".action{if}",+ "",+ } {+ t.Run(templateContent, func(t *testing.T) {+ primary := av.NewKey("primary", "Primary", "", av.KeyTypeBlock)+ primary.RenderTemplate = templateContent+ number := av.NewKey("number", "Number", "", av.KeyTypeNumber)+ computed := av.NewKey("computed", "Computed", "", av.KeyTypeTemplate)+ computed.Template = ".action{mulf .Number 2}"+ related := av.NewKey("related", "Related", "", av.KeyTypeRelation)+ related.Relation = &av.Relation{AvID: "target"}+ first := newTemplateErrorTestBlockValue(primary.ID, firstID, "Original")+ second := newTemplateErrorTestBlockValue(primary.ID, secondID, "Other")+ selfRelation := &av.Value{ID: "self", KeyID: related.ID, BlockID: firstID, Type: av.KeyTypeRelation,+ Relation: &av.ValueRelation{BlockIDs: []string{secondID}}}+ target := &av.AttributeView{ID: "target", KeyValues: []*av.KeyValues{+ {Key: primary, Values: []*av.Value{first, second}},+ {Key: number, Values: []*av.Value{{ID: "number-value", KeyID: number.ID, BlockID: firstID,+ Type: av.KeyTypeNumber, Number: &av.ValueNumber{Content: 21, IsNotEmpty: true}}}},+ {Key: computed},+ {Key: related, Values: []*av.Value{selfRelation}},+ }}+ // 目标视图未包含关联条目,也未展示模板依赖列。+ target.Views = []*av.View{{ID: "filtered", LayoutType: av.LayoutTypeTable,+ Table: av.NewLayoutTable(), GroupItemIDs: []string{secondID}, PageSize: 1}}+ context := NewAttributeViewRenderContext()+ depth := 2+ for range 10 {+ relation := &av.Value{Type: av.KeyTypeRelation, KeyID: related.ID, BlockID: firstID,+ Relation: &av.ValueRelation{BlockIDs: []string{firstID}}}+ source := &av.AttributeView{ID: "source", KeyValues: []*av.KeyValues{+ {Key: primary, Values: []*av.Value{first}},+ {Key: related, Values: []*av.Value{relation}},+ }}+ collection := newRenderTemplateTestCollection(av.LayoutTypeTable, firstID, first, relation)+ fillAttributeViewAutoGeneratedValues(source, collection, nil, &depth,+ map[string]*av.AttributeView{target.ID: target, source.ID: source}, context)+ value := relation.Relation.Contents[0]+ want := ""+ if templateContent == "<b>.action{.Computed}</b> .action{index .Related 0}" {+ want = "<b>42</b> Other"+ }+ if value.RenderedContent != want || value.HasRenderTemplate != (templateContent != "") {+ t.Fatalf("unexpected relation display: %+v", value)+ }+ if value.Block.Content != "Original" || value.BlockID != firstID || value.ID != first.ID {+ t.Fatalf("relation identity or stored value changed: %+v", value)+ }+ }+ if depth != 2 || context.renderingRelationTemplates {+ t.Fatal("nested template rendering consumed the outer recursion budget")+ }+ if first.HasRenderTemplate || first.RenderedContent != "" || len(selfRelation.Relation.Contents) != 0 ||+ len(target.KeyValues[2].Values) != 0 {+ t.Fatal("target template rendering changed source values")+ }+ if templateContent == ".action{if}" && len(context.sortedTemplateErrors()) != 1 {+ t.Fatal("relation template errors were not collected")+ }+ })+ }+}