Skip to content

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

:sparkles: Support icons for unbound database entries https://github.com/siyuan-note/siyuan/issues/19953

Daniel1cebbbb558b7
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 ba8c22f43c..f0bfe5ab1a 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": "20260927123058"
+ "updated": "20260929105001"
},
"Children": [
{
@@ -39,6 +39,49 @@
}
]
},
+ {
+ "ID": "20260929105001-jav2qb7",
+ "Type": "NodeHeading",
+ "HeadingLevel": 2,
+ "Properties": {
+ "id": "20260929105001-jav2qb7",
+ "updated": "20260929105001"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Entry icons"
+ }
+ ]
+ },
+ {
+ "ID": "20260929105001-d3q9qik",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260929105001-d3q9qik",
+ "updated": "20260929105001"
+ },
+ "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."
+ }
+ ]
+ },
+ {
+ "ID": "20260929105001-pdids8d",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260929105001-pdids8d",
+ "updated": "20260929105001"
+ },
+ "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."
+ }
+ ]
+ },
{
"ID": "20251224101749-zybcbjk",
"Type": "NodeHeading",
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 61509b5c48..bacbc3a28c 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": "20260927123058"
+ "updated": "20260929105001"
},
"Children": [
{
@@ -39,6 +39,49 @@
}
]
},
+ {
+ "ID": "20260929105001-kyrojkr",
+ "Type": "NodeHeading",
+ "HeadingLevel": 2,
+ "Properties": {
+ "id": "20260929105001-kyrojkr",
+ "updated": "20260929105001"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "条目图标"
+ }
+ ]
+ },
+ {
+ "ID": "20260929105001-6j7k32f",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260929105001-6j7k32f",
+ "updated": "20260929105001"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "非绑定条目可以设置自己的图标。点击主键值旁或条目详情中的图标即可修改或移除。未设置自定义图标时显示中性默认图标,并遵循视图的图标显示设置。"
+ }
+ ]
+ },
+ {
+ "ID": "20260929105001-5d3o0dm",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260929105001-5d3o0dm",
+ "updated": "20260929105001"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "绑定或重新绑定条目后,原有图标会被目标块的图标替换。绑定条目继续与绑定块共用图标;绑定文档块时,共用的就是文档图标。解绑后保留最后显示的图标,此后可以独立修改。"
+ }
+ ]
+ },
{
"ID": "20240208115136-9g2b46l",
"Type": "NodeHeading",
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 b9e8144905..426fd36ae6 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": "20260927123058"
+ "updated": "20260929105001"
},
"Children": [
{
@@ -39,6 +39,49 @@
}
]
},
+ {
+ "ID": "20260929105001-ao0pcy0",
+ "Type": "NodeHeading",
+ "HeadingLevel": 2,
+ "Properties": {
+ "id": "20260929105001-ao0pcy0",
+ "updated": "20260929105001"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "條目圖示"
+ }
+ ]
+ },
+ {
+ "ID": "20260929105001-6i0c6yq",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260929105001-6i0c6yq",
+ "updated": "20260929105001"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "非綁定條目可以設定自己的圖示。點擊主鍵值旁或條目詳細資料中的圖示即可修改或移除。未設定自訂圖示時顯示中性的預設圖示,並遵循視圖的圖示顯示設定。"
+ }
+ ]
+ },
+ {
+ "ID": "20260929105001-jnlk4z8",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260929105001-jnlk4z8",
+ "updated": "20260929105001"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "綁定或重新綁定條目後,原有圖示會被目標區塊的圖示取代。綁定條目繼續與綁定區塊共用圖示;綁定文件區塊時,共用的就是文件圖示。解除綁定後保留最後顯示的圖示,此後可以獨立修改。"
+ }
+ ]
+ },
{
"ID": "20251224101729-yhz5zrt",
"Type": "NodeHeading",
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 0df4d6c11e..db30e2e383 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": "20260927123058"
+ "updated": "20260929105001"
},
"Children": [
{
@@ -40,6 +40,49 @@
}
]
},
+ {
+ "ID": "20260929105001-sfv8f41",
+ "Type": "NodeHeading",
+ "HeadingLevel": 2,
+ "Properties": {
+ "id": "20260929105001-sfv8f41",
+ "updated": "20260929105001"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "エントリのアイコン"
+ }
+ ]
+ },
+ {
+ "ID": "20260929105001-hlf4mxi",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260929105001-hlf4mxi",
+ "updated": "20260929105001"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "バインドされていないエントリにも独自のアイコンを設定できます。主キーの値の横、またはエントリの詳細にあるアイコンをクリックすると、変更や削除ができます。カスタムアイコンを設定していない場合は中立的な既定アイコンが表示され、ビューのアイコン表示設定も適用されます。"
+ }
+ ]
+ },
+ {
+ "ID": "20260929105001-jz7tl6b",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260929105001-jz7tl6b",
+ "updated": "20260929105001"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "エントリをバインドまたは再バインドすると、元のアイコンは対象ブロックのアイコンに置き換わります。バインドされたエントリは引き続き対象ブロックとアイコンを共有し、ドキュメントブロックの場合はドキュメントのアイコンを使用します。バインドを解除すると最後に表示されたアイコンが保持され、その後は独立して変更できます。"
+ }
+ ]
+ },
{
"ID": "20251224101829-lva3op2",
"Type": "NodeHeading",
diff --git a/app/src/protyle/render/av/action.ts b/app/src/protyle/render/av/action.ts
index 1ef352de2f..60dda76b37 100644
--- a/app/src/protyle/render/av/action.ts
+++ b/app/src/protyle/render/av/action.ts
@@ -11,6 +11,7 @@ import {
getCellText,
getCellValueText,
getTypeByCellElement,
+ openAVCellIcon,
popTextCell,
renderCell,
renderCellAttr,
@@ -35,8 +36,7 @@ import {hintRef} from "../../hint/extend";
import {focusBlock, focusByRange} from "../../util/selection";
import {showMessage} from "../../../dialog/message";
import {previewAttrViewImages} from "../../preview/image";
-import {openEmojiPanel, unicode2Emoji} from "../../../emoji";
-import {getFileTreeIconHTML} from "../../../emoji/fileTreeIcon";
+import {unicode2Emoji} from "../../../emoji";
import * as dayjs from "dayjs";
import {openCalcMenu} from "./calc";
import {avRender, initUnfoldedGroupTables, setAVGroupFolded as setGroupFolded} from "./render";
@@ -69,6 +69,7 @@ import {getAVTemplateInteractiveElement, isAVTemplateLink} from "./attributeValu
import {isMobile} from "../../../util/functions";
import {getAVCurrentViewID} from "./viewVisibility";
import {cloneAVCellValueSnapshot} from "./cellValue";
+import {getAVBlockIconHTML} from "./blockIcon";
import {formatAVItemLinks, genAVItemLink} from "./itemLink";
import {openLink} from "../../../editor/openLink";
import {
@@ -142,6 +143,7 @@ const unbindDatabaseRows = async (protyle: IProtyle, blockElement: HTMLElement,
isDetached: true,
block: {
content: primaryInfo.content,
+ icon: primaryInfo.value.block.icon || "",
},
};
doOperations.push({
@@ -597,15 +599,7 @@ export const avClick = (protyle: IProtyle, event: MouseEvent & { target: HTMLEle
event.stopPropagation();
return true;
} else if (target.classList.contains("b3-menu__avemoji") && !protyle.disabled) {
- const rect = target.getBoundingClientRect();
- openEmojiPanel(target.nextElementSibling.getAttribute("data-id"), "doc", {
- x: rect.left,
- y: rect.bottom,
- h: rect.height,
- w: rect.width,
- }, (unicode) => {
- target.innerHTML = getFileTreeIconHTML(unicode, "file");
- }, target.querySelector("img"), {ownerElement: protyle.element});
+ openAVCellIcon(protyle, target);
event.preventDefault();
event.stopPropagation();
return true;
@@ -1467,6 +1461,10 @@ export const updateAttrViewCellAnimation = (cellElement: HTMLElement, value: IAV
if (valueElement) {
valueElement.dataset.cellValue = encodeURIComponent(JSON.stringify(cloneAVCellValueSnapshot(value)));
}
+ if (iconElement && value.type === "block") {
+ iconElement.setAttribute("data-unicode", value.block.icon || "");
+ iconElement.innerHTML = getAVBlockIconHTML(value);
+ }
renderCellAttr(cellElement, value);
return;
}
diff --git a/app/src/protyle/render/av/attributeValue.ts b/app/src/protyle/render/av/attributeValue.ts
index b397e658de..68d0e7756a 100644
--- a/app/src/protyle/render/av/attributeValue.ts
+++ b/app/src/protyle/render/av/attributeValue.ts
@@ -1,6 +1,6 @@
import {escapeAriaLabel, escapeAttr, escapeHtml} from "../../../util/escape";
import {unicode2Emoji} from "../../../emoji";
-import {getFileTreeIconHTML} from "../../../emoji/fileTreeIcon";
+import {renderAVBlockIcon} from "./blockIcon";
import {getCompressURL} from "../../../util/image";
import {isBrowserRenderableImagePath} from "../../../util/imageURL";
import {formatDateDisplay, formatDateValue} from "./dateFormat";
@@ -23,7 +23,7 @@ export const getAVTemplateHTML = (content: string) => {
return window.DOMPurify.sanitize(content);
};
-export const genAVRelationHTML = (item: IAVCellValue, rowID: string, showIcon = true, attributePanel = false) => {
+export const genAVRelationHTML = (item: IAVCellValue, rowID: string, showIcon = true) => {
if (!item?.block) {
return "";
}
@@ -34,9 +34,9 @@ export const genAVRelationHTML = (item: IAVCellValue, rowID: string, showIcon =
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}>${renderAVBlockIcon(item, showIcon)}<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>`;
+ return `<span ${attributes} data-block-id="${item.block.id}">${renderAVBlockIcon(item, showIcon)}<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 = [
@@ -127,12 +127,12 @@ const genAVRollupHTML = (value: IAVCellValue) => {
export const genAVValueHTML = (value: IAVCellValue, dateFormat: TAVDateFormat = "", renderTemplate?: string) => {
if (hasAVRenderTemplateResult(value, renderTemplate)) {
const storedValue = cloneAVCellValueSnapshot(value);
- return `<div class="fn__flex-1 av__celltext--template" data-cell-value="${escapeAttr(encodeURIComponent(JSON.stringify(storedValue)))}" placeholder="${window.siyuan.languages.empty}">${getAVTemplateHTML(value.renderedContent || "")}</div>`;
+ return `${value.type === "block" ? renderAVBlockIcon(value) : ""}<div class="fn__flex-1 av__celltext--template" data-cell-value="${escapeAttr(encodeURIComponent(JSON.stringify(storedValue)))}" placeholder="${window.siyuan.languages.empty}">${getAVTemplateHTML(value.renderedContent || "")}</div>`;
}
let html = "";
switch (value.type) {
case "block":
- html = `<input data-id="${value.block.id}" value="${escapeAttr(value.block.content)}" type="text" class="b3-text-field b3-text-field--text fn__flex-1" placeholder="${window.siyuan.languages.empty}">
+ html = `${renderAVBlockIcon(value)}<input data-id="${value.block.id || ""}" value="${escapeAttr(value.block.content)}" type="text" class="b3-text-field b3-text-field--text fn__flex-1" placeholder="${window.siyuan.languages.empty}">
<button type="button" data-type="av-bind-document" class="block__icon block__icon--show fn__flex-center ariaLabel" aria-label="${value.isDetached || !value.block.id ? window.siyuan.languages.bind : window.siyuan.languages.rebind}"><svg><use xlink:href="#iconLink"></use></svg></button>`;
break;
case "text": {
@@ -205,7 +205,7 @@ export const genAVValueHTML = (value: IAVCellValue, dateFormat: TAVDateFormat =
break;
case "relation":
value?.relation?.contents?.forEach((item, index) => {
- html += genAVRelationHTML(item, value.relation.blockIDs[index], true, true);
+ html += genAVRelationHTML(item, value.relation.blockIDs[index]);
});
if (html && html.endsWith(", ")) {
html = html.substring(0, html.length - 2);
diff --git a/app/src/protyle/render/av/blockAttr.ts b/app/src/protyle/render/av/blockAttr.ts
index ae4e78922f..eb94d876f8 100644
--- a/app/src/protyle/render/av/blockAttr.ts
+++ b/app/src/protyle/render/av/blockAttr.ts
@@ -1,10 +1,9 @@
import {fetchPost} from "../../../util/fetch";
import {addCol, getColIconByType} from "./col";
import {escapeAttr, escapeHtml} from "../../../util/escape";
-import {cellValueIsEmpty, popTextCell, updateCellsValue} from "./cell";
+import {cellValueIsEmpty, openAVCellIcon, popTextCell, updateCellsValue} from "./cell";
import {hasClosestBlock, hasClosestByAttribute, hasClosestByClassName} from "../../util/hasClosest";
-import {openEmojiPanel, unicode2Emoji} from "../../../emoji";
-import {getFileTreeIconHTML} from "../../../emoji/fileTreeIcon";
+import {unicode2Emoji} from "../../../emoji";
import {transaction} from "../../wysiwyg/transaction";
import {openMenuPanel} from "./openMenuPanel";
import {openLink} from "../../../editor/openLink";
@@ -658,15 +657,7 @@ const openEdit = (protyle: IProtyle, element: HTMLElement, event: MouseEvent) =>
while (target && element !== target) {
const type = target.getAttribute("data-type");
if (target.classList.contains("b3-menu__avemoji")) {
- const rect = target.getBoundingClientRect();
- openEmojiPanel(target.nextElementSibling.getAttribute("data-id"), "doc", {
- x: rect.left,
- y: rect.bottom,
- h: rect.height,
- w: rect.width,
- }, (unicode) => {
- target.innerHTML = getFileTreeIconHTML(unicode, "file");
- }, target.querySelector("img"), {ownerElement: protyle.element});
+ openAVCellIcon(protyle, target);
event.preventDefault();
event.stopPropagation();
return true;
diff --git a/app/src/protyle/render/av/blockIcon.test.ts b/app/src/protyle/render/av/blockIcon.test.ts
new file mode 100644
index 0000000000..f58ab94b05
--- /dev/null
+++ b/app/src/protyle/render/av/blockIcon.test.ts
@@ -0,0 +1,201 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {join} from "node:path";
+import {runInNewContext} from "node:vm";
+import * as ts from "typescript";
+import * as cellValue from "./cellValue";
+import * as dragFillValue from "./dragFillValue";
+import * as viewType from "./viewType";
+import * as escape from "../../../util/escape";
+
+// 执行实际渲染、取值和事务生成代码,隔离图标面板与编辑器外部依赖。
+const createHarness = (layout: TAVView = "table", detached = true, icon?: string) => {
+ 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;
+ const data = {view: {columns: [{id: "primary", type: "block"}], rows: [{id: "row", cells: [cell]}]}} as IAV;
+ const operations: Array<{doOperations: IOperation[], undoOperations: IOperation[]}> = [];
+ let panel: {id: string, type: string, callback: (icon: string) => void};
+ const siyuan = {config: {readonly: false, editor: {allowHTMLBLockScript: true}}, isPublish: false,
+ languages: {untitled: "Untitled"}};
+ const block = {dataset: {avId: "av", nodeId: "database", avType: layout},
+ getAttribute: (name: string) => name === "data-av-type" ? layout : "20260929120000",
+ querySelectorAll: (): HTMLElement[] => [], contains: () => true};
+ const cellElement = {dataset: {id: "value", colId: "primary", detached: String(detached)},
+ isConnected: true,
+ querySelector: (selector: string) => {
+ if (selector === "input, textarea") {
+ return null;
+ }
+ if (selector === ".av__celltext") {
+ return {textContent: cell.value.block.content, dataset: {id: cell.value.block.id}};
+ }
+ return selector === ".b3-menu__avemoji" ? target : null;
+ }};
+ const target = {dataset: {unicode: icon || ""}, innerHTML: "",
+ closest: () => 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;
+ const mocks: Record<string, unknown> = {
+ "./cellValue": cellValue,
+ "./dragFillValue": dragFillValue,
+ "./viewType": viewType,
+ "../../../util/escape": escape,
+ "../../../emoji/fileTreeIcon": {getFileTreeIconHTML: (item: string) => `<i>${escape.escapeHtml(item || "document-default")}</i>`},
+ "../../../emoji": {openEmojiPanel: (id: string, type: string, _position: unknown, callback: (icon: string) => void) => {
+ panel = {id, type, callback};
+ }},
+ "../../util/hasClosest": {hasClosestBlock: () => block, hasClosestByClassName: () => false},
+ "./virtualScroll": {getAVData: () => data, getAVPrimaryCell: () => cell},
+ "./row": {getFieldIdByCellElement: () => "row"},
+ "./col": {getColId: () => "primary"},
+ "./selectionState": {updateAVSelectedCellValue: () => {}},
+ "./batchValue": {getAVBatchEditMode: () => "replace", getAVBatchSourceValue: (_element: unknown, item: IAVCellValue) => item},
+ "../../../util/functions": {objEquals: (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)},
+ "../../../util/hostCapabilities": {getHostCapabilities: () => ({remoteKernel: false})},
+ "dayjs": () => ({format: () => "20260929130000"}),
+ "../../wysiwyg/transaction": {transaction: (_protyle: unknown, doOperations: IOperation[], undoOperations: IOperation[]) => {
+ operations.push({doOperations, undoOperations});
+ }},
+ };
+ const load = (name: string) => {
+ const module = {exports: {}};
+ runInNewContext(ts.transpileModule(readFileSync(join(__dirname, `${name}.ts`), "utf8"), {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022},
+ }).outputText, {
+ module, exports: module.exports, require: (id: string) => mocks[id] || {},
+ window: {siyuan}, document: {querySelectorAll: (): HTMLElement[] => [], createElement: () => ({
+ matches: () => false, querySelector: (): HTMLElement => null, querySelectorAll: (): HTMLElement[] => [], textContent: "",
+ })},
+ Lute: {EscapeHTMLStr: escape.escapeHtml},
+ });
+ mocks[`./${name}`] = module.exports;
+ return module.exports;
+ };
+ const icons = load("blockIcon") as typeof import("./blockIcon");
+ const attributes = load("attributeValue") as typeof import("./attributeValue");
+ const api = load("cell") as typeof import("./cell");
+ const selected = () => [{groupID: "", rowID: "row", colID: "primary", rowIndex: 0, colIndex: 0,
+ cell, column: {id: "primary", type: "block"}}] as Parameters<typeof api.updateCellsValue>[9];
+ return {api, icons, attributes, cell, cellElement, target, protyle, siyuan, operations,
+ get panel() { return panel; },
+ update: (next: unknown) => api.updateCellsValue(protyle, block as unknown as HTMLElement, next,
+ undefined, undefined, undefined, false, false, false, selected()),
+ open: () => api.openAVCellIcon(protyle, target as unknown as HTMLElement)};
+};
+
+describe("database item icons", () => {
+ it("renders detached defaults and custom icons in every layout and honors hidden icons", () => {
+ const h = createHarness();
+ for (const layout of ["table", "list", "gallery", "kanban", "calendar"] as TAVView[]) {
+ assert.match(h.api.renderCell(h.cell.value, 0, true, layout), /#iconLine/);
+ assert.match(h.api.renderCell(h.cell.value, 0, false, layout), /b3-menu__avemoji fn__none/);
+ h.cell.value.block.icon = "1f600";
+ const html = h.api.renderCell(h.cell.value, 0, true, layout);
+ assert.match(html, /data-unicode="1f600"/);
+ assert.doesNotMatch(html, /data-type="block-ref"/);
+ delete h.cell.value.block.icon;
+ }
+ assert.match(h.attributes.genAVValueHTML(h.cell.value), /#iconLine/);
+ assert.doesNotMatch(h.attributes.genAVValueHTML(h.cell.value), /data-id="undefined"/);
+ });
+
+ it("shows detached icons in relation and rollup values without creating a block reference", () => {
+ const h = createHarness("table", true, "1f600");
+ const relation = h.attributes.genAVRelationHTML(h.cell.value, "row");
+ assert.match(relation, /data-unicode="1f600"/);
+ assert.doesNotMatch(relation, /data-type="block-ref"/);
+ const rollup = h.api.renderCell({type: "rollup", rollup: {contents: [h.cell.value]}}, 0, false);
+ assert.match(rollup, /b3-menu__avemoji fn__none/);
+ });
+
+ it("keeps icons beside display templates and in entry details", () => {
+ const h = createHarness("table", true, "1f600");
+ h.cell.value.renderedContent = "<strong>Display title</strong>";
+ for (const html of [h.api.renderCell(h.cell.value), h.attributes.genAVValueHTML(h.cell.value)]) {
+ assert.match(html, /data-unicode="1f600"/);
+ assert.match(html, /<strong>Display title<\/strong>/);
+ assert.match(html, /data-cell-value=/);
+ }
+ });
+
+ it("reads an explicit empty icon for undo and preserves icons when renaming or unbinding", async () => {
+ const h = createHarness("list", true, "1f600");
+ assert.equal(h.api.genCellValueByElement("block", h.cellElement as unknown as HTMLElement).block.icon, "1f600");
+ await h.update("Renamed");
+ assert.equal(h.cell.value.block.content, "Renamed");
+ assert.equal(h.cell.value.block.icon, "1f600");
+ await h.update({icon: "", content: "Renamed"});
+ assert.equal((h.operations[1].doOperations[0].data as IAVCellValue).block.icon, "");
+ assert.equal((h.operations[1].undoOperations[0].data as IAVCellValue).block.icon, "1f600");
+ h.target.dataset.unicode = "";
+ assert.equal(h.api.genCellValueByElement("block", h.cellElement as unknown as HTMLElement).block.icon, "");
+ const bound = createHarness("table", false, "1f600");
+ await bound.update({content: "Title"});
+ assert.equal(bound.cell.value.isDetached, true);
+ assert.equal(bound.cell.value.block.icon, "1f600");
+ assert.equal((bound.operations[0].undoOperations[0].data as IAVCellValue).block.id, "document");
+ const paste = createHarness();
+ await paste.update({type: "block", isDetached: true, block: {content: "Pasted", icon: "1f600"}});
+ assert.equal((paste.operations[0].undoOperations[0].data as IAVCellValue).block.icon, "");
+ });
+
+ it("uses row transactions for detached icons and the document picker for bound icons", async () => {
+ for (const layout of ["table", "list", "gallery", "kanban"] as TAVView[]) {
+ const h = createHarness(layout);
+ h.open();
+ assert.equal(h.panel.type, "av");
+ h.panel.callback("1f600");
+ await Promise.resolve();
+ const op = h.operations[0];
+ assert.equal(op.doOperations[0].rowID, "row");
+ assert.equal(op.doOperations[0].keyID, "primary");
+ assert.equal((op.doOperations[0].data as IAVCellValue).block.content, "Title");
+ assert.equal((op.doOperations[0].data as IAVCellValue).block.icon, "1f600");
+ assert.equal((op.undoOperations[0].data as IAVCellValue).block.icon, "");
+ }
+ const bound = createHarness("table", false);
+ bound.open();
+ assert.equal(bound.panel.type, "doc");
+ assert.equal(bound.panel.id, "document");
+ bound.panel.callback("1f600");
+ assert.equal(bound.target.dataset.unicode, "1f600");
+ assert.equal(bound.operations.length, 0);
+ });
+
+ it("keeps the original row through virtual scrolling and preserves later title edits", async () => {
+ const h = createHarness();
+ h.open();
+ h.cellElement.isConnected = false;
+ h.cell.value.block.content = "Later title";
+ h.panel.callback("1f600");
+ await Promise.resolve();
+ assert.equal((h.operations[0].doOperations[0].data as IAVCellValue).block.content, "Later title");
+ assert.equal(h.operations[0].doOperations[0].rowID, "row");
+ });
+
+ it("does not write after rebinding, becoming read-only, or publishing", () => {
+ for (const change of ["binding", "disabled", "readonly", "publish"]) {
+ const h = createHarness();
+ h.open();
+ if (change === "binding") {
+ h.cell.value.isDetached = false;
+ h.cell.value.block.id = "document";
+ } else if (change === "disabled") {
+ h.protyle.disabled = true;
+ } else if (change === "readonly") {
+ h.siyuan.config.readonly = true;
+ } else {
+ h.siyuan.isPublish = true;
+ }
+ h.panel.callback("1f600");
+ assert.equal(h.operations.length, 0);
+ }
+ const h = createHarness();
+ h.protyle.disabled = true;
+ h.open();
+ assert.equal(h.panel, undefined);
+ });
+});
diff --git a/app/src/protyle/render/av/blockIcon.ts b/app/src/protyle/render/av/blockIcon.ts
new file mode 100644
index 0000000000..07a05a1bc9
--- /dev/null
+++ b/app/src/protyle/render/av/blockIcon.ts
@@ -0,0 +1,12 @@
+import {getFileTreeIconHTML} from "../../../emoji/fileTreeIcon";
+import {escapeAttr} from "../../../util/escape";
+
+export const getAVBlockIconHTML = (value: Pick<IAVCellValue, "block" | "isDetached">) => {
+ if (value.isDetached && !value.block?.icon) {
+ return '<svg><use xlink:href="#iconLine"></use></svg>';
+ }
+ return getFileTreeIconHTML(value.block?.icon, "file");
+};
+
+export const renderAVBlockIcon = (value: Pick<IAVCellValue, "block" | "isDetached">, showIcon = true) =>
+ `<span class="b3-menu__avemoji${showIcon ? "" : " fn__none"}" data-unicode="${escapeAttr(value.block?.icon || "")}">${getAVBlockIconHTML(value)}</span>`;
diff --git a/app/src/protyle/render/av/cell.ts b/app/src/protyle/render/av/cell.ts
index f426308b24..4a3ab29676 100644
--- a/app/src/protyle/render/av/cell.ts
+++ b/app/src/protyle/render/av/cell.ts
@@ -9,8 +9,7 @@ import {isDynamicRef, objEquals} from "../../../util/functions";
import {fetchPost, fetchSyncPost} from "../../../util/fetch";
import {focusBlock, focusByRange} from "../../util/selection";
import * as dayjs from "dayjs";
-import {unicode2Emoji} from "../../../emoji";
-import {getFileTreeIconHTML} from "../../../emoji/fileTreeIcon";
+import {openEmojiPanel, unicode2Emoji} from "../../../emoji";
import {getColIconByType, getColId} from "./col";
import {genAVRelationHTML, genAVValueHTML, getAVTemplateHTML} from "./attributeValue";
import {Constants} from "../../../constants";
@@ -58,11 +57,63 @@ import {
renderAVRichTextElements,
} from "./richText";
import {openAVRichTextEditor} from "./richTextEditor";
-import {getAVData} from "./virtualScroll";
+import {getAVData, getAVPrimaryCell} from "./virtualScroll";
import {AV_CELL_EDITOR_CLOSE_EVENT} from "./cellEditor";
+import {getAVBlockIconHTML, renderAVBlockIcon} from "./blockIcon";
export {cellValueIsEmpty} from "./cellValue";
+export const openAVCellIcon = (protyle: IProtyle, target: HTMLElement) => {
+ if (protyle.disabled || window.siyuan.config.readonly || window.siyuan.isPublish ||
+ protyle.options.history?.created || protyle.options.history?.snapshot) {
+ return;
+ }
+ 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");
+ const isDetached = value?.isDetached === true;
+ if (!isDetached && !blockID) {
+ return;
+ }
+ const blockElement = hasClosestBlock(target);
+ if (!blockElement) {
+ return;
+ }
+ const rowID = isDetached ? getFieldIdByCellElement(cellElement, blockElement.dataset.avType as TAVView) : "";
+ const colID = cellElement?.dataset.colId || cellElement?.dataset.fieldId;
+ if (isDetached && (!rowID || !colID)) {
+ return;
+ }
+ const rect = target.getBoundingClientRect();
+ openEmojiPanel(isDetached ? "" : blockID, isDetached ? "av" : "doc", {
+ x: rect.left, y: rect.bottom, h: rect.height, w: rect.width,
+ }, (unicode) => {
+ if (protyle.disabled || window.siyuan.config.readonly || window.siyuan.isPublish ||
+ protyle.options.history?.created || protyle.options.history?.snapshot) {
+ return;
+ }
+ if (!isDetached) {
+ target.dataset.unicode = unicode;
+ target.innerHTML = getAVBlockIconHTML({block: {content: "", icon: unicode}});
+ return;
+ }
+ // 图标面板打开期间可能发生虚拟滚动或重新绑定,按原项目定位并读取当前值。
+ const currentCell = getAVPrimaryCell(blockElement, rowID);
+ const currentValue = currentCell?.value || (cellElement.isConnected ? genCellValueByElement("block", cellElement) : value);
+ if (!currentValue.isDetached) {
+ return;
+ }
+ const oldValue = cloneAVCellValueSnapshot(currentValue);
+ oldValue.block.icon = oldValue.block.icon || "";
+ void updateCellsValue(protyle, blockElement, {...oldValue.block, icon: unicode},
+ undefined, undefined, undefined, false, false, false, [{
+ groupID: "", rowID, colID, rowIndex: 0, colIndex: -1,
+ cell: {...currentCell, id: currentCell?.id || cellElement.dataset.id, value: oldValue},
+ column: {id: colID, type: "block"} as IAVColumn,
+ }]);
+ }, 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>`;
};
@@ -139,14 +190,11 @@ export const genCellValueByElement = (colType: TAVCol, cellElement: HTMLElement)
content: inputElement ? inputElement.value :
(colType === "url" ? textElement?.dataset.href : textElement?.textContent) || ""
};
- if (colType === "block" && (inputElement?.dataset.id || textElement?.dataset.id)) {
- cellValue.block.id = inputElement?.dataset.id || textElement.dataset.id;
- if (textElement?.previousElementSibling?.classList.contains("b3-menu__avemoji")) {
- const unicode = textElement.previousElementSibling.getAttribute("data-unicode");
- if (unicode) {
- cellValue.block.icon = unicode;
- }
+ if (colType === "block") {
+ if (inputElement?.dataset.id || textElement?.dataset.id) {
+ cellValue.block.id = inputElement?.dataset.id || textElement.dataset.id;
}
+ cellValue.block.icon = cellElement.querySelector<HTMLElement>(".b3-menu__avemoji")?.dataset.unicode || "";
}
} else if (colType === "mSelect" || colType === "select") {
const mSelect: IAVCellSelectValue[] = [];
@@ -930,6 +978,9 @@ export const updateCellsValue = async (protyle: IProtyle, nodeElement: HTMLEleme
continue;
}
const oldValue = cloneAVCellValueSnapshot(sourceOldValue);
+ if (type === "block") {
+ oldValue.block.icon = oldValue.block.icon || "";
+ }
const batchMode = getAVBatchEditMode(item);
if (elementIndex === 0 && item && batchMode !== "replace") {
batchDisplayValue = getAVBatchDisplayValue(item, renderedOldValue);
@@ -1067,6 +1118,9 @@ export const updateCellsValue = async (protyle: IProtyle, nodeElement: HTMLEleme
} else {
cellValue = genCellValue(type, newValue, column?.dateFormat);
}
+ if (type === "block" && typeof cellValue.block.icon === "undefined") {
+ cellValue.block.icon = oldValue.block.icon || "";
+ }
cellValue = rebindAVCellValue(cellValue, {
id: cellId,
keyID: colId,
@@ -1175,6 +1229,11 @@ export const updateAttrViewCellInOtherElements = (protyle: IProtyle, avID: strin
}
}
if (value.type === "block") {
+ const iconElement = cellElement.querySelector<HTMLElement>(".b3-menu__avemoji");
+ if (iconElement) {
+ iconElement.dataset.unicode = value.block.icon || "";
+ iconElement.innerHTML = getAVBlockIconHTML(value);
+ }
const databaseRowElement = cellElement.closest<HTMLElement>(".protyle-db-row");
if (databaseRowElement) {
const title = value.block?.content || window.siyuan.languages.untitled;
@@ -1251,6 +1310,7 @@ export const renderCell = (cellValue: IAVCellValue, rowIndex = 0, showIcon = tru
const storedValue = cloneAVCellValueSnapshot(cellValue);
text = `<span class="av__celltext av__celltext--template" data-cell-value="${escapeAttr(encodeURIComponent(JSON.stringify(storedValue)))}">${getAVTemplateHTML(cellValue.renderedContent || "")}</span>`;
if (cellValue.type === "block") {
+ text = renderAVBlockIcon(cellValue, showIcon) + text;
const bindLabel = cellValue?.isDetached ? window.siyuan.languages.bind : window.siyuan.languages.rebind;
const updateIcon = cellValue?.isDetached ? "iconRef" : "iconRefresh";
text += `<span class="av__row-actions"><button class="av__row-action av__cell-action ariaLabel" type="button" data-position="4north" aria-label="${window.siyuan.languages.openBy}" data-type="av-row-open"><svg><use xlink:href="#iconOpen"></use></svg></button><button class="av__row-action av__cell-action ariaLabel" type="button" data-position="4north" aria-label="${bindLabel}" data-type="av-row-update"><svg><use xlink:href="#${updateIcon}"></use></svg></button></span>`;
@@ -1272,9 +1332,9 @@ export const renderCell = (cellValue: IAVCellValue, rowIndex = 0, showIcon = tru
} else if (cellValue.type === "block") {
// 不可使用换行 https://github.com/siyuan-note/siyuan/issues/11365
if (cellValue?.isDetached) {
- text = `<span class="av__celltext">${Lute.EscapeHTMLStr(cellValue.block.content || "")}</span>`;
+ text = `${renderAVBlockIcon(cellValue, showIcon)}<span class="av__celltext">${Lute.EscapeHTMLStr(cellValue.block.content || "")}</span>`;
} else {
- text = `<span class="b3-menu__avemoji${showIcon ? "" : " fn__none"}" data-unicode="${escapeAttr(cellValue.block.icon || "")}">${getFileTreeIconHTML(cellValue.block.icon, "file")}</span><span data-type="block-ref" data-id="${cellValue.block.id}" data-subtype="${getAVBlockRefSubtype(cellValue)}" class="av__celltext av__celltext--ref">${Lute.EscapeHTMLStr(cellValue.block.content)}</span>`;
+ text = `${renderAVBlockIcon(cellValue, showIcon)}<span data-type="block-ref" data-id="${cellValue.block.id}" data-subtype="${getAVBlockRefSubtype(cellValue)}" class="av__celltext av__celltext--ref">${Lute.EscapeHTMLStr(cellValue.block.content)}</span>`;
}
const bindLabel = cellValue?.isDetached ? window.siyuan.languages.bind : window.siyuan.languages.rebind;
const updateIcon = cellValue?.isDetached ? "iconRef" : "iconRefresh";
@@ -1414,9 +1474,9 @@ const renderRollup = (cellValue: IAVCellValue, showIcon: boolean) => {
}
} else if (cellValue.type === "block") {
if (cellValue?.isDetached) {
- text = `<span class="av__celltext">${Lute.EscapeHTMLStr(cellValue.block?.content || window.siyuan.languages.untitled)}</span>`;
+ text = `${renderAVBlockIcon(cellValue, showIcon)}<span class="av__celltext">${Lute.EscapeHTMLStr(cellValue.block?.content || window.siyuan.languages.untitled)}</span>`;
} else {
- text = `<span class="b3-menu__avemoji${showIcon ? "" : " fn__none"}" data-unicode="${escapeAttr(cellValue.block.icon || "")}">${getFileTreeIconHTML(cellValue.block.icon, "file")}</span><span data-type="block-ref" data-id="${cellValue.block?.id}" data-subtype="${getAVBlockRefSubtype(cellValue)}" class="av__celltext av__celltext--ref">${Lute.EscapeHTMLStr(cellValue.block?.content || window.siyuan.languages.untitled)}</span>`;
+ text = `${renderAVBlockIcon(cellValue, showIcon)}<span data-type="block-ref" data-id="${cellValue.block?.id}" data-subtype="${getAVBlockRefSubtype(cellValue)}" class="av__celltext av__celltext--ref">${Lute.EscapeHTMLStr(cellValue.block?.content || window.siyuan.languages.untitled)}</span>`;
}
} else if (cellValue.type === "number") {
text = cellValue?.number.formattedContent || cellValue?.number.content.toString() || "";
diff --git a/app/src/protyle/render/av/newItemTemplate.ts b/app/src/protyle/render/av/newItemTemplate.ts
index 132ace0188..737e564d79 100644
--- a/app/src/protyle/render/av/newItemTemplate.ts
+++ b/app/src/protyle/render/av/newItemTemplate.ts
@@ -12,6 +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 {upDownHint} from "../../../util/upDownHint";
import {hasClosestByClassName} from "../../util/hasClosest";
import * as dayjs from "dayjs";
@@ -344,7 +345,7 @@ const renderRelationFieldValue = (target: HTMLElement, options: IRelationOption[
const selected = new Set(getSelectedOptionNames(target));
const html = options.filter(option => selected.has(option.id)).map(option => {
if (option.isDetached) {
- return `<span class="av__cell--relation" data-row-id="${escapeAttr(option.id)}"><span><svg><use xlink:href="#iconLine"></use></svg><span class="fn__space--5"></span></span><span class="av__celltext">${escapeHtml(option.content)}</span></span>`;
+ return `<span class="av__cell--relation" data-row-id="${escapeAttr(option.id)}">${renderAVBlockIcon({isDetached: true, block: {content: option.content, icon: option.icon}})}<span class="av__celltext">${escapeHtml(option.content)}</span></span>`;
}
const icon = getFileTreeIconHTML(option.icon, "file");
return `<span class="av__cell--relation" data-row-id="${escapeAttr(option.id)}" data-block-id="${escapeAttr(option.blockID)}"><span class="b3-menu__avemoji" data-unicode="${escapeAttr(option.icon)}">${icon}</span><span data-type="block-ref" data-id="${escapeAttr(option.blockID)}" data-subtype="${option.refSubtype}" class="av__celltext av__celltext--ref">${escapeHtml(option.content)}</span></span>`;
diff --git a/app/src/protyle/render/av/relation.ts b/app/src/protyle/render/av/relation.ts
index 6863f3361a..ffbc4ed1e7 100644
--- a/app/src/protyle/render/av/relation.ts
+++ b/app/src/protyle/render/av/relation.ts
@@ -23,7 +23,7 @@ import {getSearchAVFocus} from "./searchAVFocus";
import {getAVTemplateHTML} from "./attributeValue";
import {hasAVRenderTemplateResult} from "./cellValue";
import {renderAVRichTextElements} from "./richText";
-import {getFileTreeIconHTML} from "../../../emoji/fileTreeIcon";
+import {getAVBlockIconHTML} from "./blockIcon";
import {unicode2Emoji} from "../../../emoji";
import {bindRelationLayout} from "./relationLayout";
import {getTopBarHeight} from "../../../layout/getTopBarHeight";
@@ -454,7 +454,7 @@ style="grid-template-columns:${gridTemplate}">
data-value-id="${escapeAttr(primaryCell.id || "")}"
style="${primaryCell.bgColor ? `background-color:${primaryCell.bgColor};` : ""}${primaryCell.color ? `color:${primaryCell.color};` : ""}">
${selected ? '<svg class="b3-menu__icon fn__grab"><use xlink:href="#iconDrag"></use></svg>' : ""}
- ${isDetached ? "" : `<span class="av__relation-row-icon">${getFileTreeIconHTML(primaryValue.block?.icon, "file")}</span>`}
+ <span class="av__relation-row-icon">${getAVBlockIconHTML(primaryValue)}</span>
<span class="b3-menu__label fn__ellipsis${isDetached ? "" : " popover__block"}${useRenderedContent ? " av__celltext--template" : ""}"
data-icon="${escapeAttr(primaryValue.block?.icon || "")}"
data-id="${escapeAttr(primaryValue.block?.id || "")}" data-content="${escapeAttr(primaryValue.block?.content || "")}">${isDetached ? content : `<span class="av__celltext--ref">${content}</span>`}</span>
@@ -998,6 +998,7 @@ const genCreatedRelationRowHTML = (menuElement: HTMLElement, rowID: string, cont
const columns = headerElement?.querySelectorAll<HTMLElement>(".av__relation-table-cell");
let cellsHTML = `<span data-relation-column="${escapeAttr(columns?.[0]?.dataset.relationColumn || "")}" class="av__relation-table-cell av__relation-table-primary" data-row-id="${rowID}">
<svg class="b3-menu__icon fn__grab"><use xlink:href="#iconDrag"></use></svg>
+ <span class="av__relation-row-icon">${getAVBlockIconHTML({isDetached: true})}</span>
<span class="b3-menu__label fn__ellipsis" data-id="">${Lute.EscapeHTMLStr(content)}</span>
</span>`;
for (let i = 1; i < (columns?.length || 1); i++) {
diff --git a/kernel/model/attribute_view_icon_fts5_test.go b/kernel/model/attribute_view_icon_fts5_test.go
new file mode 100644
index 0000000000..7bc8c83f0d
--- /dev/null
+++ b/kernel/model/attribute_view_icon_fts5_test.go
@@ -0,0 +1,69 @@
+//go:build fts5
+
+package model
+
+import (
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/av"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+)
+
+func TestAttributeViewItemIconLifecycle(t *testing.T) {
+ fixture, view, binding := setupAttributeViewBindingUndoTest(t, false)
+ itemID := binding.DoOperations[0].PreviousID
+ keyID := view.GetBlockKeyValues().Key.ID
+ update := func(data any) *av.Value {
+ t.Helper()
+ value, err := UpdateAttributeViewCell(nil, view.ID, keyID, itemID, data)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return value
+ }
+ assertIcon := func(want string, detached bool) {
+ t.Helper()
+ value := readAttributeViewItemsTest(t, view.ID).GetBlockValue(itemID)
+ if value.Block.Icon != want || value.IsDetached != detached {
+ t.Fatalf("unexpected persisted item: %+v, block: %+v", value, value.Block)
+ }
+ }
+ for _, icon := range []string{"1f680", "", "1f600"} {
+ update(map[string]any{"block": map[string]any{"icon": icon}})
+ assertIcon(icon, true)
+ }
+ 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)
+ if err != nil {
+ t.Fatal(err)
+ }
+ tree.Root.SetIALAttr("icon", icon)
+ if _, err = filesys.WriteTree(tree); err != nil {
+ t.Fatal(err)
+ }
+ if index == 0 {
+ if err = PerformTxSync(binding); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ update(map[string]any{"isDetached": false, "block": map[string]any{"id": blockID}})
+ }
+ assertIcon(icon, false)
+ }
+ update(map[string]any{"isDetached": true, "block": map[string]any{"content": "Detached"}})
+ assertIcon("1f4d6", true)
+ update(map[string]any{"block": map[string]any{"icon": "1f680"}})
+ assertIcon("1f680", true)
+ tree, err := LoadTreeByBlockID(fixture.targetID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if tree.Root.IALAttr("icon") != "1f4d6" {
+ t.Fatal("editing a detached item changed the previously bound document icon")
+ }
+}