Skip to content

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

:sparkles: Support dragging document tabs to the Documents panel https://github.com/siyuan-note/siyuan/issues/18495

Daniel8836fae0fdaf
diff --git a/app/src/boot/globalEvent/event.ts b/app/src/boot/globalEvent/event.ts
index 507c9d65b8..162a28971c 100644
--- a/app/src/boot/globalEvent/event.ts
+++ b/app/src/boot/globalEvent/event.ts
@@ -84,8 +84,10 @@ export const initWindowEvent = (app: App) => {
let scrollTarget: HTMLElement | false;
window.addEventListener("dragstart", clearDragTipGhost, true);
window.addEventListener("dragover", (event: DragEvent & { target: HTMLElement }) => {
- if (event.dataTransfer.types.includes(Constants.SIYUAN_DROP_TAB)) {
- if (!hasClosestByClassName(event.target, "layout-tab-bar")) {
+ const isDocumentTab = event.dataTransfer.types.includes(Constants.SIYUAN_DROP_DOCUMENT_TAB);
+ const tabBarElement = hasClosestByClassName(event.target, "layout-tab-bar");
+ if (event.dataTransfer.types.includes(Constants.SIYUAN_DROP_TAB) && (!isDocumentTab || tabBarElement)) {
+ if (!tabBarElement) {
stopScrollAnimation();
}
return;
@@ -102,7 +104,7 @@ export const initWindowEvent = (app: App) => {
if (event.dataTransfer.types.includes("text/plain")) {
return;
}
- // 拖拽标题/列表项块标时,按浮窗模型控制文档树所在浮动 dock 的显隐:
+ // 拖拽文档页签或标题/列表项块标时,按浮窗模型控制文档树所在浮动 dock 的显隐:
// 鼠标在边缘触发区或面板内则展开,离开则收起 https://github.com/siyuan-note/siyuan/issues/18043
if (!isWindow() &&
(!window.siyuan.layout.leftDock.pin || !window.siyuan.layout.rightDock.pin || !window.siyuan.layout.bottomDock.pin)) {
@@ -117,7 +119,7 @@ export const initWindowEvent = (app: App) => {
break;
}
}
- if (["nodeheading", "nodelistitem"].includes(gutterBlockType)) {
+ if (isDocumentTab || ["nodeheading", "nodelistitem"].includes(gutterBlockType)) {
const statusHeight = document.getElementById("status")?.clientHeight || 0;
const toolbarHeight = document.getElementById("toolbar")?.clientHeight || 0;
const inYRange = event.clientY > toolbarHeight && event.clientY < window.innerHeight - statusHeight;
@@ -145,6 +147,10 @@ export const initWindowEvent = (app: App) => {
}
const fileElement = hasClosestByClassName(event.target, "sy__file");
const protyleElement = hasClosestByClassName(event.target, "protyle", true);
+ if (isDocumentTab && !fileElement) {
+ stopScrollAnimation();
+ return;
+ }
// 光标不在编辑器也不在文档树内时,隐藏拖拽提示(避免卡在无效区域)
if (!fileElement && !protyleElement) {
document.querySelector(".drag-tip")?.remove();
diff --git a/app/src/constants.ts b/app/src/constants.ts
index f2a644d66a..8fa345ba14 100644
--- a/app/src/constants.ts
+++ b/app/src/constants.ts
@@ -28,6 +28,7 @@ export abstract class Constants {
public static readonly SIYUAN_DROP_GUTTER: string = "application/siyuan-gutter";
public static readonly SIYUAN_DROP_BLOCK_REF: string = "application/siyuan-block-ref";
public static readonly SIYUAN_DROP_TAB: string = "application/siyuan-tab";
+ public static readonly SIYUAN_DROP_DOCUMENT_TAB: string = "application/siyuan-document-tab";
public static readonly SIYUAN_DROP_EDITOR: string = "application/siyuan-editor";
// 渲染进程调主进程
diff --git a/app/src/layout/Tab.ts b/app/src/layout/Tab.ts
index b41328b3d7..550ae23ac4 100644
--- a/app/src/layout/Tab.ts
+++ b/app/src/layout/Tab.ts
@@ -50,9 +50,20 @@ export class Tab {
const tabElement = hasClosestByTag(event.target, "LI");
if (tabElement) {
event.dataTransfer.setData("text/html", tabElement.outerHTML);
- const modeJSON = {id: this.id};
+ const modeJSON = {id: this.id} as ILayoutJSON & {id: string};
layoutToJSON(this, modeJSON);
event.dataTransfer.setData(Constants.SIYUAN_DROP_TAB, JSON.stringify(modeJSON));
+ const editorJSON = Array.isArray(modeJSON.children) ? undefined : modeJSON.children;
+ delete tabElement.dataset.dragDocumentId;
+ if (editorJSON?.instance === "Editor" && editorJSON.rootId) {
+ event.dataTransfer.setData(Constants.SIYUAN_DROP_DOCUMENT_TAB, JSON.stringify({
+ rootId: editorJSON.rootId,
+ tabId: this.id,
+ title: this.title,
+ }));
+ tabElement.dataset.dragDocumentId = editorJSON.rootId;
+ window.siyuan.dragTitle = this.title;
+ }
event.dataTransfer.dropEffect = "move";
tabElement.style.opacity = "0.38";
window.siyuan.dragElement = this.headElement;
@@ -65,6 +76,7 @@ export class Tab {
const tabElement = hasClosestByTag(event.target, "LI");
if (tabElement) {
tabElement.style.opacity = "1";
+ delete tabElement.dataset.dragDocumentId;
}
/// #if !BROWSER
// 拖拽到屏幕外
@@ -86,16 +98,7 @@ export class Tab {
window.siyuan.dragElement = undefined;
if (event.dataTransfer.dropEffect === "none") {
// 按 esc 取消的时候应该还原在 dragover 时交换的 tab
- this.parent.children.forEach((item, index) => {
- const currentElement = this.headElement.parentElement.children[index];
- if (item.headElement !== currentElement) {
- if (index === 0) {
- this.headElement.parentElement.firstElementChild.before(item.headElement);
- } else {
- this.headElement.parentElement.children[index - 1].after(item.headElement);
- }
- }
- });
+ this.restoreHeadElementOrder();
}
/// #if !BROWSER
ipcRenderer.send(Constants.SIYUAN_SEND_WINDOWS, {cmd: "resetTabsStyle", data: "addRegionStyle"});
@@ -109,6 +112,23 @@ export class Tab {
this.panelElement.setAttribute("data-id", this.id);
}
+ public restoreHeadElementOrder() {
+ const headersElement = this.headElement?.parentElement;
+ if (!headersElement) {
+ return;
+ }
+ this.parent.children.forEach((item, index) => {
+ const currentElement = headersElement.children[index];
+ if (item.headElement !== currentElement) {
+ if (index === 0) {
+ headersElement.firstElementChild.before(item.headElement);
+ } else {
+ headersElement.children[index - 1].after(item.headElement);
+ }
+ }
+ });
+ }
+
public updateTitle(title: string) {
this.title = title;
this.headElement.querySelector(".item__text").innerHTML = escapeHtml(title);
diff --git a/app/src/layout/Wnd.ts b/app/src/layout/Wnd.ts
index 71062884a7..b55f31b293 100644
--- a/app/src/layout/Wnd.ts
+++ b/app/src/layout/Wnd.ts
@@ -319,6 +319,12 @@ export class Wnd {
this.element.addEventListener("dragenter", (event: DragEvent & { target: HTMLElement }) => {
elementDragCounter++;
if (event.dataTransfer.types.includes(Constants.SIYUAN_DROP_TAB)) {
+ if (event.dataTransfer.types.includes(Constants.SIYUAN_DROP_DOCUMENT_TAB) &&
+ hasClosestByClassName(event.target, "sy__file")) {
+ dragElement.classList.add("fn__none");
+ dragElement.removeAttribute("style");
+ return;
+ }
const tabHeadersElement = hasClosestByClassName(event.target, "layout-tab-bar");
if (tabHeadersElement) {
return;
diff --git a/app/src/layout/dock/Files.ts b/app/src/layout/dock/Files.ts
index ca321de9e6..518eecf6c2 100644
--- a/app/src/layout/dock/Files.ts
+++ b/app/src/layout/dock/Files.ts
@@ -1,7 +1,7 @@
import {escapeAriaLabel, escapeHtml, escapeLessThans} from "../../util/escape";
import {Tab} from "../Tab";
import {Model} from "../Model";
-import {setPanelFocus} from "../util";
+import {getInstanceById, setPanelFocus} from "../util";
import {getDockByType} from "../tabUtil";
import {Constants} from "../../constants";
import {getDocDisplayName, isMoveTargetAllowed, pathPosix, setNoteBook} from "../../util/pathName";
@@ -42,7 +42,10 @@ import {
collectExpandedDocIDs,
findMovedFileTreeItem,
getFileTreeChildList,
+ IDocumentTabDragData,
IFileTreeMove,
+ insertDocumentSortPath,
+ parseDocumentTabDragData,
restoreMovedExpandedDocItems,
updateMovedSubtree
} from "../../util/fileTreeMove";
@@ -528,7 +531,9 @@ export class Files extends Model {
/// #endif
});
this.element.addEventListener("dragover", (event: DragEvent & { target: HTMLElement }) => {
- if (window.siyuan.config.readonly || !window.siyuan.dragElement || event.dataTransfer.types.includes(Constants.SIYUAN_DROP_TAB)) {
+ const isDocumentTab = event.dataTransfer.types.includes(Constants.SIYUAN_DROP_DOCUMENT_TAB);
+ if (window.siyuan.config.readonly || !window.siyuan.dragElement ||
+ (event.dataTransfer.types.includes(Constants.SIYUAN_DROP_TAB) && !isDocumentTab)) {
event.preventDefault();
return;
}
@@ -573,14 +578,19 @@ export class Files extends Model {
event.preventDefault();
return;
}
- } else if (liElement.classList.contains("b3-list-item--focus")) {
+ } else if (isDocumentTab && liElement.dataset.nodeId ===
+ window.siyuan.dragElement.dataset.dragDocumentId) {
+ hideDragTip();
+ event.preventDefault();
+ return;
+ } else if (!isDocumentTab && liElement.classList.contains("b3-list-item--focus")) {
// 选中的文档不能拖拽到自己上,但允许标题拖拽到文档树的选中文档上 https://github.com/siyuan-note/siyuan/issues/6552
hideDragTip();
event.preventDefault();
return;
}
- dragOverLastObj.sourceOnlyRoot = gutterType ? false : true;
+ dragOverLastObj.sourceOnlyRoot = gutterType || isDocumentTab ? false : true;
if (dragOverLastObj.sourceOnlyRoot) {
const focusItems = this.element.querySelectorAll(".b3-list-item--focus");
for (let i = 0; i < focusItems.length; i++) {
@@ -665,6 +675,7 @@ export class Files extends Model {
}
}
event.preventDefault();
+ event.dataTransfer.dropEffect = "move";
});
event.preventDefault();
});
@@ -686,7 +697,11 @@ export class Files extends Model {
counter = 0;
hideDragTip();
window.siyuan.dragTitle = "";
- const newElement = this.element.querySelector(".dragover, .dragover__bottom, .dragover__top");
+ const documentTabData = event.dataTransfer.types.includes(Constants.SIYUAN_DROP_DOCUMENT_TAB) ?
+ parseDocumentTabDragData(event.dataTransfer.getData(Constants.SIYUAN_DROP_DOCUMENT_TAB)) : undefined;
+ const sourceTab = documentTabData ? getInstanceById(documentTabData.tabId) as Tab : undefined;
+ sourceTab?.restoreHeadElementOrder();
+ const newElement = this.element.querySelector<HTMLElement>(".dragover, .dragover__bottom, .dragover__top");
if (!newElement) {
return;
}
@@ -697,6 +712,13 @@ export class Files extends Model {
const oldScrollTop = this.element.scrollTop;
const toURL = newUlElement.getAttribute("data-url");
const toPath = newElement.getAttribute("data-path");
+ if (documentTabData) {
+ event.preventDefault();
+ event.stopPropagation();
+ window.siyuan.dragElement = undefined;
+ await this.dropDocumentTab(documentTabData, newElement, newUlElement, oldScrollTop);
+ return;
+ }
let gutterType = "";
for (const item of event.dataTransfer.items) {
if (item.type.startsWith(Constants.SIYUAN_DROP_GUTTER)) {
@@ -899,6 +921,104 @@ export class Files extends Model {
this.init();
}
+ private async dropDocumentTab(
+ documentTabData: IDocumentTabDragData,
+ targetElement: HTMLElement,
+ notebookElement: HTMLElement,
+ oldScrollTop: number
+ ) {
+ const moveAsChild = targetElement.classList.contains("dragover");
+ const insertAfter = targetElement.classList.contains("dragover__bottom");
+ const insertBefore = targetElement.classList.contains("dragover__top");
+ const targetNotebook = notebookElement.getAttribute("data-url");
+ const targetPath = targetElement.getAttribute("data-path");
+ targetElement.classList.remove("dragover", "dragover__bottom", "dragover__top");
+ if (!targetNotebook || !targetPath || (!moveAsChild && !insertAfter && !insertBefore)) {
+ return;
+ }
+
+ const pathResponse = await fetchSyncPost("/api/filetree/getPathByID", {id: documentTabData.rootId});
+ if (pathResponse.code !== 0 || !pathResponse.data?.path || !pathResponse.data?.notebook) {
+ return;
+ }
+ const sourcePath = pathResponse.data.path as string;
+ const sourceNotebook = pathResponse.data.notebook as string;
+ if (!isMoveTargetAllowed([sourceNotebook], targetNotebook)) {
+ showMessage(window.siyuan.languages._kernel[313]);
+ return;
+ }
+ if (sourceNotebook === targetNotebook) {
+ const sourceDirectory = sourcePath.endsWith(".sy") ? sourcePath.slice(0, -3) : sourcePath;
+ if (targetPath === sourcePath || targetPath.startsWith(sourceDirectory + "/")) {
+ return;
+ }
+ }
+
+ if (moveAsChild) {
+ const sourceParentDirectory = pathPosix().dirname(sourcePath);
+ const sourceParentPath = sourceParentDirectory === "/" ? "/" : sourceParentDirectory + ".sy";
+ if (sourceNotebook === targetNotebook && sourceParentPath === targetPath) {
+ return;
+ }
+ await fetchSyncPost("/api/filetree/moveDocs", {
+ toNotebook: targetNotebook,
+ fromPaths: [sourcePath],
+ toPath: targetPath,
+ });
+ return;
+ }
+
+ const notebookSort = notebookElement.getAttribute("data-sortmode");
+ if (notebookSort !== "6" && !(window.siyuan.config.fileTree.sort === 6 && notebookSort === "15")) {
+ return;
+ }
+ const targetDirectory = pathPosix().dirname(targetPath);
+ const newPath = pathPosix().join(targetDirectory, documentTabData.rootId + ".sy");
+ const siblingPaths: string[] = [];
+ Array.from(targetElement.parentElement.children).forEach((item) => {
+ const path = item.getAttribute("data-path");
+ if (item.tagName === "LI" && path) {
+ siblingPaths.push(path);
+ }
+ });
+ const sortedPaths = insertDocumentSortPath(
+ siblingPaths,
+ documentTabData.rootId,
+ newPath,
+ targetPath,
+ insertAfter
+ );
+ if (!sortedPaths || (sortedPaths.length === siblingPaths.length &&
+ sortedPaths.every((path, index) => path === siblingPaths[index]))) {
+ return;
+ }
+ const targetParentPath = targetDirectory === "/" ? "/" : targetDirectory + ".sy";
+ const moveResponse = await fetchSyncPost("/api/filetree/moveDocs", {
+ toNotebook: targetNotebook,
+ fromPaths: [sourcePath],
+ toPath: targetParentPath,
+ callback: Constants.CB_MOVE_NOLIST,
+ });
+ if (moveResponse.code !== 0) {
+ return;
+ }
+ const sortResponse = await fetchSyncPost("/api/filetree/changeSort", {
+ paths: sortedPaths,
+ notebook: targetNotebook,
+ });
+ if (sortResponse.code !== 0) {
+ return;
+ }
+ const listResponse = await fetchSyncPost("/api/filetree/listDocsByPath", {
+ notebook: targetNotebook,
+ path: targetParentPath,
+ app: Constants.SIYUAN_APPID,
+ });
+ if (listResponse.code === 0 && listResponse.data?.files?.length > 0) {
+ this.onLsHTML(listResponse.data, oldScrollTop);
+ }
+ }
+
private handleMsgCallback(data: IWebSocketData) {
if (data) {
switch (data.cmd) {
diff --git a/app/src/util/fileTreeMove.test.ts b/app/src/util/fileTreeMove.test.ts
index 9999f23ac7..624e321485 100644
--- a/app/src/util/fileTreeMove.test.ts
+++ b/app/src/util/fileTreeMove.test.ts
@@ -3,11 +3,67 @@ import * as assert from "node:assert/strict";
import {
findMovedFileTreeItem,
IFileTreeMove,
+ insertDocumentSortPath,
+ parseDocumentTabDragData,
remapMovedPath,
restoreMovedExpandedDocItems,
updateMovedSubtree
} from "./fileTreeMove";
+describe("parseDocumentTabDragData", () => {
+ it("parses a document tab payload", () => {
+ assert.deepEqual(parseDocumentTabDragData(JSON.stringify({
+ rootId: "20260802120000-abcdefg",
+ tabId: "tab-id",
+ title: "Document",
+ })), {
+ rootId: "20260802120000-abcdefg",
+ tabId: "tab-id",
+ title: "Document",
+ });
+ });
+
+ it("rejects non-document payloads", () => {
+ assert.equal(parseDocumentTabDragData(JSON.stringify({
+ rootId: "invalid",
+ tabId: "tab-id",
+ title: "Document",
+ })), undefined);
+ });
+});
+
+describe("insertDocumentSortPath", () => {
+ it("inserts a document from another parent before the target", () => {
+ assert.deepEqual(insertDocumentSortPath(
+ ["/target-a.sy", "/target-b.sy"],
+ "20260802120000-abcdefg",
+ "/20260802120000-abcdefg.sy",
+ "/target-b.sy",
+ false
+ ), ["/target-a.sy", "/20260802120000-abcdefg.sy", "/target-b.sy"]);
+ });
+
+ it("reorders a document already under the target parent", () => {
+ assert.deepEqual(insertDocumentSortPath(
+ ["/a.sy", "/20260802120000-abcdefg.sy", "/b.sy"],
+ "20260802120000-abcdefg",
+ "/20260802120000-abcdefg.sy",
+ "/b.sy",
+ true
+ ), ["/a.sy", "/b.sy", "/20260802120000-abcdefg.sy"]);
+ });
+
+ it("returns undefined when the target is missing", () => {
+ assert.equal(insertDocumentSortPath(
+ ["/a.sy"],
+ "20260802120000-abcdefg",
+ "/20260802120000-abcdefg.sy",
+ "/missing.sy",
+ false
+ ), undefined);
+ });
+});
+
const move: IFileTreeMove = {
fromNotebook: "source-notebook",
fromPath: "/parent/current.sy",
diff --git a/app/src/util/fileTreeMove.ts b/app/src/util/fileTreeMove.ts
index 5d2858167e..444577ae5f 100644
--- a/app/src/util/fileTreeMove.ts
+++ b/app/src/util/fileTreeMove.ts
@@ -6,6 +6,48 @@ export interface IFileTreeMove {
newPath: string;
}
+export interface IDocumentTabDragData {
+ rootId: string;
+ tabId: string;
+ title: string;
+}
+
+const BLOCK_ID_PATTERN = /^\d{14}-[0-9a-z]{7}$/;
+
+export const parseDocumentTabDragData = (data: string) => {
+ try {
+ const result = JSON.parse(data) as IDocumentTabDragData;
+ if (!BLOCK_ID_PATTERN.test(result.rootId) || typeof result.tabId !== "string" ||
+ typeof result.title !== "string") {
+ return;
+ }
+ return result;
+ } catch (e) {
+ console.warn("parse document tab drop data failed", e);
+ }
+};
+
+const getDocumentIDFromPath = (path: string) => {
+ const fileName = path.slice(path.lastIndexOf("/") + 1);
+ return fileName.endsWith(".sy") ? fileName.slice(0, -3) : fileName;
+};
+
+export const insertDocumentSortPath = (
+ siblingPaths: string[],
+ sourceID: string,
+ newPath: string,
+ targetPath: string,
+ insertAfter: boolean
+) => {
+ const paths = siblingPaths.filter((path) => getDocumentIDFromPath(path) !== sourceID);
+ const targetIndex = paths.indexOf(targetPath);
+ if (targetIndex === -1) {
+ return;
+ }
+ paths.splice(targetIndex + (insertAfter ? 1 : 0), 0, newPath);
+ return paths;
+};
+
export const findMovedFileTreeItem = (treeElement: Element, move: IFileTreeMove) => {
const sourceElement = treeElement.querySelector<HTMLElement>(
`ul[data-url="${move.fromNotebook}"] li[data-path="${move.fromPath}"]`