Skip to content

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

:sparkles: Reuse block binding candidates in database panels and menus https://github.com/siyuan-note/siyuan/issues/19935

Danieldd2a4c58a9a4
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index e37fb34301..28679daa15 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,6 +1,4 @@
{
- "bindDocument": "ربط مستند",
- "selectOneDocument": "يرجى تحديد مستند واحد",
"horizontalSuperBlock": "كتلة خارقة أفقية",
"verticalSuperBlock": "كتلة خارقة عمودية",
"prependSuperBlockColumn": "إضافة عمود إلى بداية الكتلة الخارقة الحالية",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 7a346f25d9..7a50c39410 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,6 +1,4 @@
{
- "bindDocument": "Dokument verknüpfen",
- "selectOneDocument": "Bitte genau ein Dokument auswählen",
"horizontalSuperBlock": "Horizontaler Superblock",
"verticalSuperBlock": "Vertikaler Superblock",
"prependSuperBlockColumn": "Spalte am Anfang des aktuellen Superblocks hinzufügen",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 95e710d228..e256366c26 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,6 +1,4 @@
{
- "bindDocument": "Bind document",
- "selectOneDocument": "Please select one document",
"horizontalSuperBlock": "Horizontal super block",
"verticalSuperBlock": "Vertical super block",
"prependSuperBlockColumn": "Add a column to the beginning of the current super block",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 24e704f941..b5d5a49168 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,6 +1,4 @@
{
- "bindDocument": "Vincular documento",
- "selectOneDocument": "Selecciona un solo documento",
"horizontalSuperBlock": "Superbloque horizontal",
"verticalSuperBlock": "Superbloque vertical",
"prependSuperBlockColumn": "Añadir una columna al principio del superbloque actual",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 267f7fb675..8641aa5824 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,6 +1,4 @@
{
- "bindDocument": "Lier un document",
- "selectOneDocument": "Veuillez sélectionner un seul document",
"horizontalSuperBlock": "Superblock horizontal",
"verticalSuperBlock": "Superblock vertical",
"prependSuperBlockColumn": "Ajouter une colonne au début du superblock actuel",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index b15dd94095..7a511926c5 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,6 +1,4 @@
{
- "bindDocument": "קישור מסמך",
- "selectOneDocument": "נא לבחור מסמך אחד",
"horizontalSuperBlock": "בלוק עליון אופקי",
"verticalSuperBlock": "בלוק עליון אנכי",
"prependSuperBlockColumn": "הוספת עמודה לתחילת הבלוק העליון הנוכחי",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index f3be82daa7..5a4febf771 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,6 +1,4 @@
{
- "bindDocument": "दस्तावेज़ जोड़ें",
- "selectOneDocument": "कृपया एक दस्तावेज़ चुनें",
"horizontalSuperBlock": "क्षैतिज सुपर ब्लॉक",
"verticalSuperBlock": "लंबवत सुपर ब्लॉक",
"prependSuperBlockColumn": "वर्तमान सुपर ब्लॉक की शुरुआत में कॉलम जोड़ें",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 033c77b33b..f1b4832298 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,6 +1,4 @@
{
- "bindDocument": "Tautkan dokumen",
- "selectOneDocument": "Silakan pilih satu dokumen",
"horizontalSuperBlock": "Super blok horizontal",
"verticalSuperBlock": "Super blok vertikal",
"prependSuperBlockColumn": "Tambahkan kolom ke awal super blok saat ini",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index e087aa4918..5eae44e8fd 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,6 +1,4 @@
{
- "bindDocument": "Collega documento",
- "selectOneDocument": "Seleziona un solo documento",
"horizontalSuperBlock": "Super blocco orizzontale",
"verticalSuperBlock": "Super blocco verticale",
"prependSuperBlockColumn": "Aggiungi una colonna all'inizio del super blocco corrente",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 0b1c535644..9015dfdbaa 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,6 +1,4 @@
{
- "bindDocument": "ドキュメントを関連付ける",
- "selectOneDocument": "ドキュメントを1つ選択してください",
"horizontalSuperBlock": "横向きスーパーブロック",
"verticalSuperBlock": "縦向きスーパーブロック",
"prependSuperBlockColumn": "現在のスーパーブロックの先頭に列を追加",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 2c28affb03..33c6854d1f 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,6 +1,4 @@
{
- "bindDocument": "문서 연결",
- "selectOneDocument": "문서를 하나 선택하세요",
"horizontalSuperBlock": "가로 슈퍼 블록",
"verticalSuperBlock": "세로 슈퍼 블록",
"prependSuperBlockColumn": "현재 슈퍼 블록 시작 부분에 열 추가",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 922a71535c..ab5c755759 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,6 +1,4 @@
{
- "bindDocument": "Document koppelen",
- "selectOneDocument": "Selecteer één document",
"horizontalSuperBlock": "Horizontaal superblok",
"verticalSuperBlock": "Verticaal superblok",
"prependSuperBlockColumn": "Kolom toevoegen aan het begin van het huidige superblok",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 10ad159421..3cf36bf7ac 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,6 +1,4 @@
{
- "bindDocument": "Powiąż dokument",
- "selectOneDocument": "Wybierz jeden dokument",
"horizontalSuperBlock": "Poziomy super blok",
"verticalSuperBlock": "Pionowy super blok",
"prependSuperBlockColumn": "Dodaj kolumnę na początku bieżącego super bloku",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 77f96dc872..5be89c7853 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,6 +1,4 @@
{
- "bindDocument": "Vincular documento",
- "selectOneDocument": "Selecione um documento",
"horizontalSuperBlock": "Super bloco horizontal",
"verticalSuperBlock": "Super bloco vertical",
"prependSuperBlockColumn": "Adicionar uma coluna ao início do super bloco atual",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 537a516ad1..2a4dbf796b 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,6 +1,4 @@
{
- "bindDocument": "Привязать документ",
- "selectOneDocument": "Выберите один документ",
"horizontalSuperBlock": "Горизонтальный супер блок",
"verticalSuperBlock": "Вертикальный супер блок",
"prependSuperBlockColumn": "Добавить столбец в начало текущего супер блока",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 870c95d04c..1393f9bfa0 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,6 +1,4 @@
{
- "bindDocument": "Prepojiť dokument",
- "selectOneDocument": "Vyberte jeden dokument",
"horizontalSuperBlock": "Horizontálny super blok",
"verticalSuperBlock": "Vertikálny super blok",
"prependSuperBlockColumn": "Pridať stĺpec na začiatok aktuálneho super bloku",
diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.json
index fbe8de5779..7e3b728c06 100644
--- a/app/appearance/langs/sr.json
+++ b/app/appearance/langs/sr.json
@@ -1,6 +1,4 @@
{
- "bindDocument": "Повежи документ",
- "selectOneDocument": "Изаберите један документ",
"horizontalSuperBlock": "Horizontalni superblok",
"verticalSuperBlock": "Vertikalni superblok",
"prependSuperBlockColumn": "Dodaj kolonu na početak trenutnog superbloka",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 6e141baed8..772ce55e38 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,6 +1,4 @@
{
- "bindDocument": "เชื่อมโยงเอกสาร",
- "selectOneDocument": "โปรดเลือกเอกสารหนึ่งรายการ",
"horizontalSuperBlock": "ซูเปอร์บล็อกแนวนอน",
"verticalSuperBlock": "ซูเปอร์บล็อกแนวตั้ง",
"prependSuperBlockColumn": "เพิ่มคอลัมน์ที่จุดเริ่มต้นของซูเปอร์บล็อกปัจจุบัน",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 5304c12637..2268905630 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,6 +1,4 @@
{
- "bindDocument": "Belge bağla",
- "selectOneDocument": "Lütfen bir belge seçin",
"horizontalSuperBlock": "Yatay süper blok",
"verticalSuperBlock": "Dikey süper blok",
"prependSuperBlockColumn": "Geçerli süper bloğun başına sütun ekle",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index b52f16beaf..8f2f822d71 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,6 +1,4 @@
{
- "bindDocument": "Прив’язати документ",
- "selectOneDocument": "Виберіть один документ",
"horizontalSuperBlock": "Горизонтальний суперблок",
"verticalSuperBlock": "Вертикальний суперблок",
"prependSuperBlockColumn": "Додати стовпець на початок поточного суперблока",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 73dd4f63e1..6229ab4558 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,6 +1,4 @@
{
- "bindDocument": "绑定文档",
- "selectOneDocument": "请选择一个文档",
"horizontalSuperBlock": "横向超级块",
"verticalSuperBlock": "纵向超级块",
"prependSuperBlockColumn": "在当前超级块开头添加分栏",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 2caf1ce84b..37c4838b67 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,6 +1,4 @@
{
- "bindDocument": "綁定文件",
- "selectOneDocument": "請選擇一個文件",
"horizontalSuperBlock": "橫向超級區塊",
"verticalSuperBlock": "縱向超級區塊",
"prependSuperBlockColumn": "在目前超級區塊開頭新增分欄",
diff --git a/app/src/editor/databaseRow.ts b/app/src/editor/databaseRow.ts
index 2873b10528..752fd18f62 100644
--- a/app/src/editor/databaseRow.ts
+++ b/app/src/editor/databaseRow.ts
@@ -8,6 +8,7 @@ import {searchMarkRender} from "../protyle/render/searchMarkRender";
import {registerDatabaseRowRefresh} from "../protyle/render/av/databaseRowRefresh";
import {focusDatabasePrimary} from "../protyle/render/av/primaryFocus";
import {setPanelFocus} from "../layout/util";
+import {preserveAVBindingRange} from "../protyle/render/av/binding";
export const newDatabaseRowModel = (options: {
app: App,
@@ -23,6 +24,7 @@ export const newDatabaseRowModel = (options: {
matchedKeyID?: string,
keywords?: string[],
focusPrimary?: boolean,
+ bindPrimary?: boolean,
},
}) => {
let customModel: Custom;
@@ -74,7 +76,9 @@ export const newDatabaseRowModel = (options: {
return;
}
// 保留当前内容,待属性和反链加载完成后一次替换,避免刷新期间出现空白。
+ const restoreBindingRange = preserveAVBindingRange(contextProtyle, previousBodyElement);
previousBodyElement.replaceWith(element);
+ restoreBindingRange(element);
updateLayout(custom);
updateTitle(custom, element);
focusDatabasePrimary(custom.element, contextProtyle, data);
@@ -142,7 +146,7 @@ export const newDatabaseRowModel = (options: {
getAVID: () => (customModel.data as typeof options.data).avID,
refresh: () => render(customModel),
});
- custom.element.append(contextProtyle.highlight.styleElement);
+ custom.element.append(contextProtyle.highlight.styleElement, contextProtyle.hint.element);
render(custom);
},
});
diff --git a/app/src/protyle/hint/extend.ts b/app/src/protyle/hint/extend.ts
index daaa552671..03bde9ba26 100644
--- a/app/src/protyle/hint/extend.ts
+++ b/app/src/protyle/hint/extend.ts
@@ -573,7 +573,8 @@ export const genHintItemHTML = (item: IBlock) => {
};
export const hintRef = (key: string, protyle: IProtyle, source: THintSource): IHintData[] => {
- const nodeElement = hasClosestBlock(getEditorRange(protyle.wysiwyg.element).startContainer);
+ const nodeElement = hasClosestBlock((source === "av" ? protyle.toolbar.range :
+ getEditorRange(protyle.wysiwyg.element)).startContainer);
const createTarget = protyle.hint.prepareCreateTarget(protyle, "ref");
protyle.hint.genLoading(protyle);
let refParam: import("../../types/api").SearchRefBlockRequestInput;
diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.ts
index c46d069d55..7778523db3 100644
--- a/app/src/protyle/hint/index.ts
+++ b/app/src/protyle/hint/index.ts
@@ -66,7 +66,7 @@ import {isNotCtrl, isOnlyMeta} from "../util/compatibility";
import {avRender} from "../render/av/render";
import {genIconHTML} from "../render/util";
import {updateAttrViewCellAnimation} from "../render/av/action";
-import {getAVBindingOperations} from "../render/av/binding";
+import {getAVBindingCell, getAVBindingOperations} from "../render/av/binding";
import {isRangeInEditor} from "../../util/newFileSelection";
import {genCellValueByElement} from "../render/av/cell";
import {setFold} from "../util/blockFold";
@@ -468,7 +468,7 @@ export class Hint {
this.element.innerHTML = '<div class="fn__loading" style="height: 128px;position: initial"><img width="64px" src="/stage/loading-pure.svg"></div>';
this.element.classList.remove("fn__none");
if (this.source === "av") {
- const cellElement = hasClosestByClassName(protyle.toolbar.range.startContainer, "av__cell");
+ const cellElement = getAVBindingCell(protyle.toolbar.range);
if (cellElement) {
const cellRect = cellElement.getBoundingClientRect();
/// #if !MOBILE
@@ -587,7 +587,7 @@ export class Hint {
this.element.classList.remove("hint--menu");
}
if (this.source === "av") {
- const cellElement = hasClosestByClassName(protyle.toolbar.range.startContainer, "av__cell");
+ const cellElement = getAVBindingCell(protyle.toolbar.range);
if (cellElement) {
const cellRect = cellElement.getBoundingClientRect();
/// #if !MOBILE
@@ -807,20 +807,28 @@ ${genHintItemHTML(item)}
return;
}
if (this.source === "av") {
- let cellElement = hasClosestByClassName(protyle.toolbar.range.startContainer, "av__cell");
+ let cellElement = getAVBindingCell(protyle.toolbar.range);
if (!cellElement) {
cellElement = nodeElement.querySelector(".av__cell--select") as HTMLElement;
}
- if (!cellElement) {
+ if (!cellElement?.isConnected || protyle.disabled || window.siyuan.isPublish ||
+ protyle.options.history?.created || protyle.options.history?.snapshot) {
return;
}
- const rowElement = hasClosestByClassName(cellElement, isTableLikeView(nodeElement.getAttribute("data-av-type")) ? "av__row" : "av__gallery-item");
+ const panelCell = cellElement.hasAttribute("data-row-id");
+ const rowElement = panelCell ? cellElement : hasClosestByClassName(cellElement,
+ isTableLikeView(nodeElement.getAttribute("data-av-type")) ? "av__row" : "av__gallery-item");
if (!rowElement) {
return;
}
- const previousID = rowElement.dataset.id;
+ const previousID = panelCell ? rowElement.dataset.rowId : rowElement.dataset.id;
const avID = nodeElement.getAttribute("data-av-id");
const previousValue = genCellValueByElement("block", cellElement);
+ const updatePreview = (nextValue: IAVCellValue) => {
+ if (!panelCell) {
+ updateAttrViewCellAnimation(cellElement, nextValue);
+ }
+ };
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];
@@ -832,9 +840,10 @@ ${genHintItemHTML(item)}
// 选址期间条目可能被删除、换绑或重绘,始终校验原条目及其主键值。
const isValid = () => protyle.notebookId === notebookId && protyle.path === path &&
protyle.block.rootID === rootID && nodeElement.isConnected && bindingCell.isConnected &&
- protyle.wysiwyg.element.contains(nodeElement) && nodeElement.contains(rowElement) &&
+ (panelCell || protyle.wysiwyg.element.contains(nodeElement)) && nodeElement.contains(rowElement) &&
rowElement.contains(bindingCell) && nodeElement.dataset.nodeId === blockID &&
- nodeElement.getAttribute("data-av-id") === avID && rowElement.dataset.id === previousID &&
+ nodeElement.getAttribute("data-av-id") === avID &&
+ (panelCell ? rowElement.dataset.rowId : rowElement.dataset.id) === previousID &&
JSON.stringify(genCellValueByElement("block", bindingCell)) === savedValue;
newFileAtPath({
notebookId,
@@ -849,7 +858,7 @@ ${genHintItemHTML(item)}
const operations = getAVBindingOperations(avID, previousID, id, blockID,
previousValue, {protyleID: protyle.id});
transaction(protyle, operations.doOperations, operations.undoOperations);
- updateAttrViewCellAnimation(bindingCell, {
+ updatePreview({
type: "block",
isDetached: false,
block: {content: title, id},
@@ -877,7 +886,7 @@ ${genHintItemHTML(item)}
} else {
newFileByRefHint(protyle, realFileName, bindNewDoc, newID);
}
- updateAttrViewCellAnimation(cellElement, {
+ updatePreview({
type: "block",
isDetached: false,
block: {content: realFileName, id: newID}
@@ -887,7 +896,7 @@ ${genHintItemHTML(item)}
const operations = getAVBindingOperations(avID, previousID, sourceId, nodeElement.dataset.nodeId,
previousValue, {protyleID: protyle.id});
transaction(protyle, operations.doOperations, operations.undoOperations);
- updateAttrViewCellAnimation(cellElement, {
+ updatePreview({
type: "block",
isDetached: false,
block: {
diff --git a/app/src/protyle/render/av/action.ts b/app/src/protyle/render/av/action.ts
index 11237ff914..1ef352de2f 100644
--- a/app/src/protyle/render/av/action.ts
+++ b/app/src/protyle/render/av/action.ts
@@ -55,7 +55,6 @@ import {removeCompressURL} from "../../../util/image";
import {callMobileAppShowKeyboard} from "../../../mobile/util/mobileAppUtil";
import {createAttributeViewItem, createAttributeViewItemDocs, openNewItemTemplateMenu} from "./newItemTemplate";
import {openDatabaseRowByData} from "./openDatabaseRow";
-import {openAVBindDocument} from "./bindDocument";
import {openKanbanGroupMenu} from "./kanban/groupMenu";
import {getGroupFoldedStates, updateGroupFoldedStates} from "./groupFold";
import {setPublishAVFolds, setPublishAVView} from "./publishState";
@@ -1190,6 +1189,25 @@ export const avContextmenu = (protyle: IProtyle, rowElement: HTMLElement | undef
}
});
}
+ if (selectedItemInfos.length === 1 && primaryRows[0].isDetached) {
+ menu.addItem({
+ id: "bindDocument",
+ label: window.siyuan.languages.bind,
+ icon: "iconLink",
+ click() {
+ openDatabaseRowByData(protyle, {
+ avID: blockElement.dataset.avId,
+ databaseBlockID: blockElement.dataset.nodeId,
+ notebookID: protyle.notebookId,
+ itemID: selectedItemInfos[0].itemID,
+ valueID: primaryRows[0].valueID,
+ title: primaryRows[0].content.trim(),
+ isDetached: true,
+ bindPrimary: true,
+ });
+ }
+ });
+ }
menu.addItem({
id: "addToDatabase",
label: window.siyuan.languages.addToDatabase,
@@ -1313,16 +1331,6 @@ ${window.siyuan.languages[isTableLikeView(avType) ? "insertRowAfter" : "insertIt
});
menu.addSeparator({id: "separator_2"});
}
- if (selectedItemInfos.length === 1 && primaryRows[0].isDetached) {
- menu.addItem({
- id: "bindDocument",
- label: window.siyuan.languages.bindDocument,
- icon: "iconLink",
- click() {
- openAVBindDocument(protyle, blockElement, selectedItemInfos[0].itemID);
- }
- });
- }
if (hasBlock) {
menu.addItem({
id: "unbindBlock",
diff --git a/app/src/protyle/render/av/attributeValue.ts b/app/src/protyle/render/av/attributeValue.ts
index 07c46b0458..b397e658de 100644
--- a/app/src/protyle/render/av/attributeValue.ts
+++ b/app/src/protyle/render/av/attributeValue.ts
@@ -133,7 +133,7 @@ export const genAVValueHTML = (value: IAVCellValue, dateFormat: TAVDateFormat =
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}">
-<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.bindDocument : window.siyuan.languages.rebind}"><svg><use xlink:href="#iconLink"></use></svg></button>`;
+<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": {
const source = getAVTextSource(value);
diff --git a/app/src/protyle/render/av/bindBlock.test.ts b/app/src/protyle/render/av/bindBlock.test.ts
new file mode 100644
index 0000000000..8cfe7071d0
--- /dev/null
+++ b/app/src/protyle/render/av/bindBlock.test.ts
@@ -0,0 +1,34 @@
+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";
+
+test("panel binding searches the primary text and anchors to the original field", () => {
+ const requests: unknown[][] = [];
+ let selected: HTMLElement;
+ const range = {selectNodeContents: (element: HTMLElement) => { selected = element; }};
+ const protyle = {options: {}, toolbar: {}} as IProtyle;
+ const field = {isConnected: true, dataset: {rowId: "item"},
+ querySelector: () => ({value: " Current title "})} as unknown as HTMLElement;
+ const exports = {} as typeof import("./bindBlock");
+ runInNewContext(transpileModule(readFileSync(join(__dirname, "bindBlock.ts"), "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2020},
+ }).outputText, {
+ exports,
+ require: () => ({hintRef: (...args: unknown[]) => requests.push(args)}),
+ document: {createRange: () => range},
+ window: {siyuan: {menus: {menu: {remove() {}}}}},
+ });
+ exports.openAVBindBlock(protyle, field);
+ assert.equal(selected, field);
+ assert.equal(protyle.toolbar.range, range);
+ assert.deepEqual(requests, [["Current title", protyle, "av"]]);
+ protyle.disabled = true;
+ exports.openAVBindBlock(protyle, field);
+ protyle.disabled = false;
+ protyle.options.history = {snapshot: "snapshot"} as IProtyle["options"]["history"];
+ exports.openAVBindBlock(protyle, field);
+ assert.equal(requests.length, 1);
+});
diff --git a/app/src/protyle/render/av/bindBlock.ts b/app/src/protyle/render/av/bindBlock.ts
new file mode 100644
index 0000000000..77a690551a
--- /dev/null
+++ b/app/src/protyle/render/av/bindBlock.ts
@@ -0,0 +1,12 @@
+import {hintRef} from "../../hint/extend";
+
+export const openAVBindBlock = (protyle: IProtyle, field: HTMLElement) => {
+ if (!field.isConnected || !field.dataset.rowId || protyle.disabled || window.siyuan.isPublish ||
+ protyle.options.history?.created || protyle.options.history?.snapshot) {
+ return;
+ }
+ window.siyuan.menus.menu.remove();
+ protyle.toolbar.range = document.createRange();
+ protyle.toolbar.range.selectNodeContents(field);
+ hintRef(field.querySelector("input")?.value.trim() || "", protyle, "av");
+};
diff --git a/app/src/protyle/render/av/bindDocument.test.ts b/app/src/protyle/render/av/bindDocument.test.ts
deleted file mode 100644
index be119edaf4..0000000000
--- a/app/src/protyle/render/av/bindDocument.test.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-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 {getAVBindingOperations} from "./binding";
-
-test("document binding validates document selection and reads the current binding for undo", async () => {
- let choose: (paths: string[]) => boolean | void;
- let message = "";
- let value: IAVCellValue = {type: "block", blockID: "item", isDetached: true, block: {id: "", content: "Title"}};
- const requests: unknown[] = [];
- const transactions: IOperation[][][] = [];
- const protyle = {id: "editor", options: {}} as IProtyle;
- const block = {dataset: {avId: "database", nodeId: "carrier"}, isConnected: true};
- const modules: Record<string, unknown> = {
- "../../../util/pathName": {movePathTo: (options: {cb: typeof choose, validate: (paths: string[]) => boolean}) => {
- choose = paths => options.validate(paths) ? options.cb(paths) : false;
- }},
- "../../../dialog/message": {showMessage: (text: string) => { message = text; }},
- "../../../util/fetch": {fetchSyncPost: async (_path: string, body: unknown) => {
- requests.push(body);
- return {code: 0, data: [{avID: "database", keyValues: [{key: {type: "block"}, values: value ? [value] : []}]}]};
- }},
- "../../wysiwyg/transaction": {transaction: (_owner: IProtyle, ...operations: IOperation[][]) => transactions.push(operations)},
- "./binding": {getAVBindingOperations},
- };
- const exports = {} as typeof import("./bindDocument");
- runInNewContext(transpileModule(readFileSync(join(__dirname, "bindDocument.ts"), "utf8"), {
- compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2020},
- }).outputText, {exports, require: (name: string) => modules[name], window: {siyuan: {languages: {selectOneDocument: "Select one"}}}});
- exports.openAVBindDocument(protyle, block as unknown as HTMLElement, "item");
- assert.equal(choose(["/"]), false);
- assert.equal(choose(["/first.sy", "/second.sy"]), false);
- assert.equal(message, "Select one");
- assert.equal(requests.length, 0);
- for (const oldID of ["", "old-document"]) {
- value = {...value, isDetached: !oldID, block: {id: oldID, content: "Title"}};
- choose(["/parent/new-document.sy"]);
- await new Promise(resolve => setTimeout(resolve, 0));
- const [redo, undo] = transactions[transactions.length - 1];
- assert.equal(redo[0].nextID, "new-document");
- assert.equal(redo[0].previousID, "item");
- assert.equal(redo[0].blockID, "carrier");
- assert.equal(undo[0].nextID, oldID);
- assert.equal(undo[0].isDetached, !oldID);
- }
- assert.deepEqual(JSON.parse(JSON.stringify(requests[0])), {id: "item", avID: "database", itemID: "item"});
- value = undefined;
- choose(["/deleted-item.sy"]);
- await new Promise(resolve => setTimeout(resolve, 0));
- assert.equal(transactions.length, 2);
- value = {type: "block", blockID: "item", block: {id: "previous", content: "Title"}};
- choose(["/readonly.sy"]);
- protyle.disabled = true;
- await new Promise(resolve => setTimeout(resolve, 0));
- assert.equal(transactions.length, 2);
- choose = undefined;
- exports.openAVBindDocument(protyle, block as unknown as HTMLElement, "item");
- assert.equal(choose, undefined);
-});
diff --git a/app/src/protyle/render/av/bindDocument.ts b/app/src/protyle/render/av/bindDocument.ts
deleted file mode 100644
index c2a84c83ec..0000000000
--- a/app/src/protyle/render/av/bindDocument.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import {movePathTo} from "../../../util/pathName";
-import {fetchSyncPost} from "../../../util/fetch";
-import {showMessage} from "../../../dialog/message";
-import {transaction} from "../../wysiwyg/transaction";
-import {getAVBindingOperations} from "./binding";
-
-export const openAVBindDocument = (protyle: IProtyle, blockElement: HTMLElement, itemID: string) => {
- const canEdit = () => blockElement.isConnected && !protyle.disabled && !window.siyuan.isPublish &&
- !protyle.options.history?.created && !protyle.options.history?.snapshot;
- if (!itemID || !canEdit()) {
- return;
- }
- const avID = blockElement.dataset.avId;
- const blockID = blockElement.dataset.nodeId;
- const bind = async (nextID: string) => {
- // 确认选址后读取当前绑定,保留条目身份及可撤销的原绑定。
- const response = await fetchSyncPost("/api/av/getAttributeViewKeys", {id: itemID, avID, itemID});
- if (response.code !== 0 || !canEdit()) {
- return;
- }
- const table = response.data.find(item => item.avID === avID);
- const value = table?.keyValues.find(item => item.key.type === "block")?.values.find(item => item.blockID === itemID);
- if (!value || !value.isDetached && value.block?.id === nextID) {
- return;
- }
- const operations = getAVBindingOperations(avID, itemID, nextID, blockID, value, {protyleID: protyle.id});
- transaction(protyle, operations.doOperations, operations.undoOperations);
- };
- movePathTo({
- title: window.siyuan.languages.bindDocument,
- flashcard: false,
- validate(paths) {
- if (paths.length !== 1 || !paths[0].endsWith(".sy")) {
- showMessage(window.siyuan.languages.selectOneDocument);
- return false;
- }
- return true;
- },
- cb(paths) {
- const path = paths[0];
- void bind(path.substring(path.lastIndexOf("/") + 1, path.length - 3));
- },
- });
-};
diff --git a/app/src/protyle/render/av/binding.test.ts b/app/src/protyle/render/av/binding.test.ts
index 8e121e9e5f..88df9440b7 100644
--- a/app/src/protyle/render/av/binding.test.ts
+++ b/app/src/protyle/render/av/binding.test.ts
@@ -1,6 +1,6 @@
import * as assert from "node:assert/strict";
import {test} from "node:test";
-import {getAVBindingOperations} from "./binding";
+import {getAVBindingOperations, preserveAVBindingRange} from "./binding";
for (const isDetached of [false, true]) {
test(`binding operations preserve item identity and the ${isDetached ? "detached" : "bound"} original`, () => {
@@ -21,3 +21,35 @@ for (const isDetached of [false, true]) {
assert.equal(undoOperations[0].isDetached, isDetached);
});
}
+
+test("binding candidates follow a refreshed panel field but close when its binding changes", () => {
+ let selected: unknown;
+ let hidden = false;
+ const oldCell = {
+ nodeType: 1,
+ dataset: {avId: "database", rowId: "item", colId: "primary"},
+ querySelector: () => ({dataset: {id: "old-block"}}),
+ closest: (): unknown => oldCell,
+ };
+ const range = {startContainer: oldCell, selectNodeContents: (cell: unknown) => { selected = cell; }};
+ const protyle = {
+ toolbar: {range},
+ hint: {element: {classList: {contains: () => hidden, add: () => { hidden = true; }}}},
+ } as unknown as IProtyle;
+ const panel = {contains: (cell: unknown) => cell === oldCell} as HTMLElement;
+ let boundID = "old-block";
+ const newCell = {querySelector: () => ({dataset: {id: boundID}})};
+ const nextPanel = {querySelector: (selector: string) => {
+ assert.equal(selector, '[data-av-id="database"][data-row-id="item"][data-col-id="primary"]');
+ return newCell;
+ }} as unknown as HTMLElement;
+ const restore = preserveAVBindingRange(protyle, panel);
+ restore(nextPanel);
+ assert.equal(selected, newCell);
+ assert.equal(hidden, false);
+ selected = undefined;
+ boundID = "other-block";
+ restore(nextPanel);
+ assert.equal(selected, undefined);
+ assert.equal(hidden, true);
+});
diff --git a/app/src/protyle/render/av/binding.ts b/app/src/protyle/render/av/binding.ts
index 8877a9d50e..256ef14bd5 100644
--- a/app/src/protyle/render/av/binding.ts
+++ b/app/src/protyle/render/av/binding.ts
@@ -8,3 +8,32 @@ export const getAVBindingOperations = (avID: string, itemID: string, nextID: str
undoOperations: [{...base, nextID: isDetached ? "" : previousValue.block.id, isDetached}] as IOperation[],
};
};
+
+// 表格单元格和数据库面板共用绑定候选,使用原始字段作为定位与事务目标。
+export const getAVBindingCell = (range: Range): HTMLElement | null => {
+ if (!range) {
+ return null;
+ }
+ const node = range.startContainer;
+ const element = node.nodeType === 1 ? node as HTMLElement : node.parentElement;
+ return element?.closest<HTMLElement>('.av__cell, [data-row-id][data-col-id][data-type="block"]') || null;
+};
+
+// 属性保存会重绘面板,将正在使用的绑定候选重新定位到同一条目的字段。
+export const preserveAVBindingRange = (protyle: IProtyle, element: HTMLElement) => {
+ const range = protyle.toolbar.range;
+ const cell = getAVBindingCell(range);
+ if (!cell?.dataset.rowId || !element.contains(cell) || protyle.hint.element.classList.contains("fn__none")) {
+ return () => {};
+ }
+ const selector = `[data-av-id="${cell.dataset.avId}"][data-row-id="${cell.dataset.rowId}"][data-col-id="${cell.dataset.colId}"]`;
+ const boundID = cell.querySelector("input")?.dataset.id;
+ return (nextElement: HTMLElement) => {
+ const nextCell = nextElement.querySelector<HTMLElement>(selector);
+ if (nextCell && nextCell.querySelector("input")?.dataset.id === boundID) {
+ range.selectNodeContents(nextCell);
+ } else {
+ protyle.hint.element.classList.add("fn__none");
+ }
+ };
+};
diff --git a/app/src/protyle/render/av/blockAttr.ts b/app/src/protyle/render/av/blockAttr.ts
index 7dde2a92f0..ae4e78922f 100644
--- a/app/src/protyle/render/av/blockAttr.ts
+++ b/app/src/protyle/render/av/blockAttr.ts
@@ -17,7 +17,8 @@ import {isBrowser, isTouchDevice} from "../../../util/functions";
import {Constants} from "../../../constants";
import {removeCompressURL} from "../../../util/image";
import {openDatabaseRowByData} from "./openDatabaseRow";
-import {openAVBindDocument} from "./bindDocument";
+import {openAVBindBlock} from "./bindBlock";
+import {preserveAVBindingRange} from "./binding";
import {confirmDialog} from "../../../dialog/confirmDialog";
import {
createEmptyAVValue,
@@ -133,6 +134,7 @@ export const renderAVAttribute = (element: HTMLElement, id: string, protyle: IPr
if (element.dataset.avAttributeRenderId !== renderID) {
return;
}
+ const restoreBindingRange = preserveAVBindingRange(protyle, element);
let html = "";
const tables = Array.isArray(response.data) ? response.data : [];
tables.forEach((table) => {
@@ -344,6 +346,10 @@ export const renderAVAttribute = (element: HTMLElement, id: string, protyle: IPr
}
});
element.addEventListener("mousedown", (event) => {
+ if (hasClosestByAttribute(event.target as HTMLElement, "data-type", "av-bind-document")) {
+ event.preventDefault();
+ return;
+ }
if (!hasClosestByAttribute(event.target as HTMLElement, "data-type", "remove")) {
return;
}
@@ -415,9 +421,8 @@ export const renderAVAttribute = (element: HTMLElement, id: string, protyle: IPr
const bindElement = hasClosestByAttribute(event.target as HTMLElement, "data-type", "av-bind-document");
if (bindElement) {
const field = bindElement.closest<HTMLElement>("[data-row-id][data-col-id]");
- const blockElement = hasClosestBlock(bindElement) as HTMLElement;
- if (field && blockElement) {
- openAVBindDocument(protyle, blockElement, field.dataset.rowId);
+ if (field) {
+ openAVBindBlock(protyle, field);
}
event.stopPropagation();
return;
@@ -532,6 +537,7 @@ export const renderAVAttribute = (element: HTMLElement, id: string, protyle: IPr
element.innerHTML = html;
}
renderAVRichTextElements(element);
+ restoreBindingRange(element);
element.dataset.readonly = String(Boolean(protyle.disabled));
element.querySelectorAll<HTMLInputElement | HTMLTextAreaElement>("input, textarea").forEach(item => {
item.readOnly = Boolean(protyle.disabled);
diff --git a/app/src/protyle/render/av/openDatabaseRow.ts b/app/src/protyle/render/av/openDatabaseRow.ts
index 5aa80010f3..c7f4c7967b 100644
--- a/app/src/protyle/render/av/openDatabaseRow.ts
+++ b/app/src/protyle/render/av/openDatabaseRow.ts
@@ -14,6 +14,7 @@ import {Custom} from "../../../layout/dock/Custom";
import {searchMarkRender} from "../searchMarkRender";
import {registerDatabaseRowRefresh} from "./databaseRowRefresh";
import {focusDatabasePrimary} from "./primaryFocus";
+import {preserveAVBindingRange} from "./binding";
export interface IDatabaseRowOpenData {
avID: string;
@@ -28,6 +29,7 @@ export interface IDatabaseRowOpenData {
matchedKeyID?: string;
keywords?: string[];
focusPrimary?: boolean;
+ bindPrimary?: boolean;
}
const highlightDatabaseRow = (protyle: IProtyle, rootElement: HTMLElement, data: IDatabaseRowOpenData) => {
@@ -94,7 +96,9 @@ const openMobileDatabaseRow = (protyle: Pick<IProtyle, "app">, data: IDatabaseRo
return;
}
// 保留当前内容,待属性和反链加载完成后一次替换,避免刷新期间出现空白。
+ const restoreBindingRange = preserveAVBindingRange(contextProtyle, previousBodyElement);
previousBodyElement.replaceWith(element);
+ restoreBindingRange(element);
const primaryElement = element.querySelector<HTMLElement>('[data-primary="true"] [data-cell-value]');
if (primaryElement?.dataset.cellValue) {
const value = JSON.parse(decodeURIComponent(primaryElement.dataset.cellValue)) as IAVCellValue;
@@ -121,7 +125,7 @@ const openMobileDatabaseRow = (protyle: Pick<IProtyle, "app">, data: IDatabaseRo
getAVID: () => data.avID,
refresh: () => render(contextProtyle),
});
- rowElement.append(contextProtyle.highlight.styleElement);
+ rowElement.append(contextProtyle.highlight.styleElement, contextProtyle.hint.element);
render(contextProtyle);
},
});
@@ -232,6 +236,7 @@ export const openDatabaseRowByData = async (protyle: Pick<IProtyle, "app">, data
matchedKeyID: data.matchedKeyID,
keywords: data.keywords,
focusPrimary: data.focusPrimary,
+ bindPrimary: data.bindPrimary,
},
},
afterOpen(model) {
diff --git a/app/src/protyle/render/av/primaryFocus.test.ts b/app/src/protyle/render/av/primaryFocus.test.ts
index 8f31ee576e..1e80ddf31d 100644
--- a/app/src/protyle/render/av/primaryFocus.test.ts
+++ b/app/src/protyle/render/av/primaryFocus.test.ts
@@ -32,3 +32,20 @@ test("database items focus once without replacing existing text or stealing focu
}
assert.equal(focused, 1);
});
+
+test("opening an item for binding shows primary candidates only once", () => {
+ const field = {} as HTMLElement;
+ const root = {isConnected: true, querySelector: () => field} as unknown as Element;
+ const calls: unknown[][] = [];
+ const exports = {} as typeof import("./primaryFocus");
+ runInNewContext(ts.transpileModule(readFileSync(join(__dirname, "primaryFocus.ts"), "utf8"), {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022},
+ }).outputText, {exports, window: {siyuan: {}}, require: () => ({
+ openAVBindBlock: (...args: unknown[]) => calls.push(args),
+ })});
+ const request = {avID: "av", itemID: "row", bindPrimary: true};
+ const protyle = {options: {}} as IProtyle;
+ exports.focusDatabasePrimary(root, protyle, request);
+ exports.focusDatabasePrimary(root, protyle, request);
+ assert.deepEqual(calls, [[protyle, field]]);
+});
diff --git a/app/src/protyle/render/av/primaryFocus.ts b/app/src/protyle/render/av/primaryFocus.ts
index bce6c5ea71..bab2e6b369 100644
--- a/app/src/protyle/render/av/primaryFocus.ts
+++ b/app/src/protyle/render/av/primaryFocus.ts
@@ -1,18 +1,25 @@
import {popTextCell} from "./cell";
+import {openAVBindBlock} from "./bindBlock";
// 打开条目后只在首次完成渲染时进入主键编辑,刷新不重复聚焦,也不覆盖现有内容。
export const focusDatabasePrimary = (root: Element, protyle: IProtyle,
- request: {avID: string; itemID: string; focusPrimary?: boolean}) => {
- if (!request.focusPrimary || !root.isConnected) {
+ request: {avID: string; itemID: string; focusPrimary?: boolean; bindPrimary?: boolean}) => {
+ if ((!request.focusPrimary && !request.bindPrimary) || !root.isConnected) {
return;
}
delete request.focusPrimary;
+ const bindPrimary = request.bindPrimary;
+ delete request.bindPrimary;
if (protyle.disabled || window.siyuan.isPublish || protyle.options.history?.created || protyle.options.history?.snapshot) {
return;
}
const field = root.querySelector<HTMLElement>(
`[data-av-id="${request.avID}"] [data-primary="true"] [data-row-id="${request.itemID}"]`);
if (field) {
+ if (bindPrimary) {
+ openAVBindBlock(protyle, field);
+ return;
+ }
const input = field.querySelector<HTMLInputElement>("input");
if (input && !input.disabled && !input.readOnly) {
input.focus();