Skip to content

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

:sparkles: Support choosing a location when creating database-bound documents https://github.com/siyuan-note/siyuan/issues/19888

Daniel1365ad694eba
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101256-f8b1sbi.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101256-f8b1sbi.sy
index 4e29656fd3..7572873ee5 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101256-f8b1sbi.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101256-f8b1sbi.sy
@@ -6,7 +6,7 @@
"id": "20200924101256-f8b1sbi",
"title": "Ref Content Block",
"type": "doc",
- "updated": "20260927091603"
+ "updated": "20260927161549"
},
"Children": [
{
@@ -15,7 +15,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20200924101312-jj4e0v3",
- "updated": "20260927091603"
+ "updated": "20260927161549"
},
"Children": [
{
@@ -61,7 +61,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260927091603-y3kej6k",
- "updated": "20260927091603"
+ "updated": "20260927161549"
},
"Children": [
{
@@ -93,7 +93,7 @@
},
{
"Type": "NodeText",
- "Data": " in the reference suggestions to select a notebook root or a parent document. Confirm to create the document there and insert its reference at the original position. This location applies only to this creation and does not change the default save path. Canceling creates no document. This is available on desktop and mobile."
+ "Data": " in the reference suggestions to select a notebook root or a parent document. Confirm to create the document there and insert its reference at the original position. This location applies only to this creation and does not change the default save path. Canceling creates no document. This is available on desktop and mobile. This action is also available when binding or rebinding a database entry. The entry is bound to the new document only after the document has been created successfully; canceling or a creation failure leaves the original binding unchanged."
}
]
},
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200813013559-sgbzl5k.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200813013559-sgbzl5k.sy
index a48a4868ea..99fedba642 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200813013559-sgbzl5k.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200813013559-sgbzl5k.sy
@@ -6,7 +6,7 @@
"id": "20200813013559-sgbzl5k",
"title": "引用内容块",
"type": "doc",
- "updated": "20260927091603"
+ "updated": "20260927161549"
},
"Children": [
{
@@ -15,7 +15,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20200817123136-in6y5m1",
- "updated": "20260927091603"
+ "updated": "20260927161549"
},
"Children": [
{
@@ -61,7 +61,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260927091603-ca0ts26",
- "updated": "20260927091603"
+ "updated": "20260927161549"
},
"Children": [
{
@@ -93,7 +93,7 @@
},
{
"Type": "NodeText",
- "Data": ",指定笔记本根目录或父文档。确认后将在该位置创建文档,并在原位置插入引用。所选位置仅对本次创建生效,不会修改默认保存路径;取消不会创建文档。桌面端和移动端均支持此操作。"
+ "Data": ",指定笔记本根目录或父文档。确认后将在该位置创建文档,并在原位置插入引用。所选位置仅对本次创建生效,不会修改默认保存路径;取消不会创建文档。桌面端和移动端均支持此操作。数据库条目绑定或重新绑定文档时也可使用此操作。文档创建成功后才会绑定到该条目;取消或创建失败不会改变原有绑定。"
}
]
},
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120247-63nd8y5.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120247-63nd8y5.sy
index 2d83a554f5..c195830d90 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120247-63nd8y5.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120247-63nd8y5.sy
@@ -6,7 +6,7 @@
"id": "20211226120247-63nd8y5",
"title": "引用内容區塊",
"type": "doc",
- "updated": "20260927091603"
+ "updated": "20260927161549"
},
"Children": [
{
@@ -15,7 +15,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20211226120337-x5qwass",
- "updated": "20260927091603"
+ "updated": "20260927161549"
},
"Children": [
{
@@ -61,7 +61,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260927091603-savpene",
- "updated": "20260927091603"
+ "updated": "20260927161549"
},
"Children": [
{
@@ -93,7 +93,7 @@
},
{
"Type": "NodeText",
- "Data": ",指定筆記本根目錄或父文件。確認後將在該位置建立文件,並在原位置插入區塊引用。所選位置僅對本次建立生效,不會修改預設儲存路徑;取消不會建立文件。桌面端和行動端均支援此操作。"
+ "Data": ",指定筆記本根目錄或父文件。確認後將在該位置建立文件,並在原位置插入區塊引用。所選位置僅對本次建立生效,不會修改預設儲存路徑;取消不會建立文件。桌面端和行動端均支援此操作。資料庫項目綁定或重新綁定文件時也可使用此操作。文件建立成功後才會綁定到該項目;取消或建立失敗不會改變原有綁定。"
}
]
},
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-uxno1yp.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-uxno1yp.sy
index 08f2a205c8..abdec30453 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-uxno1yp.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-uxno1yp.sy
@@ -7,7 +7,7 @@
"id": "20240530101000-uxno1yp",
"title": "コンテンツブロックの参照",
"type": "doc",
- "updated": "20260927091603"
+ "updated": "20260927161549"
},
"Children": [
{
@@ -17,7 +17,7 @@
"Properties": {
"ID": "20240530101000-3mutq27",
"id": "20240530101000-ggy8jav",
- "updated": "20260927091603"
+ "updated": "20260927161549"
},
"Children": [
{
@@ -73,7 +73,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260927091603-uttae8i",
- "updated": "20260927091603"
+ "updated": "20260927161549"
},
"Children": [
{
@@ -101,7 +101,7 @@
},
{
"Type": "NodeText",
- "Data": " を選ぶと、ノートブックのルートまたは親ドキュメントを指定できます。確定すると、その場所にドキュメントを作成し、元の位置に参照を挿入します。選択した保存先は今回の作成にのみ適用され、既定の保存先は変更されません。キャンセルするとドキュメントは作成されません。デスクトップ版とモバイル版の両方で利用できます。"
+ "Data": " を選ぶと、ノートブックのルートまたは親ドキュメントを指定できます。確定すると、その場所にドキュメントを作成し、元の位置に参照を挿入します。選択した保存先は今回の作成にのみ適用され、既定の保存先は変更されません。キャンセルするとドキュメントは作成されません。デスクトップ版とモバイル版の両方で利用できます。データベースの項目にドキュメントをバインドまたは再バインドするときも、この操作を利用できます。ドキュメントの作成が成功した後にのみ項目をバインドします。キャンセルした場合や作成に失敗した場合、元のバインドは変更されません。"
}
]
},
diff --git a/app/src/protyle/hint/extend.ts b/app/src/protyle/hint/extend.ts
index 0ca63aa7c7..c9838c8e47 100644
--- a/app/src/protyle/hint/extend.ts
+++ b/app/src/protyle/hint/extend.ts
@@ -613,14 +613,12 @@ export const hintRef = (key: string, protyle: IProtyle, source: THintSource): IH
<span class="b3-list-item__text">${window.siyuan.languages.newSubDoc} <mark>${response.data.k}</mark></span></div>`,
});
createItemCount++;
- if (source !== "av") {
- dataList.push({
- value: `((newFileAtPath "${newFileName}"${Constants.ZWSP}'${newFileName}${Lute.Caret}'))`,
- html: `<div class="b3-list-item__first"><svg class="b3-list-item__graphic"><use xlink:href="#iconFolder"></use></svg>
+ dataList.push({
+ value: `((newFileAtPath "${newFileName}"${Constants.ZWSP}'${newFileName}${Lute.Caret}'))`,
+ html: `<div class="b3-list-item__first"><svg class="b3-list-item__graphic"><use xlink:href="#iconFolder"></use></svg>
<span class="b3-list-item__text">${window.siyuan.languages.newFileAtPath} <mark>${response.data.k}</mark></span></div>`,
- });
- createItemCount++;
- }
+ });
+ createItemCount++;
}
response.data.blocks.forEach((item: IBlock) => {
const name = item.name ? stripSearchMark(escapeSearchHighlight(item.name)) : item.refText.replace(new RegExp(Constants.ZWSP, "g"), "");
diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.ts
index a55b540d38..b8bf9361a5 100644
--- a/app/src/protyle/hint/index.ts
+++ b/app/src/protyle/hint/index.ts
@@ -22,6 +22,7 @@ import {
getBlockRefAnchorText,
getDocCreateTemplatePath,
isConfiguredCreateTargetCurrentSubDoc,
+ newFileAtPath,
newFileByRefHint,
newFileByRefHintAtPath,
newFileBySelectRange,
@@ -64,6 +65,7 @@ import {avRender} from "../render/av/render";
import {genIconHTML} from "../render/util";
import {updateAttrViewCellAnimation} from "../render/av/action";
import {getAVBindingOperations} from "../render/av/binding";
+import {isRangeInEditor} from "../../util/newFileSelection";
import {genCellValueByElement} from "../render/av/cell";
import {setFold} from "../util/blockFold";
import {getIconValueKind} from "../../emoji/iconValue";
@@ -680,11 +682,9 @@ export class Hint {
const subDocRefText = `((newSubDoc "${oldValue}"${Constants.ZWSP}'${newFileName}${Lute.Caret}'))`;
searchHTML += `<button style="width: calc(100% - 16px)" class="b3-list-item b3-list-item--two${hideConfiguredCreate && response.data.blocks.length === 0 ? " b3-list-item--focus" : ""}" data-value="${encodeURIComponent(subDocRefText)}"><div class="b3-list-item__first"><svg class="b3-list-item__graphic"><use xlink:href="#iconFile"></use></svg>
<span class="b3-list-item__text">${window.siyuan.languages.newSubDoc} <mark>${response.data.k}</mark></span></div></button>`;
- if (source !== "av") {
- const pathRefText = `((newFileAtPath "${oldValue}"${Constants.ZWSP}'${newFileName}${Lute.Caret}'))`;
- searchHTML += `<button style="width: calc(100% - 16px)" class="b3-list-item b3-list-item--two" data-value="${encodeURIComponent(pathRefText)}"><div class="b3-list-item__first"><svg class="b3-list-item__graphic"><use xlink:href="#iconFolder"></use></svg>
+ const pathRefText = `((newFileAtPath "${oldValue}"${Constants.ZWSP}'${newFileName}${Lute.Caret}'))`;
+ searchHTML += `<button style="width: calc(100% - 16px)" class="b3-list-item b3-list-item--two" data-value="${encodeURIComponent(pathRefText)}"><div class="b3-list-item__first"><svg class="b3-list-item__graphic"><use xlink:href="#iconFolder"></use></svg>
<span class="b3-list-item__text">${window.siyuan.languages.newFileAtPath} <mark>${response.data.k}</mark></span></div></button>`;
- }
}
response.data.blocks.forEach((item: IBlock, index: number) => {
let blockRefHTML;
@@ -824,6 +824,43 @@ ${genHintItemHTML(item)}
const previousID = rowElement.dataset.id;
const avID = nodeElement.getAttribute("data-av-id");
const previousValue = genCellValueByElement("block", cellElement);
+ 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];
+ const {notebookId, path, block: {rootID}} = protyle;
+ const blockID = nodeElement.dataset.nodeId;
+ const bindingCell = cellElement;
+ const savedValue = JSON.stringify(previousValue);
+ const savedRange = range.cloneRange();
+ // 选址期间条目可能被删除、换绑或重绘,始终校验原条目及其主键值。
+ const isValid = () => protyle.notebookId === notebookId && protyle.path === path &&
+ protyle.block.rootID === rootID && nodeElement.isConnected && bindingCell.isConnected &&
+ 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 &&
+ JSON.stringify(genCellValueByElement("block", bindingCell)) === savedValue;
+ newFileAtPath({
+ notebookId,
+ name,
+ isValid,
+ restoreFocus() {
+ if (isRangeInEditor(protyle.wysiwyg.element, savedRange)) {
+ focusByRange(savedRange);
+ }
+ },
+ onCreated(id, title) {
+ const operations = getAVBindingOperations(avID, previousID, id, blockID,
+ previousValue, {protyleID: protyle.id});
+ transaction(protyle, operations.doOperations, operations.undoOperations);
+ updateAttrViewCellAnimation(bindingCell, {
+ type: "block",
+ isDetached: false,
+ block: {content: title, id},
+ });
+ },
+ });
+ return;
+ }
let tempElement = document.createElement("div");
tempElement.innerHTML = value.replace(/<mark>/g, "").replace(/<\/mark>/g, "");
tempElement = tempElement.firstElementChild as HTMLDivElement;
diff --git a/app/src/util/newFile.ts b/app/src/util/newFile.ts
index 611568225f..390a3036eb 100644
--- a/app/src/util/newFile.ts
+++ b/app/src/util/newFile.ts
@@ -487,23 +487,43 @@ export const newFileByRefHintAtPath = (
onCreated: (id: string, range: Range) => void,
) => {
const context = createNewFileSelectionContext(protyle, range);
- const title = replaceFileName(name.trim());
- if (!context || !isNewFileSelectionValid(protyle, context) || (title && !validateName(title))) {
+ if (!context) {
+ return;
+ }
+ newFileAtPath({
+ notebookId: context.notebookId,
+ name,
+ isValid: () => !!isNewFileSelectionValid(protyle, context),
+ restoreFocus: () => focusByRange(context.range),
+ onCreated: (id) => onCreated(id, context.range),
+ });
+};
+
+/** 在选定位置新建文档,仅在调用方上下文仍有效时创建和回调 */
+export const newFileAtPath = (options: {
+ notebookId: string;
+ name: string;
+ isValid: () => boolean;
+ restoreFocus?: () => void;
+ onCreated: (id: string, title: string) => void;
+}) => {
+ const title = replaceFileName(options.name.trim());
+ if (!options.isValid() || (title && !validateName(title))) {
return;
}
let submitted = false;
movePathTo({
title: window.siyuan.languages.newFileAtPath,
flashcard: false,
- sourceNotebookIds: [context.notebookId],
+ sourceNotebookIds: [options.notebookId],
restoreFocus() {
- if (isNewFileSelectionValid(protyle, context)) {
- focusByRange(context.range);
+ if (options.isValid()) {
+ options.restoreFocus?.();
}
},
cb(paths, notebooks) {
- if (submitted || !paths[0] || !notebooks[0] || !isNewFileSelectionValid(protyle, context) ||
- !isMoveTargetAllowed([context.notebookId], notebooks[0])) {
+ if (submitted || !paths[0] || !notebooks[0] || !options.isValid() ||
+ !isMoveTargetAllowed([options.notebookId], notebooks[0])) {
return;
}
submitted = true;
@@ -513,8 +533,8 @@ export const newFileByRefHintAtPath = (
parentPath: paths[0],
title,
}, (id) => {
- if (isNewFileSelectionValid(protyle, context)) {
- onCreated(id, context.range);
+ if (options.isValid()) {
+ options.onCreated(id, title);
}
});
},
diff --git a/app/tests/newRefDocAtPath.test.js b/app/tests/newRefDocAtPath.test.js
index 3b61c2d627..e2fe807815 100644
--- a/app/tests/newRefDocAtPath.test.js
+++ b/app/tests/newRefDocAtPath.test.js
@@ -75,7 +75,7 @@ const fixture = () => {
hint.genHTML = items => { hint.items = items; };
protyle.hint = hint;
protyle.toolbar.setInlineMark = (...args) => { inserted.push(args); return []; };
- return {api, deps, paths, window, Lute, protyle, hint, range, text, requests, inserted, focused,
+ return {api, deps, paths, window, Lute, protyle, hint, range, text, block, requests, inserted, focused,
get picker() { return picker; },
open() { api.newFileByRefHintAtPath(protyle, "New title", range, (...args) => inserted.push(args)); },
};
@@ -180,7 +180,7 @@ test("hint selection preserves reference subtype, anchor text and undo context",
}
});
-test("typed and searched reference suggestions offer location selection, excluding database bindings", async () => {
+test("typed and searched reference suggestions offer location selection including database bindings", async () => {
for (const source of ["hint", "search", "av"]) {
for (const hideConfigured of [true, false]) {
const f = fixture();
@@ -189,13 +189,118 @@ test("typed and searched reference suggestions offer location selection, excludi
extend.hintRef("New title", f.protyle, source);
f.requests[0].cb({data: {newDoc: true, k: "New title", blocks: []}});
await Promise.resolve();
- assert.equal(f.hint.items.some(item => item.value.startsWith("((newFileAtPath ")), source !== "av");
+ assert.equal(f.hint.items.some(item => item.value.startsWith("((newFileAtPath ")), true);
assert.equal(f.hint.items.some(item => item.value.startsWith("((newFile ")), !hideConfigured);
assert.equal(f.hint.items.some(item => item.value.startsWith("((newSubDoc ")), true);
f.hint.genSearchHTML(f.protyle, {value: "New title"}, false, "Original anchor", source);
f.requests[1].cb({data: {newDoc: true, k: "New title", blocks: []}});
await Promise.resolve();
- assert.equal(f.hint.element.lastElementChild.innerHTML.includes("newFileAtPath"), source !== "av");
+ assert.equal(f.hint.element.lastElementChild.innerHTML.includes("newFileAtPath"), true);
+ }
+ }
+});
+
+const databaseFixture = (view = "table", isDetached = true) => {
+ const f = fixture();
+ const cell = {isConnected: true};
+ const row = {dataset: {id: "original-item"}, contains: node => node === cell};
+ let currentValue = {type: "block", isDetached, block: {id: isDetached ? "" : "old-doc", content: "Original"}};
+ Object.assign(f.block, {
+ isConnected: true,
+ dataset: {nodeId: "database-block"},
+ getAttribute: name => name === "data-av-type" ? view : "database",
+ contains: node => node === row,
+ });
+ f.protyle.id = "editor";
+ f.protyle.wysiwyg.element.contains = node => node === f.block || node === f.text;
+ f.hint.source = "av";
+ const operations = [];
+ const animations = [];
+ Object.assign(f.deps, load("protyle/render/av/binding", f.deps, f.window, f.Lute),
+ load("protyle/render/av/viewType", f.deps, f.window, f.Lute), {
+ hasClosestByClassName: (node, name) => {
+ if (name === "av__cell") {
+ return cell;
+ }
+ assert.equal(name, ["table", "list"].includes(view) ? "av__row" : "av__gallery-item");
+ return row;
+ },
+ genCellValueByElement: () => currentValue,
+ transaction: (_protyle, doOperations, undoOperations) => operations.push({doOperations, undoOperations}),
+ updateAttrViewCellAnimation: (target, value) => animations.push({target, value}),
+ });
+ return Object.assign(f, {cell, row, operations, animations,
+ changeValue: value => { currentValue = value; },
+ openDatabase() {
+ f.hint.fill(`((newFileAtPath "Original"\u200b'New title${f.Lute.Caret}'))`, f.protyle, false);
+ },
+ });
+};
+
+test("database creation binds only after success and preserves item identity and undo", () => {
+ for (const view of ["table", "list", "gallery", "kanban"]) {
+ for (const isDetached of [false, true]) {
+ const f = databaseFixture(view, isDetached);
+ f.openDatabase();
+ f.picker.cb(["/chosen-parent.sy"], ["other"]);
+ assert.equal(f.operations.length, 0);
+ assert.equal(f.animations.length, 0);
+ assert.equal(f.requests[0].data.path, "/chosen-parent/20260927120000-newdoc1.sy");
+ f.requests[0].cb({code: 0});
+ assert.equal(f.operations.length, 1);
+ const {doOperations, undoOperations} = f.operations[0];
+ assert.equal(doOperations[0].previousID, "original-item");
+ assert.equal(doOperations[0].avID, "database");
+ assert.equal(doOperations[0].blockID, "database-block");
+ assert.equal(doOperations[0].nextID, "20260927120000-newdoc1");
+ assert.equal(undoOperations[0].isDetached, isDetached);
+ assert.equal(undoOperations[0].nextID, isDetached ? "" : "old-doc");
+ assert.equal(f.animations.length, 1);
+ assert.equal(f.animations[0].target, f.cell);
+ assert.equal(f.animations[0].value.block.content, "New title");
+ assert.equal(f.inserted.length, 0);
+ }
+ }
+});
+
+test("canceling database location selection leaves the original binding and display intact", () => {
+ const f = databaseFixture();
+ f.openDatabase();
+ f.picker.restoreFocus();
+ assert.equal(f.requests.length, 0);
+ assert.equal(f.operations.length, 0);
+ assert.equal(f.animations.length, 0);
+ assert.equal(f.focused.length, 1);
+});
+
+test("database context changes before confirmation or after creation starts cannot replace another binding", () => {
+ const changes = [
+ f => { f.cell.isConnected = false; },
+ f => { f.block.isConnected = false; },
+ f => { f.row.dataset.id = "other-item"; },
+ f => { f.block.dataset.nodeId = "other-carrier"; },
+ f => { f.block.getAttribute = () => "other-database"; },
+ f => { f.protyle.block.rootID = "other-document"; },
+ f => { f.protyle.notebookId = "other"; },
+ f => { f.changeValue({type: "block", isDetached: false, block: {id: "another-doc", content: "Changed"}}); },
+ f => { f.changeValue({type: "block", isDetached: true, block: {id: "", content: "Edited title"}}); },
+ ];
+ for (const change of changes) {
+ for (const afterCreate of [false, true]) {
+ const f = databaseFixture();
+ f.openDatabase();
+ if (afterCreate) {
+ f.picker.cb(["/"], ["other"]);
+ }
+ change(f);
+ if (afterCreate) {
+ f.requests[0].cb({code: 0});
+ } else {
+ f.picker.cb(["/"], ["other"]);
+ assert.equal(f.requests.length, 0);
+ }
+ assert.equal(f.operations.length, 0);
+ assert.equal(f.animations.length, 0);
}
}
});