Skip to content

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

:sparkles: Improve database entry icon presets and binding https://github.com/siyuan-note/siyuan/issues/19953

Daniel4368cb257e73
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.sy
index 3f9205b1f7..14b2cbff39 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
@@ -7,7 +7,7 @@
"id": "20240208172514-9dsv6na",
"title": "Database",
"type": "doc",
- "updated": "20260929123717"
+ "updated": "20260930140000"
},
"Children": [
{
@@ -59,12 +59,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260929105001-d3q9qik",
- "updated": "20260929105001"
+ "updated": "20260930140000"
},
"Children": [
{
"Type": "NodeText",
- "Data": "Unbound entries can have their own icons. Click the icon beside the primary-key value or in the entry details to change or remove it. Entries without a custom icon show a neutral default icon, and the view's icon visibility setting still applies."
+ "Data": "Unbound entries can have their own icons. Click the icon beside the primary-key value, in the entry details, or in a relation field to change or remove it. Item templates can preset icons for both unbound and document entries. Unbound entries without a custom icon show a short horizontal line, and the view's icon visibility setting still applies."
}
]
},
@@ -73,12 +73,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260929105001-pdids8d",
- "updated": "20260929105001"
+ "updated": "20260930140000"
},
"Children": [
{
"Type": "NodeText",
- "Data": "Binding or rebinding an entry replaces its icon with the target block's icon. Bound entries continue to share their icons with the bound blocks; for a document block, this is the document icon. Unbinding preserves the last displayed icon, which can then be changed independently."
+ "Data": "When binding or rebinding to a regular block without a custom icon, the block inherits the entry's icon. If the block already has an icon, or is an existing document, its own icon is used. A document created during binding inherits the entry's custom icon; if none is set, the document template's icon is used. Bound entries share icons with their bound blocks. Unbinding preserves the last displayed icon, which can then be changed independently."
}
]
},
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.sy
index 73b5f00649..bef623df21 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
@@ -7,7 +7,7 @@
"id": "20240208113259-nykkvaq",
"title": "数据库",
"type": "doc",
- "updated": "20260929123717"
+ "updated": "20260930140000"
},
"Children": [
{
@@ -59,12 +59,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260929105001-6j7k32f",
- "updated": "20260929105001"
+ "updated": "20260930140000"
},
"Children": [
{
"Type": "NodeText",
- "Data": "非绑定条目可以设置自己的图标。点击主键值旁或条目详情中的图标即可修改或移除。未设置自定义图标时显示中性默认图标,并遵循视图的图标显示设置。"
+ "Data": "未绑定条目可以拥有自己的图标,点击主键旁、条目详情或关联字段中的图标即可修改或清除。条目模板可以为未绑定条目和文档条目预设图标。未设置自定义图标的未绑定条目显示短横线,视图的图标显示设置仍然生效。"
}
]
},
@@ -73,12 +73,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260929105001-5d3o0dm",
- "updated": "20260929105001"
+ "updated": "20260930140000"
},
"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.sy
index 7acfcb0809..6e8ceb09cd 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
@@ -7,7 +7,7 @@
"id": "20240208171522-y7dxcno",
"title": "資料庫",
"type": "doc",
- "updated": "20260929123717"
+ "updated": "20260930140000"
},
"Children": [
{
@@ -59,12 +59,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260929105001-6i0c6yq",
- "updated": "20260929105001"
+ "updated": "20260930140000"
},
"Children": [
{
"Type": "NodeText",
- "Data": "非綁定條目可以設定自己的圖示。點擊主鍵值旁或條目詳細資料中的圖示即可修改或移除。未設定自訂圖示時顯示中性的預設圖示,並遵循視圖的圖示顯示設定。"
+ "Data": "未綁定條目可以擁有自己的圖示,點擊主鍵旁、條目詳情或關聯欄位中的圖示即可修改或清除。條目範本可以為未綁定條目和文件條目預設圖示。未設定自訂圖示的未綁定條目顯示短橫線,檢視的圖示顯示設定仍然生效。"
}
]
},
@@ -73,12 +73,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260929105001-jnlk4z8",
- "updated": "20260929105001"
+ "updated": "20260930140000"
},
"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.sy
index 93b8ba09e3..7dc2ad9fa5 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
@@ -8,7 +8,7 @@
"id": "20240530101000-3eaevtp",
"title": "データベース",
"type": "doc",
- "updated": "20260929123717"
+ "updated": "20260930140000"
},
"Children": [
{
@@ -60,12 +60,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260929105001-hlf4mxi",
- "updated": "20260929105001"
+ "updated": "20260930140000"
},
"Children": [
{
"Type": "NodeText",
- "Data": "バインドされていないエントリにも独自のアイコンを設定できます。主キーの値の横、またはエントリの詳細にあるアイコンをクリックすると、変更や削除ができます。カスタムアイコンを設定していない場合は中立的な既定アイコンが表示され、ビューのアイコン表示設定も適用されます。"
+ "Data": "未バインドのエントリには独自のアイコンを設定できます。主キーの横、エントリの詳細、またはリレーションフィールドにあるアイコンをクリックすると、変更や削除ができます。エントリテンプレートでは、未バインドのエントリとドキュメントのエントリの両方にアイコンを事前設定できます。独自のアイコンがない未バインドのエントリには短い横線が表示され、ビューのアイコン表示設定も適用されます。"
}
]
},
@@ -74,12 +74,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260929105001-jz7tl6b",
- "updated": "20260929105001"
+ "updated": "20260930140000"
},
"Children": [
{
"Type": "NodeText",
- "Data": "エントリをバインドまたは再バインドすると、元のアイコンは対象ブロックのアイコンに置き換わります。バインドされたエントリは引き続き対象ブロックとアイコンを共有し、ドキュメントブロックの場合はドキュメントのアイコンを使用します。バインドを解除すると最後に表示されたアイコンが保持され、その後は独立して変更できます。"
+ "Data": "独自のアイコンがない通常のブロックにバインドまたは再バインドすると、ブロックはエントリのアイコンを引き継ぎます。ブロックにアイコンがある場合や既存のドキュメントにバインドする場合は、対象のアイコンを使用します。バインド時に新規作成するドキュメントは、エントリに設定されたアイコンを引き継ぎます。エントリにアイコンがない場合は、ドキュメントテンプレートのアイコンを使用します。バインド後はエントリとブロックでアイコンを共有します。バインドを解除すると最後に表示されたアイコンが残り、個別に変更できるようになります。"
}
]
},
diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.ts
index 3742655605..1ec9531546 100644
--- a/app/src/protyle/hint/index.ts
+++ b/app/src/protyle/hint/index.ts
@@ -67,6 +67,7 @@ import {avRender} from "../render/av/render";
import {genIconHTML} from "../render/util";
import {updateAttrViewCellAnimation} from "../render/av/action";
import {getAVBindingCell, getAVBindingOperations} from "../render/av/binding";
+import {bindCreatedAVDocument} from "../render/av/bindCreatedDocument";
import {isRangeInEditor} from "../../util/newFileSelection";
import {genCellValueByElement} from "../render/av/cell";
import {setFold} from "../util/blockFold";
@@ -847,6 +848,21 @@ ${genHintItemHTML(item)}
updateAttrViewCellAnimation(cellElement, nextValue);
}
};
+ const bindingBlockID = nodeElement.dataset.nodeId;
+ const savedPrimaryValue = JSON.stringify(previousValue);
+ const bindCreatedDoc = async (id: string, title: string) => {
+ const bound = await bindCreatedAVDocument(protyle, {
+ avID, itemID: previousID, documentID: id, blockID: bindingBlockID, previousValue,
+ isValid: () => cellElement.isConnected && nodeElement.isConnected &&
+ nodeElement.dataset.nodeId === bindingBlockID &&
+ (panelCell ? rowElement.dataset.rowId : rowElement.dataset.id) === previousID &&
+ JSON.stringify(genCellValueByElement("block", cellElement)) === savedPrimaryValue,
+ });
+ if (bound) {
+ updatePreview({type: "block", isDetached: false,
+ block: {content: title, id, icon: previousValue.block?.icon}});
+ }
+ };
if (value.startsWith("((newFileAtPath ") && value.endsWith(`${Lute.Caret}'))`)) {
const fileNames = value.substring("((newFileAtPath \"".length, value.length - 4).split(`"${Constants.ZWSP}'`);
const name = fileNames.length === 1 ? fileNames[0] : fileNames[1];
@@ -872,16 +888,7 @@ ${genHintItemHTML(item)}
focusByRange(savedRange);
}
},
- onCreated(id, title) {
- const operations = getAVBindingOperations(avID, previousID, id, blockID,
- previousValue, {protyleID: protyle.id});
- transaction(protyle, operations.doOperations, operations.undoOperations);
- updatePreview({
- type: "block",
- isDetached: false,
- block: {content: title, id},
- });
- },
+ onCreated: bindCreatedDoc,
});
return;
}
@@ -894,21 +901,12 @@ ${genHintItemHTML(item)}
const fileNames = value.substring(prefix.length, value.length - 4).split(`"${Constants.ZWSP}'`);
const realFileName = fileNames.length === 1 ? fileNames[0] : fileNames[1];
const newID = Lute.NewNodeID();
- const bindNewDoc = () => {
- const operations = getAVBindingOperations(avID, previousID, newID, nodeElement.dataset.nodeId,
- previousValue, {protyleID: protyle.id});
- transaction(protyle, operations.doOperations, operations.undoOperations);
- };
+ const bindNewDoc = () => bindCreatedDoc(newID, realFileName);
if (isNewSubDoc) {
newSubDocByRefHint(protyle, realFileName, bindNewDoc, newID);
} else {
newFileByRefHint(protyle, realFileName, bindNewDoc, newID);
}
- updatePreview({
- type: "block",
- isDetached: false,
- block: {content: realFileName, id: newID}
- });
} else {
const sourceId = tempElement.getAttribute("data-id");
const operations = getAVBindingOperations(avID, previousID, sourceId, nodeElement.dataset.nodeId,
diff --git a/app/src/protyle/render/av/bindCreatedDocument.test.ts b/app/src/protyle/render/av/bindCreatedDocument.test.ts
new file mode 100644
index 0000000000..693ace17dc
--- /dev/null
+++ b/app/src/protyle/render/av/bindCreatedDocument.test.ts
@@ -0,0 +1,64 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {join} from "node:path";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+import * as binding from "./binding";
+
+const createHarness = (icon = "1f600", code = 0, invalidateDuringSave = false) => {
+ const api = {} as typeof import("./bindCreatedDocument");
+ const events: Array<{path: string, data: unknown}> = [];
+ let valid = true;
+ const siyuan = {config: {readonly: false}, isPublish: false};
+ runInNewContext(transpileModule(readFileSync(join(__dirname, "bindCreatedDocument.ts"), "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},
+ }).outputText, {
+ exports: api, window: {siyuan},
+ require: (name: string) => ({
+ "./binding": binding,
+ "../../../util/fetch": {fetchSyncPost: async (path: string, data: unknown) => {
+ events.push({path, data});
+ valid = !invalidateDuringSave;
+ return {code};
+ }},
+ "../../wysiwyg/transaction": {transaction: (_protyle: unknown, data: unknown) => {
+ events.push({path: "transaction", data});
+ }},
+ })[name] || {},
+ });
+ const protyle = {id: "editor", options: {}} as IProtyle;
+ return {events, siyuan, bind: () => api.bindCreatedAVDocument(protyle, {
+ avID: "database", itemID: "entry", documentID: "new-document", blockID: "carrier",
+ previousValue: {type: "block", isDetached: true, block: {content: "Title", icon}},
+ isValid: () => valid,
+ })};
+};
+
+test("a newly created binding document receives the entry icon before binding", async () => {
+ const h = createHarness();
+ assert.equal(await h.bind(), true);
+ assert.equal(h.events[0].path, "/api/attr/setBlockAttrs");
+ assert.equal(JSON.stringify(h.events[0].data), JSON.stringify({id: "new-document", attrs: {icon: "1f600"}}));
+ const op = (h.events[1].data as IOperation[])[0];
+ assert.equal(op.action, "replaceAttrViewBlock");
+ assert.equal(op.previousID, "entry");
+ assert.equal(op.nextID, "new-document");
+});
+
+test("an entry without a custom icon preserves the created document's default icon", async () => {
+ const h = createHarness("");
+ assert.equal(await h.bind(), true);
+ assert.deepEqual(h.events.map(item => item.path), ["transaction"]);
+});
+
+test("binding stops if assigning the icon fails or the original entry becomes unavailable", async () => {
+ for (const h of [createHarness("1f600", -1), createHarness("1f600", 0, true)]) {
+ assert.equal(await h.bind(), false);
+ assert.deepEqual(h.events.map(item => item.path), ["/api/attr/setBlockAttrs"]);
+ }
+ const h = createHarness();
+ h.siyuan.config.readonly = true;
+ assert.equal(await h.bind(), false);
+ assert.equal(h.events.length, 0);
+});
diff --git a/app/src/protyle/render/av/bindCreatedDocument.ts b/app/src/protyle/render/av/bindCreatedDocument.ts
new file mode 100644
index 0000000000..0894929d07
--- /dev/null
+++ b/app/src/protyle/render/av/bindCreatedDocument.ts
@@ -0,0 +1,30 @@
+import {fetchSyncPost} from "../../../util/fetch";
+import {transaction} from "../../wysiwyg/transaction";
+import {getAVBindingOperations} from "./binding";
+
+// 在绑定前为本次新建的文档设置条目图标,未设置图标时保留文档创建流程的默认值。
+export const bindCreatedAVDocument = async (protyle: IProtyle, options: {
+ avID: string;
+ itemID: string;
+ documentID: string;
+ blockID: string;
+ previousValue: IAVCellValue;
+ isValid: () => boolean;
+}) => {
+ const canBind = () => options.isValid() && !protyle.disabled && !window.siyuan.config.readonly &&
+ !window.siyuan.isPublish && !protyle.options.history?.created && !protyle.options.history?.snapshot;
+ if (!canBind()) {
+ return false;
+ }
+ const icon = options.previousValue.block?.icon;
+ if (icon) {
+ const response = await fetchSyncPost("/api/attr/setBlockAttrs", {id: options.documentID, attrs: {icon}});
+ if (response.code !== 0 || !canBind()) {
+ return false;
+ }
+ }
+ const operations = getAVBindingOperations(options.avID, options.itemID, options.documentID,
+ options.blockID, options.previousValue, {protyleID: protyle.id});
+ transaction(protyle, operations.doOperations, operations.undoOperations);
+ return true;
+};
diff --git a/app/src/protyle/render/av/blockIcon.test.ts b/app/src/protyle/render/av/blockIcon.test.ts
index f58ab94b05..baeb971663 100644
--- a/app/src/protyle/render/av/blockIcon.test.ts
+++ b/app/src/protyle/render/av/blockIcon.test.ts
@@ -10,7 +10,7 @@ import * as viewType from "./viewType";
import * as escape from "../../../util/escape";
// 执行实际渲染、取值和事务生成代码,隔离图标面板与编辑器外部依赖。
-const createHarness = (layout: TAVView = "table", detached = true, icon?: string) => {
+const createHarness = (layout: TAVView = "table", detached = true, icon?: string, relation = false) => {
const value: IAVCellValue = {id: "value", keyID: "primary", blockID: "row", type: "block",
isDetached: detached, block: {content: "Title", ...(detached ? {} : {id: "document"}), icon}};
const cell = {id: "value", value} as IAVCell;
@@ -33,8 +33,11 @@ const createHarness = (layout: TAVView = "table", detached = true, icon?: string
}
return selector === ".b3-menu__avemoji" ? target : null;
}};
- const target = {dataset: {unicode: icon || ""}, innerHTML: "",
- closest: () => cellElement, querySelector: (): HTMLElement => null,
+ const relationElement = {dataset: {rowId: "row", relationValue: encodeURIComponent(JSON.stringify(value))},
+ closest: () => ({dataset: layout === "gallery" ? {fieldId: "relation"} : {colId: "relation"}})};
+ const target = {dataset: {unicode: icon || ""}, innerHTML: "", isConnected: true,
+ closest: (selector: string) => selector === ".av__cell--relation" ? (relation ? relationElement : null) : cellElement,
+ querySelector: (): HTMLElement => null,
getBoundingClientRect: () => ({left: 1, bottom: 2, height: 3, width: 4})};
const protyle = {disabled: false, element: {}, options: {},
wysiwyg: {element: {querySelectorAll: () => [block]}}} as unknown as IProtyle;
@@ -49,6 +52,12 @@ const createHarness = (layout: TAVView = "table", detached = true, icon?: string
}},
"../../util/hasClosest": {hasClosestBlock: () => block, hasClosestByClassName: () => false},
"./virtualScroll": {getAVData: () => data, getAVPrimaryCell: () => cell},
+ "../../../util/fetch": {fetchSyncPost: async (path: string) => ({code: 0,
+ data: path.endsWith("getAttributeViewKeysByID") ? [{relation: {avID: "related"}}] : [{
+ avID: "related", blockIDs: ["related-database"],
+ keyValues: [{key: {id: "primary", type: "block"}, values: [cell.value]}],
+ }],
+ })},
"./row": {getFieldIdByCellElement: () => "row"},
"./col": {getColId: () => "primary"},
"./selectionState": {updateAVSelectedCellValue: () => {}},
@@ -176,6 +185,25 @@ describe("database item icons", () => {
assert.equal(h.operations[0].doOperations[0].rowID, "row");
});
+ it("edits the related entry with its carrier and reads its latest primary value for undo", async () => {
+ const h = createHarness("gallery", true, undefined, true);
+ await h.open();
+ assert.equal(h.panel.type, "av");
+ h.cell.value.block.content = "Later title";
+ h.cell.value.block.icon = "1f680";
+ await h.panel.callback("1f600");
+ const op = h.operations[0];
+ assert.equal(op.doOperations[0].avID, "related");
+ assert.equal(op.doOperations[0].blockID, "related-database");
+ assert.equal(op.doOperations[0].rowID, "row");
+ assert.equal((op.doOperations[0].data as IAVCellValue).block.content, "Later title");
+ assert.equal((op.undoOperations[0].data as IAVCellValue).block.icon, "1f680");
+ assert.equal(h.target.dataset.unicode, "1f600");
+ h.cell.value.isDetached = false;
+ await h.panel.callback("");
+ assert.equal(h.operations.length, 1);
+ });
+
it("does not write after rebinding, becoming read-only, or publishing", () => {
for (const change of ["binding", "disabled", "readonly", "publish"]) {
const h = createHarness();
diff --git a/app/src/protyle/render/av/cell.ts b/app/src/protyle/render/av/cell.ts
index 4a3ab29676..ef70e656c9 100644
--- a/app/src/protyle/render/av/cell.ts
+++ b/app/src/protyle/render/av/cell.ts
@@ -68,6 +68,12 @@ export const openAVCellIcon = (protyle: IProtyle, target: HTMLElement) => {
protyle.options.history?.created || protyle.options.history?.snapshot) {
return;
}
+ const relationElement = target.closest<HTMLElement>(".av__cell--relation");
+ const relationValue = relationElement?.dataset.relationValue ?
+ JSON.parse(decodeURIComponent(relationElement.dataset.relationValue)) as IAVCellValue : undefined;
+ if (relationValue?.isDetached) {
+ return openAVRelationIcon(protyle, target, relationElement, relationValue);
+ }
const cellElement = target.closest<HTMLElement>('.av__cell[data-dtype="block"], [data-type="block"][data-cell-value]');
const value = cellElement ? genCellValueByElement("block", cellElement) : undefined;
const blockID = value ? value.block?.id : target.nextElementSibling?.getAttribute("data-id");
@@ -114,6 +120,56 @@ export const openAVCellIcon = (protyle: IProtyle, target: HTMLElement) => {
}, target.querySelector("img"), {ownerElement: protyle.element});
};
+const openAVRelationIcon = async (protyle: IProtyle, target: HTMLElement, relationElement: HTMLElement, value: IAVCellValue) => {
+ const sourceCell = relationElement.closest<HTMLElement>('.av__cell[data-dtype="relation"], [data-type="relation"][data-av-id]');
+ const sourceBlock = hasClosestBlock(target);
+ const keyID = sourceCell?.dataset.colId || sourceCell?.dataset.fieldId;
+ const rowID = relationElement.dataset.rowId;
+ if (!sourceBlock || !keyID || !rowID) {
+ return;
+ }
+ const sourceAVID = sourceBlock.dataset.avId;
+ const response = await fetchSyncPost("/api/av/getAttributeViewKeysByID", {avID: sourceAVID, keyIDs: [keyID]});
+ const avID = response.code === 0 ? response.data?.[0]?.relation?.avID : "";
+ if (!avID || !target.isConnected || protyle.disabled || window.siyuan.config.readonly || window.siyuan.isPublish ||
+ protyle.options.history?.created || protyle.options.history?.snapshot) {
+ return;
+ }
+ const rect = target.getBoundingClientRect();
+ openEmojiPanel("", "av", {
+ x: rect.left, y: rect.bottom, h: rect.height, w: rect.width,
+ }, async (unicode) => {
+ if (protyle.disabled || window.siyuan.config.readonly || window.siyuan.isPublish ||
+ protyle.options.history?.created || protyle.options.history?.snapshot) {
+ return;
+ }
+ // 关联字段修改目标数据库的主键值,读取当前条目,避免覆盖后续编辑或重新绑定。
+ const current = await fetchSyncPost("/api/av/getAttributeViewKeys", {
+ id: rowID, avID, itemID: rowID, valueID: value.id,
+ });
+ const table = current.code === 0 ? current.data?.find(item => item.avID === avID) : undefined;
+ const primary = table?.keyValues.find(item => item.key.type === "block");
+ const currentValue = primary?.values?.[0];
+ const blockID = table?.blockIDs?.[0];
+ if (!currentValue?.isDetached || !blockID || protyle.disabled || window.siyuan.config.readonly ||
+ window.siyuan.isPublish || protyle.options.history?.created || protyle.options.history?.snapshot) {
+ return;
+ }
+ const oldValue = cloneAVCellValueSnapshot(currentValue);
+ oldValue.block.icon = oldValue.block.icon || "";
+ const newValue = cloneAVCellValueSnapshot(oldValue);
+ newValue.block.icon = unicode;
+ const options = {valueID: oldValue.id, avID, blockID, keyID: primary.key.id, rowID: oldValue.blockID};
+ transaction(protyle, [createAVCellUpdateOperation({...options, data: newValue})],
+ [createAVCellUpdateOperation({...options, data: oldValue})]);
+ if (target.isConnected && relationElement.dataset.rowId === rowID) {
+ relationElement.dataset.relationValue = encodeURIComponent(JSON.stringify(newValue));
+ target.dataset.unicode = unicode;
+ target.innerHTML = getAVBlockIconHTML(newValue);
+ }
+ }, target.querySelector("img"), {ownerElement: protyle.element});
+};
+
const renderCellURL = (urlContent: string) => {
return `<span class="av__celltext av__celltext--url" data-type="url" data-href="${escapeAttr(urlContent)}">${Lute.EscapeHTMLStr(urlContent)}</span>`;
};
diff --git a/app/src/protyle/render/av/newItemTemplate.ts b/app/src/protyle/render/av/newItemTemplate.ts
index 737e564d79..317c772e9c 100644
--- a/app/src/protyle/render/av/newItemTemplate.ts
+++ b/app/src/protyle/render/av/newItemTemplate.ts
@@ -12,7 +12,7 @@ import {getFieldsByData} from "./view";
import {getColIconByType} from "./col";
import {openEmojiPanel, unicode2Emoji} from "../../../emoji";
import {getFileTreeIconHTML} from "../../../emoji/fileTreeIcon";
-import {renderAVBlockIcon} from "./blockIcon";
+import {getAVBlockIconHTML, renderAVBlockIcon} from "./blockIcon";
import {upDownHint} from "../../../util/upDownHint";
import {hasClosestByClassName} from "../../util/hasClosest";
import * as dayjs from "dayjs";
@@ -494,8 +494,7 @@ const openContentTemplateMenu = (target: HTMLElement) => {
const collectTemplate = (root: HTMLElement, itemTemplate: IAVNewItemTemplate, fields: IAVColumn[]) => {
itemTemplate.name = (root.querySelector('[data-role="template-name"]') as HTMLInputElement).value.trim();
itemTemplate.targetType = (root.querySelector('[data-role="target-type"]') as HTMLSelectElement).value as TAVNewItemTarget;
- itemTemplate.icon = itemTemplate.targetType === "document" ?
- (root.querySelector('[data-role="template-icon"]') as HTMLElement).dataset.value || "" : "";
+ itemTemplate.icon = (root.querySelector('[data-role="template-icon"]') as HTMLElement).dataset.value || "";
itemTemplate.primaryKeyTemplate = (root.querySelector('[data-role="primary-key"]') as HTMLInputElement).value;
itemTemplate.contentTemplatePath = (root.querySelector('[data-role="content-template"]') as HTMLElement).dataset.value || "";
const boxID = (root.querySelector('[data-role="box-id"]') as HTMLSelectElement).value;
@@ -560,14 +559,14 @@ const getEditorHTML = (itemTemplate: IAVNewItemTemplate, primaryKey: IAVColumn |
<div class="block__logo block__logo--icon"><svg class="block__logoicon"><use xlink:href="#iconAdd"></use></svg><span>${window.siyuan.languages.type}</span></div>
<div class="fn__flex-1 fn__flex custom-attr__avvalue" style="align-items:center"><select class="b3-select fn__flex-1" data-role="target-type"><option value="detached"${isDocument ? "" : " selected"}>${window.siyuan.languages.createDetachedBlock}</option><option value="document"${isDocument ? " selected" : ""}>${window.siyuan.languages.createBoundBlock}</option></select></div>
</div>
+ <div class="block__icons av__row">
+ <div class="block__logo block__logo--icon"><svg class="block__logoicon"><use xlink:href="#iconEmoji"></use></svg><span>${window.siyuan.languages.icon}</span></div>
+ <div class="fn__flex-1 fn__flex custom-attr__avvalue" style="align-items:center"><button class="b3-text-field b3-text-field--text fn__flex-1 fn__flex" data-role="template-icon" data-value="${escapeAttr(itemTemplate.icon || "")}" type="button" style="align-items:center;text-align:left"><span class="b3-menu__avemoji">${getAVBlockIconHTML({isDetached: !isDocument, block: {content: "", icon: itemTemplate.icon}})}</span></button></div>
+ </div>
</div>
<div data-role="document-options" class="${isDocument ? "" : "fn__none"}">
<div class="fn__hr"></div>
<div class="custom-attr">
- <div class="block__icons av__row">
- <div class="block__logo block__logo--icon"><svg class="block__logoicon"><use xlink:href="#iconEmoji"></use></svg><span>${window.siyuan.languages.icon}</span></div>
- <div class="fn__flex-1 fn__flex custom-attr__avvalue" style="align-items:center"><button class="b3-text-field b3-text-field--text fn__flex-1 fn__flex" data-role="template-icon" data-value="${escapeAttr(itemTemplate.icon || "")}" type="button" style="align-items:center;text-align:left"><span class="b3-menu__avemoji">${getFileTreeIconHTML(itemTemplate.icon, "file")}</span></button></div>
- </div>
<div class="block__icons av__row">
<div class="block__logo block__logo--icon ariaLabel" data-position="parentE" aria-label="${escapeAttr(`${window.siyuan.languages.fileTree14}<br>${window.siyuan.languages.fileTree13}`)}"><svg class="block__logoicon"><use xlink:href="#iconFolder"></use></svg><span>${window.siyuan.languages.savePath}</span></div>
<div class="fn__flex-1 custom-attr__avvalue"><div class="fn__flex" style="align-items:center"><select class="b3-select" data-role="box-id" style="width:${showPath ? "160px" : "100%"}">${notebookOptions}</select><span class="fn__space${showPath ? "" : " fn__none"}" data-role="path-space"></span><input spellcheck="false" class="b3-text-field fn__flex-1${showPath ? "" : " fn__none"}" data-role="path-template" value="${escapeAttr(itemTemplate.saveLocation?.pathTemplate || "")}"${showPath ? "" : " disabled"}></div><div class="b3-label__text${isDefault ? "" : " fn__none"}" data-role="default-tip" style="margin-top:4px">${window.siyuan.languages.newItemTemplateDefaultTip}</div><div class="b3-label__text${isSubDoc ? "" : " fn__none"}" data-role="subdoc-tip" style="margin-top:4px">${window.siyuan.languages.newItemTemplateSubDocTip}</div></div>
@@ -665,7 +664,13 @@ export const openNewItemTemplateDialog = (options: {
templates.map((item, index) => `<li class="b3-list-item b3-list-item--hide-action${index === selectedIndex ? " b3-list-item--focus" : ""}" data-index="${index}" draggable="true"><svg class="b3-list-item__graphic fn__grab"><use xlink:href="#iconDrag"></use></svg><span class="b3-list-item__text">${escapeHtml(item.name)}</span>${item.id === defaultTemplateID ? `<span class="b3-list-item__meta">${window.siyuan.languages.default}</span>` : ""}<span class="b3-list-item__action ariaLabel" data-menu="true" data-position="4west" data-role="template-action" aria-label="${window.siyuan.languages.more}"><svg><use xlink:href="#iconMore"></use></svg></span></li>`).join("");
hostElement.innerHTML = selectedIndex < 0 ? "" : getEditorHTML(templates[selectedIndex], primaryKey, fields, options.protyle.notebookId);
const target = hostElement.querySelector('[data-role="target-type"]') as HTMLSelectElement;
- target?.addEventListener("change", () => hostElement.querySelector('[data-role="document-options"]')?.classList.toggle("fn__none", target.value !== "document"));
+ target?.addEventListener("change", () => {
+ hostElement.querySelector('[data-role="document-options"]')?.classList.toggle("fn__none", target.value !== "document");
+ const iconElement = hostElement.querySelector<HTMLElement>('[data-role="template-icon"]');
+ iconElement.querySelector(".b3-menu__avemoji").innerHTML = getAVBlockIconHTML({
+ isDetached: target.value !== "document", block: {content: "", icon: iconElement.dataset.value},
+ });
+ });
const boxIDElement = hostElement.querySelector('[data-role="box-id"]') as HTMLSelectElement;
const unavailableOption = boxIDElement?.selectedOptions[0]?.dataset.unavailable === "true";
if (target?.value === "document" && unavailableOption && !warnedUnavailableNotebooks.has(templates[selectedIndex].id)) {
@@ -698,7 +703,9 @@ export const openNewItemTemplateDialog = (options: {
w: rect.width,
}, unicode => {
iconElement.dataset.value = unicode;
- emojiElement.innerHTML = getFileTreeIconHTML(unicode, "file");
+ emojiElement.innerHTML = getAVBlockIconHTML({
+ isDetached: target.value !== "document", block: {content: "", icon: unicode},
+ });
}, emojiElement.querySelector("img"), {
ownerElement: options.protyle.element,
targetID: options.protyle.block.rootID,
diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.ts
index 1b7f2f2272..02ae3b42f3 100644
--- a/app/src/types/index.d.ts
+++ b/app/src/types/index.d.ts
@@ -1184,6 +1184,7 @@ interface IAVNewItemFieldValue {
interface IAVNewItemTemplate {
id: string;
name: string;
+ /** 游离条目和文档条目均支持预设图标。 */
icon?: string;
targetType: TAVNewItemTarget;
primaryKeyTemplate?: string;
@@ -1474,6 +1475,7 @@ interface IAVCellValue {
block?: {
content: string,
id?: string,
+ /** 游离条目可独立设置图标;绑定条目与目标块共享图标,无图标的普通块在绑定时继承条目图标。 */
icon?: string,
refSubtype?: "s" | "d"
}
diff --git a/kernel/api/contract_av_test.go b/kernel/api/contract_av_test.go
index b08a2a5656..856eb8a5b2 100644
--- a/kernel/api/contract_av_test.go
+++ b/kernel/api/contract_av_test.go
@@ -2,22 +2,120 @@ package api
import (
"bytes"
+ "context"
"encoding/json"
"net/http"
"os"
+ "os/exec"
"path/filepath"
"reflect"
"testing"
+ "time"
"github.com/88250/gulu"
+ "github.com/88250/lute/ast"
"github.com/siyuan-note/siyuan/kernel/apicontract"
"github.com/siyuan-note/siyuan/kernel/av"
"github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
"github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/sql"
"github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
)
+func TestAVContractDetachedItemIcon(t *testing.T) {
+ if os.Getenv("SIYUAN_TEST_AV_ICON_CONTRACT") != "1" {
+ // 数据库索引和队列有进程级状态,使用独立进程验证实际写入路径。
+ ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
+ defer cancel()
+ command := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestAVContractDetachedItemIcon$", "-test.v")
+ command.Env = append(os.Environ(), "SIYUAN_TEST_AV_ICON_CONTRACT=1")
+ if output, err := command.CombinedOutput(); err != nil {
+ t.Fatalf("icon contract subprocess failed: %v\n%s", err, output)
+ }
+ return
+ }
+ fixture := setupAttributeViewContextFilterAPITest(t)
+ util.TempDir, util.ConfDir, util.HistoryDir = t.TempDir(), t.TempDir(), t.TempDir()
+ languageData, err := os.ReadFile("../../app/appearance/langs/en.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var language struct {
+ Time map[string]any `json:"_time"`
+ }
+ if err = json.Unmarshal(languageData, &language); err != nil {
+ t.Fatal(err)
+ }
+ util.TimeLangs["en"] = language.Time
+ model.Conf.Search, model.Conf.Editor, model.Conf.Export = conf.NewSearch(), conf.NewEditor(), conf.NewExport()
+ tree, err := model.LoadTreeByBlockID(fixture.databaseID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ util.QueueDir = t.TempDir()
+ util.DBPath = filepath.Join(t.TempDir(), util.DBName)
+ util.HistoryDBPath = filepath.Join(t.TempDir(), "history.db")
+ util.AssetContentDBPath = filepath.Join(t.TempDir(), "asset_content.db")
+ sql.InitDatabase(true)
+ sql.InitHistoryDatabase(true)
+ sql.InitAssetContentDatabase(true)
+ treenode.UpsertBlockTree(tree)
+ defer func() {
+ time.Sleep(700 * time.Millisecond)
+ sql.FlushQueue()
+ sql.CloseDatabase()
+ }()
+ database := fixture.attrView
+ primary := database.GetBlockKeyValues()
+ itemID := ast.NewNodeID()
+ primary.Values = append(primary.Values, &av.Value{ID: ast.NewNodeID(), KeyID: primary.Key.ID,
+ BlockID: itemID, Type: av.KeyTypeBlock, IsDetached: true, Block: &av.ValueBlock{Content: "Entry", Icon: "1f600"}})
+ database.Views[0].ItemIDs = append(database.Views[0].ItemIDs, itemID)
+ database.NewItemTemplates = []*av.NewItemTemplate{{ID: ast.NewNodeID(), Name: "Detached",
+ TargetType: av.NewItemTargetDetached, Icon: "1f600"}}
+ if err := av.SaveAttributeView(database); err != nil {
+ t.Fatal(err)
+ }
+ path := "/api/av/setAttributeViewBlockAttr"
+ response := callAttributeViewContextFilterAPI(t, path, map[string]any{
+ "avID": database.ID, "keyID": primary.Key.ID, "itemID": itemID,
+ "value": map[string]any{"block": map[string]any{"icon": "1f680"}},
+ }, setAttributeViewBlockAttr)
+ requireAPIContract(t, http.MethodPost, path, response)
+ var result struct {
+ Code int
+ Data struct{ Value *av.Value }
+ }
+ decodeAttributeViewContextFilterAPIResponse(t, response, &result)
+ if result.Code != 0 || result.Data.Value.Block.Icon != "1f680" || result.Data.Value.Block.Content != "Entry" {
+ t.Fatalf("partial icon update lost primary text: %s", response.Body.String())
+ }
+ tree, err = model.LoadTreeByBlockID(fixture.databaseID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ heading := &ast.Node{Type: ast.NodeHeading, ID: ast.NewNodeID(), HeadingLevel: 2}
+ heading.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("Heading")})
+ tree.Root.AppendChild(heading)
+ if _, err = filesys.WriteTree(tree); err != nil {
+ t.Fatal(err)
+ }
+ treenode.UpsertBlockTree(tree)
+ path = "/api/av/batchReplaceAttributeViewBlocks"
+ response = callAttributeViewContextFilterAPI(t, path, map[string]any{
+ "avID": database.ID, "isDetached": false, "oldNew": []map[string]string{{itemID: heading.ID}},
+ }, batchReplaceAttributeViewBlocks)
+ requireAPIContract(t, http.MethodPost, path, response)
+ var boundResult struct{ Code int }
+ decodeAttributeViewContextFilterAPIResponse(t, response, &boundResult)
+ stored, err := av.ParseAttributeView(database.ID)
+ if err != nil || boundResult.Code != 0 || stored.GetBlockValue(itemID).Block.Icon != "1f680" {
+ t.Fatalf("binding lost inherited icon: %s, %v", response.Body.String(), err)
+ }
+}
+
func TestAVContractRemoveReferencedDatabase(t *testing.T) {
fixture := setupAttributeViewContextFilterAPITest(t)
block := treenode.GetBlockTree(fixture.databaseID)
diff --git a/kernel/apicontract/av_requests.go b/kernel/apicontract/av_requests.go
index 34fd2603af..4b4248bad0 100644
--- a/kernel/apicontract/av_requests.go
+++ b/kernel/apicontract/av_requests.go
@@ -31,6 +31,7 @@ type GetAttributeViewAddingBlockDefaultValuesRequest struct {
AddingBlockID string `json:"addingBlockID" api:"optional,nullable"`
}
+// 无图标的普通块继承原条目图标,已有文档或已设置图标的普通块使用自身图标。
type BatchReplaceAttributeViewBlocksRequest struct {
AvID string `json:"avID"`
IsDetached bool `json:"isDetached"`
@@ -233,6 +234,7 @@ type CreateAttributeViewItemWithMarkdownRequest struct {
Session string `json:"session" api:"optional,nullable"`
}
+// 新建文档继承游离条目已设置的图标;条目未设置图标时沿用文档模板图标。
type CreateAttributeViewItemDocsRequest struct {
AvID string `json:"avID"`
BlockID string `json:"blockID"`
diff --git a/kernel/apicontract/av_types.go b/kernel/apicontract/av_types.go
index f195ffc573..5e591b8c22 100644
--- a/kernel/apicontract/av_types.go
+++ b/kernel/apicontract/av_types.go
@@ -78,7 +78,8 @@ type AVValue struct {
}
type AVValueBlock struct {
- ID string `json:"id,omitempty" api:"optional,nullable"`
+ ID string `json:"id,omitempty" api:"optional,nullable"`
+ // 游离条目可独立设置图标;绑定条目与目标块共享图标,无图标的普通块在绑定时继承条目图标。
Icon string `json:"icon,omitempty" api:"optional,nullable"`
Content string `json:"content" api:"optional,nullable"`
RefSubtype string `json:"refSubtype,omitempty" api:"optional,nullable,enum=s|d"`
@@ -416,8 +417,9 @@ type AVViewData struct {
}
type AVNewItemTemplate struct {
- ID string `json:"id" api:"optional,nullable"`
- Name string `json:"name" api:"optional,nullable"`
+ ID string `json:"id" api:"optional,nullable"`
+ Name string `json:"name" api:"optional,nullable"`
+ // 游离条目和文档条目均支持预设图标;省略或为空时使用相应的默认图标。
Icon string `json:"icon,omitempty" api:"optional,nullable"`
TargetType string `json:"targetType" api:"optional,nullable,enum=detached|document"`
PrimaryKeyTemplate string `json:"primaryKeyTemplate,omitempty" api:"optional,nullable"`
diff --git a/kernel/av/new_item_template.go b/kernel/av/new_item_template.go
index c72f5dbafb..9495f9f8b9 100644
--- a/kernel/av/new_item_template.go
+++ b/kernel/av/new_item_template.go
@@ -74,7 +74,6 @@ func (av *AttributeView) SetNewItemTemplates(config *NewItemTemplatesConfig) err
return fmt.Errorf("invalid new item template target type [%s]", itemTemplate.TargetType)
}
if NewItemTargetDocument != itemTemplate.TargetType {
- itemTemplate.Icon = ""
itemTemplate.HideInFileTree = false
}
itemTemplate.ContentTemplatePath = strings.TrimSpace(itemTemplate.ContentTemplatePath)
diff --git a/kernel/av/new_item_template_test.go b/kernel/av/new_item_template_test.go
index 09183f784f..77b3e009bc 100644
--- a/kernel/av/new_item_template_test.go
+++ b/kernel/av/new_item_template_test.go
@@ -123,7 +123,7 @@ func TestEmptyNewItemTemplatesUseVirtualDefault(t *testing.T) {
}
}
-func TestDetachedNewItemTemplateDropsIcon(t *testing.T) {
+func TestDetachedNewItemTemplatePreservesIcon(t *testing.T) {
attrView := &AttributeView{Spec: CurrentSpec, ID: ast.NewNodeID()}
config := &NewItemTemplatesConfig{Templates: []*NewItemTemplate{{
ID: ast.NewNodeID(), Name: "Detached", Icon: "1f4c4", TargetType: NewItemTargetDetached, HideInFileTree: true,
@@ -131,8 +131,8 @@ func TestDetachedNewItemTemplateDropsIcon(t *testing.T) {
if err := attrView.SetNewItemTemplates(config); nil != err {
t.Fatalf("set detached new item template failed: %s", err)
}
- if "" != attrView.NewItemTemplates[0].Icon {
- t.Fatalf("detached template icon should be empty: %q", attrView.NewItemTemplates[0].Icon)
+ if "1f4c4" != attrView.NewItemTemplates[0].Icon {
+ t.Fatalf("detached template icon was not preserved: %q", attrView.NewItemTemplates[0].Icon)
}
if attrView.NewItemTemplates[0].HideInFileTree {
t.Fatal("detached template should not preserve the file tree visibility setting")
diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.go
index 6940429b6b..4bed6e713a 100644
--- a/kernel/model/attribute_view.go
+++ b/kernel/model/attribute_view.go
@@ -7842,6 +7842,11 @@ func replaceAttributeViewBlock0(attrView *av.AttributeView, oldBlockID, newNodeI
}
if av.KeyTypeBlock == blockVal.Type {
+ if !isDetached {
+ if err = inheritAttributeViewBlockIcon(tx, node, tree, blockVal.Block.Icon); err != nil {
+ return
+ }
+ }
blockVal.IsDetached = isDetached
if !isDetached {
if "" != blockVal.Block.ID && blockVal.Block.ID != newNodeID {
@@ -8163,13 +8168,18 @@ func updateAttributeViewValue0(tx *Transaction, attrView *av.AttributeView, keyI
if updatedVal.Block == nil {
return nil, ErrBlockNotFound
}
- _, tree, loadErr := getNodeByBlockID(tx, updatedVal.Block.ID)
+ node, tree, loadErr := getNodeByBlockID(tx, updatedVal.Block.ID)
if loadErr != nil {
return nil, loadErr
}
if err = validateAttributeViewBinding(avID, tree); err != nil {
return
}
+ if oldIsDetached || oldBoundBlockID != updatedVal.Block.ID {
+ if err = inheritAttributeViewBlockIcon(tx, node, tree, blockVal.Block.Icon); err != nil {
+ return
+ }
+ }
}
if av.KeyTypeText == updatedVal.Type && nil != updatedVal.Text {
if nil != oldText && nil != oldText.Rich && !attributeViewTextRichFieldPresent(data) &&
diff --git a/kernel/model/attribute_view_binding_undo.go b/kernel/model/attribute_view_binding_undo.go
index 557c98e339..0a358d3cf2 100644
--- a/kernel/model/attribute_view_binding_undo.go
+++ b/kernel/model/attribute_view_binding_undo.go
@@ -27,11 +27,12 @@ import (
"github.com/siyuan-note/siyuan/kernel/util"
)
-// 换绑快照只保留主键值,条目 ID 和其他字段值始终保持不变。
+// 换绑快照保留主键值和继承到目标块的图标,条目 ID 和其他字段值始终保持不变。
type attributeViewBindingSnapshot struct {
- avID, blockID, boxID string
- before, after *av.Value
- duplicateItemID string
+ avID, blockID, boxID string
+ before, after *av.Value
+ duplicateItemID string
+ iconBlockID, inheritedIcon string
}
func (tx *Transaction) replaceAttributeViewBinding(op *Operation) error {
@@ -57,7 +58,7 @@ func (tx *Transaction) replaceAttributeViewBinding(op *Operation) error {
value.IsDetached != expected.IsDetached || value.Block.ID != expected.Block.ID {
return fmt.Errorf("database entry binding [%s] changed", expected.BlockID)
}
- if err = tx.applyAttributeViewBinding(current, value, desired, state); err != nil {
+ if err = tx.applyAttributeViewBinding(current, value, desired, state, op.attributeViewBindingUndo); err != nil {
return err
}
op.RetData = map[string]any{"targetItemID": value.BlockID, "duplicate": false}
@@ -115,7 +116,7 @@ func (tx *Transaction) replaceAttributeViewBinding(op *Operation) error {
state.duplicateItemID = existing.BlockID
}
if state.duplicateItemID == "" {
- if err = tx.applyAttributeViewBinding(current, value, desired, state); err != nil {
+ if err = tx.applyAttributeViewBinding(current, value, desired, state, false); err != nil {
return err
}
} else if err = tx.rememberAttributeViewMutationTree(blockID); err != nil {
@@ -135,7 +136,7 @@ func (tx *Transaction) replaceAttributeViewBinding(op *Operation) error {
}
func (tx *Transaction) applyAttributeViewBinding(current *av.AttributeView, value, desired *av.Value,
- state *attributeViewBindingSnapshot) error {
+ state *attributeViewBindingSnapshot, undo bool) error {
if !desired.IsDetached {
if existing := current.GetBlockValueByBoundID(desired.Block.ID); existing != nil && existing.BlockID != value.BlockID {
return fmt.Errorf("database block [%s] is already bound", desired.Block.ID)
@@ -190,9 +191,25 @@ func (tx *Transaction) applyAttributeViewBinding(current *av.AttributeView, valu
avIDs = append(avIDs, current.ID)
}
avs := strings.Join(avIDs, ",")
- if err := setNodeAttrsWithTx(tx, nodes[id], trees[id], map[string]string{
+ attrs := map[string]string{
av.NodeAttrNameAvs: avs, av.NodeAttrViewNames: getAvNames(avs),
- }); err != nil {
+ }
+ if !tx.isReplay && bound {
+ if icon := attributeViewInheritedBlockIcon(nodes[id], desired.Block.Icon); icon != "" {
+ state.iconBlockID, state.inheritedIcon = id, icon
+ attrs["icon"] = icon
+ }
+ } else if id == state.iconBlockID {
+ // 仅恢复本次继承的图标,保留绑定后单独修改过的块图标。
+ expected, desiredIcon := "", state.inheritedIcon
+ if undo {
+ expected, desiredIcon = desiredIcon, ""
+ }
+ if nodes[id].IALAttr("icon") == expected {
+ attrs["icon"] = desiredIcon
+ }
+ }
+ if err := setNodeAttrsWithTx(tx, nodes[id], trees[id], attrs); err != nil {
return err
}
}
@@ -212,3 +229,26 @@ func (tx *Transaction) applyAttributeViewBinding(current *av.AttributeView, valu
refreshRelatedSrcAvsInBlock(current.ID, state.blockID, tx)
return nil
}
+
+// 无自定义图标的普通块继承条目图标,文档始终使用自身图标。
+func attributeViewInheritedBlockIcon(node *ast.Node, icon string) string {
+ if node == nil || node.Type == ast.NodeDocument || node.IALAttr("icon") != "" {
+ return ""
+ }
+ icon, _ = util.FilterIconValue(icon)
+ return icon
+}
+
+func inheritAttributeViewBlockIcon(tx *Transaction, node *ast.Node, tree *parse.Tree, icon string) error {
+ icon = attributeViewInheritedBlockIcon(node, icon)
+ if icon == "" {
+ return nil
+ }
+ if tx != nil {
+ if err := tx.rememberAttributeViewMutationTree(node.ID); err != nil {
+ return err
+ }
+ return setNodeAttrsWithTx(tx, node, tree, map[string]string{"icon": icon})
+ }
+ return setNodeAttrs(node, tree, map[string]string{"icon": icon})
+}
diff --git a/kernel/model/attribute_view_icon_fts5_test.go b/kernel/model/attribute_view_icon_fts5_test.go
index 7bc8c83f0d..757b397771 100644
--- a/kernel/model/attribute_view_icon_fts5_test.go
+++ b/kernel/model/attribute_view_icon_fts5_test.go
@@ -5,8 +5,10 @@ package model
import (
"testing"
+ "github.com/88250/lute/ast"
"github.com/siyuan-note/siyuan/kernel/av"
"github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
)
func TestAttributeViewItemIconLifecycle(t *testing.T) {
@@ -35,7 +37,7 @@ func TestAttributeViewItemIconLifecycle(t *testing.T) {
update(map[string]any{"block": map[string]any{"content": "Renamed"}})
assertIcon("1f600", true)
- // 绑定和重新绑定始终采用目标块图标,取消绑定保留最后显示的图标。
+ // 已有文档使用自身图标,取消绑定保留最后显示的图标。
for index, blockID := range []string{fixture.sourceID, fixture.targetID} {
icon := []string{"1f4c4", "1f4d6"}[index]
tree, err := LoadTreeByBlockID(blockID)
@@ -67,3 +69,158 @@ func TestAttributeViewItemIconLifecycle(t *testing.T) {
t.Fatal("editing a detached item changed the previously bound document icon")
}
}
+
+func TestAttributeViewItemIconBindingInheritance(t *testing.T) {
+ for _, method := range []string{"transaction", "replace", "batch", "cell"} {
+ t.Run(method, func(t *testing.T) {
+ fixture, view, binding := setupAttributeViewBindingUndoTest(t, false)
+ itemID := binding.DoOperations[0].PreviousID
+ tree, err := LoadTreeByBlockID(fixture.targetID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ heading := &ast.Node{Type: ast.NodeHeading, ID: ast.NewNodeID(), HeadingLevel: 2}
+ heading.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("Heading")})
+ tree.Root.AppendChild(heading)
+ if _, err = filesys.WriteTree(tree); err != nil {
+ t.Fatal(err)
+ }
+ treenode.UpsertBlockTree(tree)
+ switch method {
+ case "transaction":
+ binding.DoOperations[0].NextID = heading.ID
+ err = PerformTxSync(binding)
+ case "replace":
+ _, _, err = replaceAttributeViewBlock(view.ID, itemID, heading.ID, false, nil)
+ case "batch":
+ err = BatchReplaceAttributeViewBlocks(view.ID, false, []map[string]string{{itemID: heading.ID}})
+ case "cell":
+ _, err = UpdateAttributeViewCell(nil, view.ID, view.GetBlockKeyValues().Key.ID, itemID,
+ map[string]any{"isDetached": false, "block": map[string]any{"id": heading.ID}})
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertIcon := func(icon string) {
+ t.Helper()
+ node, _, loadErr := getNodeByBlockID(nil, heading.ID)
+ if loadErr != nil || node.IALAttr("icon") != icon {
+ t.Fatalf("block icon was not restored: %v, %q", loadErr, node.IALAttr("icon"))
+ }
+ }
+ assertIcon("1f600")
+ if value := readAttributeViewItemsTest(t, view.ID).GetBlockValue(itemID); value.Block.Icon != "1f600" || value.IsDetached {
+ t.Fatalf("bound entry lost inherited icon: %+v", value)
+ }
+ if method != "transaction" {
+ return
+ }
+ entry := GlobalUndoLog.Peek(fixture.sourceID)
+ for cycle := 0; cycle < 2; cycle++ {
+ if err = PerformTxSync(&Transaction{DoOperations: entry.UndoOperationsForReplay(), isReplay: true}); err != nil {
+ t.Fatal(err)
+ }
+ assertIcon("")
+ assertAttributeViewItemsEqual(t, view, readAttributeViewItemsTest(t, view.ID))
+ if err = PerformTxSync(&Transaction{DoOperations: entry.DoOperationsForReplay(), isReplay: true}); err != nil {
+ t.Fatal(err)
+ }
+ assertIcon("1f600")
+ }
+ node, tree, err := getNodeByBlockID(nil, heading.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = setNodeAttrs(node, tree, map[string]string{"icon": "1f680"}); err != nil {
+ t.Fatal(err)
+ }
+ if err = PerformTxSync(&Transaction{DoOperations: entry.UndoOperationsForReplay(), isReplay: true}); err != nil {
+ t.Fatal(err)
+ }
+ assertIcon("1f680")
+ })
+ }
+}
+
+func TestAttributeViewItemIconTemplateAndCreatedDocument(t *testing.T) {
+ fixture := setupTemplateDocTreeTransactionTest(t)
+ database := addTemplateAttributeViewTestFixture(t, fixture, ast.NewNodeID())
+ view := database.attrView
+ template := &av.NewItemTemplate{ID: ast.NewNodeID(), Name: "Entry", TargetType: av.NewItemTargetDetached,
+ Icon: "1f600", PrimaryKeyTemplate: "Entry"}
+ if err := view.SetNewItemTemplates(&av.NewItemTemplatesConfig{Templates: []*av.NewItemTemplate{template}}); err != nil {
+ t.Fatal(err)
+ }
+ if err := av.SaveAttributeView(view); err != nil {
+ t.Fatal(err)
+ }
+ created, err := CreateAttributeViewItem(view.ID, database.nodes[0].ID, view.Views[0].ID, template.ID, "", "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, operations := range [][]*Operation{created.Transaction.UndoOperations, created.Transaction.DoOperations} {
+ if err = PerformTxSync(&Transaction{DoOperations: cloneOperations(operations), isReplay: true}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if value := readAttributeViewItemsTest(t, view.ID).GetBlockValue(created.ItemID); value.Block.Icon != "1f600" || !value.IsDetached {
+ t.Fatalf("template icon missing after redo: %+v", value)
+ }
+ docs, err := CreateAttributeViewItemDocs(view.ID, database.nodes[0].ID, CreateAttributeViewItemDocsSaveModeSubDoc, []string{created.ItemID})
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertBoundIcon := func() {
+ t.Helper()
+ value := readAttributeViewItemsTest(t, view.ID).GetBlockValue(created.ItemID)
+ tree, loadErr := LoadTreeByBlockID(docs.BlockIDs[0])
+ if loadErr != nil || value.IsDetached || value.Block.Icon != "1f600" || tree.Root.IALAttr("icon") != "1f600" {
+ t.Fatalf("new document did not inherit entry icon: %+v, %v", value, loadErr)
+ }
+ }
+ assertBoundIcon()
+ if err = PerformTxSync(&Transaction{DoOperations: cloneOperations(docs.Transaction.UndoOperations), isReplay: true}); err != nil {
+ t.Fatal(err)
+ }
+ if value := readAttributeViewItemsTest(t, view.ID).GetBlockValue(created.ItemID); !value.IsDetached || value.Block.Icon != "1f600" {
+ t.Fatalf("undo lost detached entry icon: %+v", value)
+ }
+ if err = PerformTxSync(&Transaction{DoOperations: cloneOperations(docs.Transaction.DoOperations), isReplay: true}); err != nil {
+ t.Fatal(err)
+ }
+ assertBoundIcon()
+ stored := readAttributeViewItemsTest(t, view.ID)
+ documentTemplate := &av.NewItemTemplate{ID: ast.NewNodeID(), Name: "Document", TargetType: av.NewItemTargetDocument,
+ Icon: "1f4c4", PrimaryKeyTemplate: "Document"}
+ stored.NewItemTemplates = append(stored.NewItemTemplates, documentTemplate)
+ stored.DefaultTemplateID = documentTemplate.ID
+ if err = av.SaveAttributeView(stored); err != nil {
+ t.Fatal(err)
+ }
+ for _, hasIcon := range []bool{true, false} {
+ item, createErr := CreateAttributeViewItem(view.ID, database.nodes[0].ID, view.Views[0].ID, template.ID, "", "")
+ if createErr != nil {
+ t.Fatal(createErr)
+ }
+ want := "1f600"
+ if !hasIcon {
+ want = "1f4c4"
+ if _, err = UpdateAttributeViewCell(nil, view.ID, view.GetBlockKeyValues().Key.ID, item.ItemID,
+ map[string]any{"block": map[string]any{"icon": ""}}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ createdDocs, createErr := CreateAttributeViewItemDocs(view.ID, database.nodes[0].ID,
+ CreateAttributeViewItemDocsSaveModeTemplate, []string{item.ItemID})
+ if createErr != nil {
+ t.Fatal(createErr)
+ }
+ tree, loadErr := LoadTreeByBlockID(createdDocs.BlockIDs[0])
+ if loadErr != nil || tree.Root.IALAttr("icon") != want {
+ t.Fatalf("template icon priority: want %q, error %v", want, loadErr)
+ }
+ if currentTemplate := readAttributeViewItemsTest(t, view.ID).GetNewItemTemplate(documentTemplate.ID); currentTemplate.Icon != "1f4c4" {
+ t.Fatal("creating a document changed the shared item template icon")
+ }
+ }
+}
diff --git a/kernel/model/attribute_view_new_item.go b/kernel/model/attribute_view_new_item.go
index 77b532a90f..4e2e4075a2 100644
--- a/kernel/model/attribute_view_new_item.go
+++ b/kernel/model/attribute_view_new_item.go
@@ -161,6 +161,12 @@ func createAttributeViewItem(avID, blockID, viewID, templateID, previousID, grou
applyAttributeViewContextFilterDefaultValue(attrView, itemID, filterContext, fieldValues)
boundBlockID := itemID
isDetached := av.NewItemTargetDocument != itemTemplate.TargetType
+ if isDetached && itemTemplate.Icon != "" {
+ fieldValues[attrView.GetBlockKeyValues().Key.ID] = &av.Value{
+ Type: av.KeyTypeBlock, IsDetached: true,
+ Block: &av.ValueBlock{Content: preview.PrimaryKey, Icon: itemTemplate.Icon},
+ }
+ }
var createdTree *parse.Tree
if !isDetached {
boundBlockID, createdTree, err = createAttributeViewItemDocumentWithMarkdown(preview, itemTemplate, document)
@@ -278,7 +284,12 @@ func CreateAttributeViewItemDocs(avID, blockID, saveMode string, itemIDs []strin
return cleanupErr
}
for _, item := range items {
- item.docID, item.tree, err = createAttributeViewItemDocument(item.preview, itemTemplate)
+ // 条目已设置的图标优先用于新建文档,未设置时沿用文档模板。
+ documentTemplate := *itemTemplate
+ if icon, valid := util.FilterIconValue(item.original.Block.Icon); valid && icon != "" {
+ documentTemplate.Icon = icon
+ }
+ item.docID, item.tree, err = createAttributeViewItemDocument(item.preview, &documentTemplate)
if nil != err {
return nil, newItemCreationError(err, cleanupCreatedDocs())
}