An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
import {config as configApi} from "../../config/util/configApi";
import {hasClosestByClassName, hasTopClosestByTag} from "../../protyle/util/hasClosest";
import {escapeHtml, escapeHtmlTextAndAttr} from "../../util/escape";
import {getTreeItemTailHTML} from "../../util/treeItemTail";
import {Model} from "../../layout/Model";
import {Constants} from "../../constants";
import {getDocDisplayName, isMoveTargetAllowed, pathPosix, setNoteBook} from "../../util/pathName";
import {initFileMenu, initNavigationMenu, sortMenu} from "../../menus/navigation";
import {toggleMenu} from "../../menus/menuToggle";
import {
getPublishAccessLevel,
getPublishAccessOptionByLevel,
openPublishAccessDialog
} from "../../protyle/util/publishAccess";
import {fetchPost, fetchSyncPost} from "../../util/fetch";
import {restoreFileTreePaths} from "../../util/fileTreeRestore";
import {saveOpenFileTreePaths} from "../../util/fileTreePaths";
import {removeFileTreeItems} from "../../util/fileTreeRemove";
import {reorderSortedFileTree} from "../../util/fileTreeReorder";
import {genUUID} from "../../util/genID";
import {openMobileFileById} from "../editor";
import {
getFileTreeDefaultIconAttr,
getFileTreeIconHTML,
syncFileTreeItemDefaultIcon,
updateFileTreeItemIcon,
} from "../../emoji/fileTreeIcon";
import {newNotebook, openEncryptedNotebook} from "../../util/mount";
import {newFileInTree} from "../../util/newFile";
import {MenuItem} from "../../menus/Menu";
import type {App} from "../../index";
import {refreshFileTree} from "../../dialog/processSystem";
import {confirmDialog} from "../../dialog/confirmDialog";
import {showMessage} from "../../dialog/message";
import {dragOverScroll, stopScrollAnimation} from "../../boot/globalEvent/dragover";
import {
cancelFileTreeCollapse,
collapseFileTree,
expandFileTree,
isFileTreeCollapsing
} from "../../layout/dock/fileTreeAnimation";
import {updateNotebookRootForBoxDoc} from "../../util/notebookRoot";
import {bindMousePointerTouchBridge, isMousePointerTouchEvent} from "../util/mousePointerTouchBridge";
import {
collectExpandedDocIDs,
findMovedFileTreeItem,
getRelativeReorderRequest,
getFileTreeChildList,
IFileTreeMove,
restoreMovedExpandedDocItems,
updateMovedSubtree
} from "../../util/fileTreeMove";
import {
FILE_TREE_CHILDREN_SORT_MODE,
FILE_TREE_EFFECTIVE_SORT_MODE,
getFileTreeSortRefreshTargets,
getMovedFileTreeSortRefreshTargets,
getResponseEffectiveSortMode,
isCustomFileTreeList,
reorderFileTreeNotebooks,
type IDocSortModeChanged,
updateFileTreeSortMode
} from "../../util/fileTreeSort";
import {MobileOpenedFileSelection} from "./mobileOpenedFileSelection";
import {insertMobileMultiSelectMenu, renderMultiSelectToolbar, updateMultiSelectToolbar} from "../util/multiSelectToolbar";
import {PinnedDocs} from "../../layout/dock/PinnedDocs";
import {ParentDocClick} from "../../layout/dock/parentDocClick";
import {emitToPlugins} from "../../plugin/EventBusCore";
export class MobileFiles extends Model {
public element: HTMLElement;
private actionsElement: HTMLElement;
private selectionElement: HTMLElement;
private selectionObserver: MutationObserver;
private multiSelect = false;
private pinnedDocs: PinnedDocs;
private closeElement: HTMLElement;
private reloadNotebookInfoTimeout: number;
private docSortModeRefreshTimeout: number;
private docSortModeChanges = new Map<string, IDocSortModeChanged>();
private movedExpandedDocIDs = new Set<string>();
private openedFileSelection = new MobileOpenedFileSelection();
private parentDocClick = new ParentDocClick();
private touchDragState: {
selectedElement: HTMLElement;
startX: number;
startY: number;
isDragging: boolean;
ghostElement: HTMLElement;
startTime: number;
};
constructor(app: App, filesElement: HTMLElement) {
super({app});
this.connect({
id: genUUID(),
type: "filetree",
msgCallback: this.handleMsgCallback.bind(this)
});
filesElement.innerHTML = `<div class="toolbar toolbar--dark">
<div class="fn__space"></div>
<div class="toolbar__text">${window.siyuan.languages.fileTree}</div>
<div class="fn__space"></div>
<svg data-type="newNotebook" class="toolbar__icon"><use xlink:href="#iconNewNoteBook"></use></svg>
<svg data-type="refresh" class="toolbar__icon"><use xlink:href="#iconRefresh"></use></svg>
<svg data-type="focus" class="toolbar__icon"><use xlink:href="#iconFocus"></use></svg>
<svg data-type="collapse" class="toolbar__icon"><use xlink:href="#iconContract"></use></svg>
<svg data-type="publish-access" class="toolbar__icon${window.siyuan.config.readonly || !window.siyuan.config.publish.enable ? " fn__none" : ""}"><use xlink:href="#iconEye"></use></svg>
<svg data-type="sort" class="toolbar__icon${window.siyuan.config.readonly ? " fn__none" : ""}"><use xlink:href="#iconSort"></use></svg>
</div>
<div class="fn__flex-1"></div>
<ul class="b3-list b3-list--background fn__flex-column" style="min-height: auto;height:42px;transition: height .2s cubic-bezier(0, 0, .2, 1) 0ms">
<li class="b3-list-item" data-type="toggle">
<span class="b3-list-item__toggle">
<svg class="b3-list-item__arrow"><use xlink:href="#iconRight"></use></svg>
</span>
<span class="b3-list-item__text">${window.siyuan.languages.closeNotebook}</span>
<span class="counter" style="cursor: auto"></span>
</li>
<ul class="fn__none fn__flex-1"></ul>
</ul>`;
this.actionsElement = filesElement.firstElementChild as HTMLElement;
this.element = this.actionsElement.nextElementSibling as HTMLElement;
this.pinnedDocs = new PinnedDocs(app, this.element, (id, notebook) => {
openMobileFileById(app, id, [Constants.CB_GET_SCROLL], undefined, notebook);
}, true);
this.closeElement = this.element.nextElementSibling as HTMLElement;
this.selectionElement = document.createElement("div");
this.selectionElement.className = "protyle-util fn__none";
this.selectionElement.style.cssText = "position:relative;margin:8px;flex-shrink:0";
this.actionsElement.after(this.selectionElement);
this.selectionObserver = new MutationObserver(() => this.updateMultiSelect());
renderMultiSelectToolbar(this.selectionElement, 0, () => {
const item = this.element.querySelector<HTMLElement>("li.b3-list-item--focus");
if (item) {
if (item.dataset.type === "navigation-root") {
initNavigationMenu(this.app, item);
} else {
initFileMenu(this.app, item.closest("ul[data-url]").getAttribute("data-url"), item.dataset.path, item);
}
window.siyuan.menus.menu.fullscreen("bottom");
}
}, () => this.setMultiSelect(false));
filesElement.addEventListener("click", (event) => {
if (!this.multiSelect || this.selectionElement.contains(event.target as Node)) {
return;
}
const target = event.target as HTMLElement;
const item = target.closest<HTMLElement>('li[data-type="navigation-file"], li[data-type="navigation-root"]');
const toggle = target.closest(".b3-list-item__toggle:not(.fn__hidden)") ||
(target.closest(".b3-list-item__icon") ? item?.querySelector(":scope > .b3-list-item__toggle:not(.fn__hidden)") : null);
if (item && this.element.contains(item) && !this.pinnedDocs.element.contains(item)) {
if (toggle) {
this.toggleTreeItem(item);
} else {
item.classList.toggle("b3-list-item--focus");
}
}
event.preventDefault();
event.stopPropagation();
}, true);
filesElement.addEventListener("touchstart", (event) => {
if (this.multiSelect && this.pinnedDocs.element.contains(event.target as Node)) {
event.stopPropagation();
}
}, {capture: true, passive: true});
filesElement.addEventListener("click", (event: MouseEvent & { target: HTMLElement }) => {
let target = event.target as HTMLElement;
const parentTitle = target.closest<HTMLElement>(".b3-list-item__text");
const parentRow = parentTitle?.parentElement;
const isParentTitle = window.siyuan.config.fileTree.parentDocTitleClickMode !== 0 &&
!!parentRow?.getAttribute("data-node-id") && Number(parentRow.getAttribute("data-count")) > 0;
if (!isParentTitle) {
this.parentDocClick.cancel();
}
while (target && !target.isEqualNode(this.actionsElement)) {
if (target.classList.contains("b3-list-item__icon")) {
const notebookElement = target.closest("li[data-encrypted=true]");
if (notebookElement) {
openEncryptedNotebook(this.app, notebookElement.getAttribute("data-url"), notebookElement.querySelector(".b3-list-item__text").textContent);
event.preventDefault();
event.stopPropagation();
break;
}
target = target.previousElementSibling as HTMLElement;
}
const type = target.getAttribute("data-type");
if (type === "refresh") {
if (!target.getAttribute("disabled")) {
target.setAttribute("disabled", "disabled");
confirmDialog(window.siyuan.languages.rebuildDataIndex, window.siyuan.languages.rebuildDataIndexTip, () => {
refreshFileTree(() => {
target.removeAttribute("disabled");
this.init(false);
});
}, () => {
target.removeAttribute("disabled");
});
}
event.preventDefault();
break;
} else if (type === "focus") {
if (window.siyuan.mobile.editor) {
this.selectItem(window.siyuan.mobile.editor.protyle.notebookId, window.siyuan.mobile.editor.protyle.path);
}
event.preventDefault();
break;
} else if (type === "newNotebook") {
newNotebook();
} else if (type === "collapse") {
this.pinnedDocs.collapse();
Array.from(this.element.children).forEach(item => {
const liElement = item.firstElementChild;
const toggleElement = liElement.querySelector(".b3-list-item__arrow");
if (toggleElement.classList.contains("b3-list-item__arrow--open")) {
toggleElement.classList.remove("b3-list-item__arrow--open");
liElement.nextElementSibling.remove();
}
});
event.preventDefault();
break;
} else if (target.classList.contains("b3-list-item__switch")) {
if (target.closest("[data-encrypted=true]")) {
event.preventDefault();
event.stopPropagation();
break;
}
const rect = target.getBoundingClientRect();
const rootUL = hasTopClosestByTag(target, "UL");
openPublishAccessDialog(target.parentElement.getAttribute("data-type") === "navigation-root" ?
rootUL ? rootUL.getAttribute("data-url") : "" : target.parentElement.getAttribute("data-node-id"), {
x: rect.left,
y: rect.bottom,
h: rect.height,
w: rect.width,
}, (access) => {
target.innerHTML = access.iconHTML;
fetchPost("/api/filetree/setPublishAccess", {
id: access.id,
visible: access.visible,
password: access.password,
disable: access.disable,
});
});
event.preventDefault();
event.stopPropagation();
break;
} else if (type === "publish-access") {
// 顶部栏中的按钮
target.classList.toggle("block__icon--active");
this.refreshPublishAccessSwitch();
event.preventDefault();
event.stopPropagation();
break;
} else if (type === "sort") {
this.genSort();
event.preventDefault();
event.stopPropagation();
break;
} else if (target.classList.contains("b3-list-item__toggle") && !target.classList.contains("fn__hidden") && target.parentElement.getAttribute("data-type") !== "toggle") {
this.toggleTreeItem(target.parentElement);
event.preventDefault();
event.stopPropagation();
break;
} else if (type === "toggle") {
const svgElement = target.querySelector("svg");
if (svgElement.classList.contains("b3-list-item__arrow--open")) {
this.closeElement.style.height = "42px";
svgElement.classList.remove("b3-list-item__arrow--open");
this.closeElement.lastElementChild.classList.add("fn__none");
} else {
this.closeElement.style.height = "40%";
svgElement.classList.add("b3-list-item__arrow--open");
this.closeElement.lastElementChild.classList.remove("fn__none");
}
event.stopPropagation();
event.preventDefault();
break;
} else if (type === "open") {
const notebookId = target.getAttribute("data-url");
const liElement = target.closest("li");
// 加密笔记本关闭(锁定)时点"打开"先弹解锁框,解锁成功后再挂载
if (liElement && liElement.getAttribute("data-encrypted") === "true") {
openEncryptedNotebook(this.app, notebookId, liElement.querySelector(".b3-list-item__text").textContent);
} else {
fetchPost("/api/notebook/openNotebook", {
notebook: notebookId
});
}
event.stopPropagation();
event.preventDefault();
break;
} else if (target.classList.contains("b3-list-item__action")) {
const type = target.getAttribute("data-type");
const pathString = target.parentElement.getAttribute("data-path");
const ulElement = hasTopClosestByTag(target, "UL");
if (ulElement) {
const notebookId = ulElement.getAttribute("data-url");
if (!window.siyuan.config.readonly) {
if (type === "new") {
newFileInTree(app, notebookId, pathString);
} else if (type === "more-root") {
toggleMenu({
target: target, build: () => {
initNavigationMenu(app, target.parentElement);
this.insertMultiSelectMenu(target.parentElement);
window.siyuan.menus.menu.fullscreen("bottom");
}
});
}
}
if (type === "more-file") {
toggleMenu({
target: target, build: () => {
initFileMenu(app, notebookId, pathString, target.parentElement);
this.insertMultiSelectMenu(target.parentElement);
window.siyuan.menus.menu.fullscreen("bottom");
}
});
}
}
event.preventDefault();
event.stopPropagation();
break;
} else if (target.tagName === "LI") {
this.setCurrent(target, !isParentTitle || parentRow !== target);
const ulElement = hasTopClosestByTag(target, "UL");
const notebookId = ulElement ? ulElement.getAttribute("data-url") : "";
if (target.getAttribute("data-type") === "navigation-file") {
if (window.siyuan.config.fileTree.parentDocTitleClickMode !== 0 && Number(target.getAttribute("data-count")) > 0) {
if (parentRow === target) {
this.handleParentDocClick(target, notebookId);
} else {
this.parentDocClick.cancel();
this.toggleTreeItem(target);
}
} else {
openMobileFileById(app, target.getAttribute("data-node-id"), [Constants.CB_GET_SCROLL], undefined, notebookId);
}
} else if (target.getAttribute("data-type") === "navigation-root") {
const boxDocID = target.getAttribute("data-node-id");
if (boxDocID) {
if (window.siyuan.config.fileTree.parentDocTitleClickMode !== 0 && Number(target.getAttribute("data-count")) > 0) {
if (parentRow === target) {
this.handleParentDocClick(target, notebookId);
} else {
this.parentDocClick.cancel();
this.toggleTreeItem(target);
}
} else {
openMobileFileById(app, boxDocID, [Constants.CB_GET_SCROLL], undefined, notebookId);
}
} else if (ulElement) {
this.getLeaf(target, notebookId);
}
}
event.preventDefault();
break;
}
target = target.parentElement;
}
});
filesElement.addEventListener("touchstart", (event: TouchEvent) => {
if (this.multiSelect) return;
if (window.siyuan.config.readonly) return;
if (event.touches.length !== 1) return;
const touch = event.touches[0];
const target = touch.target as HTMLElement;
if (this.pinnedDocs.element.contains(target)) return;
const liElement = target.closest(".b3-list-item") as HTMLElement;
if (!liElement) return;
const dataType = liElement.getAttribute("data-type");
if (dataType !== "navigation-file" && dataType !== "navigation-root") return;
if (dataType === "navigation-root") {
if (window.siyuan.config.fileTree.sort !== 6) return;
}
this.touchDragState = {
isDragging: false,
selectedElement: liElement,
startX: touch.clientX,
startY: touch.clientY,
ghostElement: null,
startTime: Date.now() - (isMousePointerTouchEvent(event) ? Constants.TIMEOUT_LONGPRESS : 0),
};
if (!isMousePointerTouchEvent(event)) {
const state = this.touchDragState;
window.setTimeout(() => {
if (this.touchDragState !== state) {
return;
}
this.startTouchDrag(state, state.startX, state.startY, true);
}, Constants.TIMEOUT_LONGPRESS);
}
}, {passive: false});
this.element.addEventListener("scroll", () => {
if (this.touchDragState && !this.touchDragState.isDragging) {
this.touchDragState = null;
}
}, {passive: true});
filesElement.addEventListener("touchmove", (event: TouchEvent) => {
const state = this.touchDragState;
if (!state) return;
const touch = event.touches[0];
if (!state.isDragging) {
if (Date.now() - state.startTime < Constants.TIMEOUT_LONGPRESS &&
(Math.abs(touch.clientX - state.startX) > 5 || Math.abs(touch.clientY - state.startY) > 5)) {
this.touchDragState = null;
return;
}
if (Math.abs(touch.clientX - state.startX) < Constants.SIZE_DRAG_THRESHOLD &&
Math.abs(touch.clientY - state.startY) < Constants.SIZE_DRAG_THRESHOLD) return;
this.startTouchDrag(state, touch.clientX, touch.clientY, !isMousePointerTouchEvent(event));
event.preventDefault();
event.stopPropagation();
}
if (state.isDragging) {
// 进入拖拽后阻止原生滚动,避免列表伴随手指滚动
event.preventDefault();
event.stopPropagation();
state.ghostElement.style.left = `${touch.clientX}px`;
state.ghostElement.style.top = `${touch.clientY}px`;
// 手指接近列表上下边缘时自动滚动,避免拖拽时触不到屏外目标
dragOverScroll({clientY: touch.clientY} as MouseEvent, this.element.getBoundingClientRect(), this.element);
const target = document.elementFromPoint(touch.clientX, touch.clientY);
if (target && this.pinnedDocs.element.contains(target)) {
this.clearDragIndicators();
if (state.selectedElement.dataset.type === "navigation-file") {
this.pinnedDocs.previewDrop(touch.clientX, touch.clientY);
}
return;
}
this.pinnedDocs.clearDrop();
const liElement = target?.closest(".b3-list-item") as HTMLElement;
if (!liElement) return;
this.clearDragIndicators();
const targetDataType = liElement.getAttribute("data-type");
const selectedDataType = state.selectedElement.getAttribute("data-type");
if (targetDataType === "navigation-file" && selectedDataType === "navigation-root") {
return;
}
if (selectedDataType === "navigation-file" && targetDataType === "navigation-root") {
liElement.classList.add("dragover");
return;
}
const liRect = liElement.getBoundingClientRect();
if (selectedDataType === "navigation-root" && targetDataType === "navigation-root") {
if (touch.clientY > liRect.top + liRect.height / 2) {
liElement.classList.add("dragover__bottom");
} else {
liElement.classList.add("dragover__top");
}
return;
}
if (targetDataType === "navigation-file") {
const dragHeight = liRect.height * .2;
if (touch.clientY > liRect.bottom - dragHeight) {
liElement.classList.add("dragover__bottom");
} else if (touch.clientY < liRect.top + dragHeight) {
liElement.classList.add("dragover__top");
}
}
if (!liElement.classList.contains("dragover__top") && !liElement.classList.contains("dragover__bottom") &&
!(selectedDataType === "navigation-root" && targetDataType === "navigation-root")) {
liElement.classList.add("dragover");
}
}
}, {passive: false});
filesElement.addEventListener("touchend", async (event: TouchEvent) => {
const state = this.touchDragState;
if (!state) return;
stopScrollAnimation();
state.selectedElement.style.opacity = "";
if (state.isDragging) {
state.ghostElement?.remove();
const touch = event.changedTouches[0];
const target = document.elementFromPoint(touch.clientX, touch.clientY);
if (target && this.pinnedDocs.element.contains(target) && state.selectedElement.dataset.type === "navigation-file") {
this.touchDragState = null;
await this.pinnedDocs.drop([state.selectedElement.dataset.nodeId], touch.clientX, touch.clientY);
return;
}
const newElement = this.element.querySelector(".dragover, .dragover__bottom, .dragover__top");
if (!newElement) {
this.touchDragState = null;
return;
}
const newUlElement = hasTopClosestByTag(newElement, "UL");
if (!newUlElement) {
this.clearDragIndicators();
this.touchDragState = null;
return;
}
const oldScrollTop = this.element.scrollTop;
const toURL = newUlElement.getAttribute("data-url");
const toPath = newElement.getAttribute("data-path");
const selectRootElements: HTMLElement[] = [];
const selectFileElements: HTMLElement[] = [];
const fromPaths: string[] = [];
if (state.selectedElement.getAttribute("data-type") === "navigation-root") {
selectRootElements.push(state.selectedElement);
} else {
const dataPath = state.selectedElement.getAttribute("data-path");
// 禁止父节点移动到子节点 https://github.com/siyuan-note/siyuan/issues/12539
if (newElement.getAttribute("data-path").startsWith(dataPath.replace(".sy", ""))) {
this.clearDragIndicators();
this.touchDragState = null;
return;
}
fromPaths.push(dataPath);
selectFileElements.push(state.selectedElement);
}
if (newElement.classList.contains("dragover")) {
const sourceNotebookId = state.selectedElement.getAttribute("data-notebook-id") ||
state.selectedElement.closest("ul[data-url]")?.getAttribute("data-url") ||
state.selectedElement.getAttribute("data-url") || "";
if (!isMoveTargetAllowed([sourceNotebookId], toURL)) {
showMessage(window.siyuan.languages._kernel[391]);
this.clearDragIndicators();
this.touchDragState = null;
return;
}
fetchPost("/api/filetree/moveDocs", {
toNotebook: toURL,
fromPaths,
toPath,
});
this.clearDragIndicators();
this.touchDragState = null;
return;
}
if (newElement.classList.contains("dragover__bottom") || newElement.classList.contains("dragover__top")) {
const targetListElement = newElement.parentElement;
if (window.siyuan.config.fileTree.sort === 6 && selectRootElements.length > 0 &&
newElement.getAttribute("data-path") === "/") {
const sourceIDs = selectRootElements.map(item => item.parentElement.getAttribute("data-url"));
if (sourceIDs.includes(toURL)) {
this.clearDragIndicators();
this.touchDragState = null;
return;
}
if (newElement.classList.contains("dragover__top")) {
selectRootElements.forEach(item => {
newElement.parentElement.before(item.parentElement);
});
} else {
selectRootElements.reverse().forEach(item => {
newElement.parentElement.after(item.parentElement);
});
}
fetchPost("/api/notebook/reorder", getRelativeReorderRequest(
sourceIDs,
toURL,
!newElement.classList.contains("dragover__top")
));
} else if (!isCustomFileTreeList(targetListElement) && selectFileElements.length > 0) {
const after = newElement.classList.contains("dragover__bottom");
const sourceNotebookId = state.selectedElement.getAttribute("data-notebook-id") ||
state.selectedElement.closest("ul[data-url]")?.getAttribute("data-url") || "";
this.clearDragIndicators();
this.touchDragState = null;
if (!isMoveTargetAllowed([sourceNotebookId], toURL)) {
showMessage(window.siyuan.languages._kernel[391]);
return;
}
const result = await reorderSortedFileTree(
selectFileElements.map(item => item.getAttribute("data-node-id")),
newElement.getAttribute("data-node-id"), after);
if (result) {
const response = await fetchSyncPost("/api/filetree/listDocsByPath", {
notebook: result.notebook,
path: result.parentPath,
app: Constants.SIYUAN_APPID,
});
if (response.code === 0 && response.data?.files) {
this.onLsHTML(response.data, oldScrollTop);
}
}
return;
} else if (isCustomFileTreeList(targetListElement) && selectFileElements.length > 0) {
let hasMove = false;
const toDir = pathPosix().dirname(toPath);
if (fromPaths.length > 0) {
const sourceNotebookId = state.selectedElement.getAttribute("data-notebook-id") ||
state.selectedElement.closest("ul[data-url]")?.getAttribute("data-url") ||
state.selectedElement.getAttribute("data-url") || "";
if (!isMoveTargetAllowed([sourceNotebookId], toURL)) {
showMessage(window.siyuan.languages._kernel[391]);
this.clearDragIndicators();
this.touchDragState = null;
return;
}
await fetchSyncPost("/api/filetree/moveDocs", {
toNotebook: toURL,
fromPaths,
toPath: toDir === "/" ? "/" : toDir + ".sy",
callback: Constants.CB_MOVE_NOLIST,
});
selectFileElements.forEach(item => {
const fromPath = item.getAttribute("data-path");
const newPath = pathPosix().join(toDir, item.getAttribute("data-node-id") + ".sy");
updateMovedSubtree(item, getFileTreeChildList(item), fromPath, newPath, 20);
});
hasMove = true;
}
if (newElement.classList.contains("dragover__top")) {
selectFileElements.forEach(item => {
let nextULElement;
if (item.nextElementSibling && item.nextElementSibling.tagName === "UL") {
nextULElement = item.nextElementSibling;
}
newElement.before(item);
if (nextULElement) {
item.after(nextULElement);
}
});
} else if (newElement.classList.contains("dragover__bottom")) {
selectFileElements.reverse().forEach(item => {
let nextULElement;
if (item.nextElementSibling && item.nextElementSibling.tagName === "UL") {
nextULElement = item.nextElementSibling;
}
if (newElement.nextElementSibling && newElement.nextElementSibling.tagName === "UL") {
newElement.nextElementSibling.after(item);
} else {
newElement.after(item);
}
if (nextULElement) {
item.after(nextULElement);
}
});
}
fetchPost("/api/filetree/reorderDocs", getRelativeReorderRequest(
selectFileElements.map(item => item.getAttribute("data-node-id")),
newElement.getAttribute("data-node-id"),
!newElement.classList.contains("dragover__top")
), () => {
if (hasMove) {
fetchPost("/api/filetree/listDocsByPath", {
notebook: toURL,
path: toDir === "/" ? "/" : toDir + ".sy",
app: Constants.SIYUAN_APPID,
}, response => {
if (response.data.path === "/" && response.data.files.length === 0) {
showMessage(window.siyuan.languages.emptyContent);
return;
}
this.onLsHTML(response.data, oldScrollTop);
});
}
});
}
}
}
this.clearDragIndicators();
this.touchDragState = null;
});
const cancelTouchDrag = () => {
stopScrollAnimation();
this.touchDragState?.ghostElement?.remove();
if (this.touchDragState?.selectedElement) {
this.touchDragState.selectedElement.style.opacity = "";
}
this.clearDragIndicators();
this.touchDragState = null;
};
filesElement.addEventListener("touchcancel", cancelTouchDrag);
filesElement.addEventListener("pointercancel", cancelTouchDrag);
window.addEventListener("blur", cancelTouchDrag);
bindMousePointerTouchBridge(filesElement);
this.init();
}
private handleMsgCallback(data: IWebSocketData) {
if (data) { this.pinnedDocs?.onFileTreeMessage(data); }
if (data) {
switch (data.cmd) {
case "moveDocs":
this.onMove(data);
break;
case "reloadFiletree":
setNoteBook(() => {
this.init(false);
});
break;
case "boxDocFeatureChanged":
setNoteBook(() => {
this.updateBoxDocFeature();
});
break;
case "notebookIconChanged":
this.updateNotebookIcon(data.data);
break;
case "reloadNotebookInfo":
window.clearTimeout(this.reloadNotebookInfoTimeout);
this.reloadNotebookInfoTimeout = window.setTimeout(() => {
setNoteBook((notebooks) => {
notebooks.forEach((notebook) => {
const liElement = this.element.querySelector<HTMLElement>(
`ul[data-url="${notebook.id}"] > li[data-type="navigation-root"]`
);
if (liElement) {
this.updateSubFileCount(liElement, notebook.subFileCount);
}
});
});
}, 128);
break;
case "mount":
this.onMount(data);
emitToPlugins("opened-notebook", data);
break;
case "createnotebook":
setNoteBook((notebooks) => {
let previousId: string;
notebooks.find(item => {
if (!item.closed) {
if (item.id === data.data.box.id) {
if (previousId) {
this.element.querySelector(`.b3-list[data-url="${previousId}"]`).insertAdjacentHTML("afterend", this.genNotebook(data.data.box));
} else {
this.element.insertAdjacentHTML("afterbegin", this.genNotebook(data.data.box));
}
return true;
}
previousId = item.id;
}
});
});
break;
case "closeBox":
case "removeBox":
this.onRemove(data);
emitToPlugins("closed-notebook", data);
break;
case "removeDoc":
this.onRemove(data);
break;
case "create":
if (data.data.listDocTree) {
this.selectItem(data.data.box.id, data.data.path);
} else {
this.updateItemArrow(data.data.box.id, data.data.path);
}
break;
case "heading2doc":
this.updateItemArrow(data.data.box.id, data.data.path);
break;
case "createdailynote":
case "li2doc":
this.selectItem(data.data.box.id, data.data.path);
break;
case "reloadDocInfo":
this.updateDocInfo(data);
break;
case "renamenotebook": {
const name = data.data.name;
if (typeof name !== "string") {
break;
}
const notebook = window.siyuan.notebooks.find((item) => item.id === data.data.box);
if (notebook) {
notebook.name = name;
}
const textElement = this.element.querySelector(`[data-url="${data.data.box}"] .b3-list-item__text`) ||
this.closeElement.querySelector(`[data-url="${data.data.box}"] .b3-list-item__text`);
if (textElement) {
textElement.textContent = name;
}
break;
}
case "rename":
this.onRename(data.data);
break;
}
}
}
private updateNotebookIcon(data: { boxID: string, icon: string }) {
if (!data || typeof data.boxID !== "string" || typeof data.icon !== "string") {
return;
}
const notebook = window.siyuan.notebooks.find((item) => item.id === data.boxID);
if (!notebook) {
return;
}
notebook.icon = data.icon;
if (notebook.encrypted && notebook.closed) {
return;
}
const liElement = notebook.closed ?
this.closeElement.querySelector<HTMLElement>(`li[data-url="${data.boxID}"]`) :
this.element.querySelector<HTMLElement>(
`ul[data-url="${data.boxID}"] > li[data-type="navigation-root"]`
);
if (liElement) {
updateFileTreeItemIcon(liElement, data.icon, "notebook");
}
}
private startTouchDrag(state: MobileFiles["touchDragState"], clientX: number, clientY: number, vibrate = false) {
if (state.isDragging) {
return;
}
state.isDragging = true;
const ghostElement = document.createElement("ul");
ghostElement.id = "dragGhost";
ghostElement.append(state.selectedElement.cloneNode(true));
ghostElement.setAttribute("style", `background-color: var(--b3-theme-surface);width: 100%;touch-action: none;margin-left: -50%;margin-top:20px;z-index:${window.siyuan.zIndex};position: fixed;top:${clientY}px;left:${clientX}px`);
ghostElement.setAttribute("class", "b3-list b3-list--background");
document.body.append(ghostElement);
state.ghostElement = ghostElement;
state.selectedElement.style.opacity = "0.38";
if (vibrate) {
if (window.webkit?.messageHandlers.vibrate) {
window.webkit.messageHandlers.vibrate.postMessage("");
} else if (navigator.vibrate) {
navigator.vibrate(Constants.TIMEOUT_VIBRATION_DURATION);
}
}
}
private clearDragIndicators = () => {
if (!this.touchDragState) return;
this.element.querySelectorAll(".dragover__top, .dragover__bottom, .dragover").forEach(el => {
el.classList.remove("dragover__top", "dragover__bottom", "dragover");
});
};
public destroy() {
this.parentDocClick.cancel();
this.selectionObserver.disconnect();
this.pinnedDocs.destroy();
}
private genSort() {
toggleMenu({
target: this.element.querySelector("[data-type=sort]"),
build: (_menu, session) => {
const subMenu = sortMenu("notebooks", window.siyuan.config.fileTree.sort, (sort) => {
if (sort === null) {
return;
}
configApi.set("fileTree.sort", sort, () => {
this.onDocSortModeChanged({
scope: "global",
box: "",
id: "",
path: "/",
sortMode: sort,
});
});
});
subMenu.forEach((item) => {
window.siyuan.menus.menu.append(new MenuItem(item).element);
});
session.show(() => window.siyuan.menus.menu.fullscreen("bottom"));
},
});
}
private updateItemArrow(notebookId: string, filePath: string) {
const treeElement = this.element.querySelector(`[data-url="${notebookId}"]`);
if (!treeElement) {
return;
}
let currentPath = filePath;
let liElement;
while (!liElement) {
// 新文档只影响父级的子文档状态,从父路径开始查找。
const dirname = pathPosix().dirname(currentPath);
if (dirname === "/") {
const rootElement = treeElement.firstElementChild as HTMLElement;
if (rootElement.querySelector(".b3-list-item__arrow--open")) {
this.getLeaf(rootElement, notebookId, true);
}
break;
}
currentPath = dirname + ".sy";
liElement = treeElement.querySelector(`[data-path="${currentPath}"]`);
if (liElement) {
const hiddenElement = liElement.querySelector(".fn__hidden");
if (hiddenElement) {
// 原先无子文档:显示展开箭头
hiddenElement.classList.remove("fn__hidden");
syncFileTreeItemDefaultIcon(liElement as HTMLElement);
} else if (liElement.querySelector(".b3-list-item__arrow--open")) {
// 父文档已展开:刷新子列表
this.getLeaf(liElement, notebookId, true);
}
break;
}
}
}
private updateDocInfo(data: IWebSocketData) {
const notebook = window.siyuan.notebooks.find((item) => item.id === data.data.rootID);
const subFileCount = notebook && window.siyuan.isPublish ? notebook.subFileCount : data.data.subFileCount;
if (notebook) {
notebook.subFileCount = subFileCount;
}
const liElement = this.element.querySelector(
`li[data-node-id="${data.data.rootID}"][data-type="navigation-file"], ` +
`li[data-node-id="${data.data.rootID}"][data-type="navigation-root"]`
);
if (liElement) {
this.updateSubFileCount(liElement as HTMLElement, subFileCount);
}
}
private updateSubFileCount(liElement: HTMLElement, subFileCount: number) {
liElement.setAttribute("data-count", subFileCount.toString());
if (subFileCount === 0) {
liElement.querySelector(".b3-list-item__toggle")?.classList.add("fn__hidden");
liElement.querySelector(".b3-list-item__arrow")?.classList.remove("b3-list-item__arrow--open");
if (liElement.nextElementSibling?.tagName === "UL") {
liElement.nextElementSibling.remove();
}
} else {
liElement.querySelector(".b3-list-item__toggle")?.classList.remove("fn__hidden");
}
syncFileTreeItemDefaultIcon(liElement);
this.updateDocActionElement(liElement);
}
private updateDocActionElement(liElement: HTMLElement) {
if (liElement.getAttribute("data-type") !== "navigation-root" || !liElement.getAttribute("data-node-id")) {
return;
}
liElement.querySelector(".b3-list-item__icon")?.setAttribute("aria-label",
Number(liElement.getAttribute("data-count")) > 0 ?
window.siyuan.languages.docIconClickExpand : window.siyuan.languages.openDocument);
}
private updateBoxDocFeature() {
const enabled = window.siyuan.config.fileTree.boxDocEnabled;
window.siyuan.notebooks.forEach((notebook) => {
if (notebook.closed) {
return;
}
const notebookElement = this.element.querySelector<HTMLElement>(`:scope > ul[data-url="${notebook.id}"]`);
const rootElement = notebookElement?.querySelector<HTMLElement>(":scope > li[data-type=\"navigation-root\"]");
if (!notebookElement || !rootElement) {
return;
}
const subFileCount = updateNotebookRootForBoxDoc(rootElement, notebook, enabled);
rootElement.querySelector<HTMLElement>(".b3-list-item__icon")?.setAttribute("aria-label", enabled ?
(subFileCount > 0 ? window.siyuan.languages.docIconClickExpand : window.siyuan.languages.openDocument) :
window.siyuan.languages.changeIcon);
this.element.append(notebookElement);
});
}
private genNotebook(item: INotebook) {
const editingPublishAccess = this.actionsElement.querySelector('[data-type="publish-access"]').classList.contains("block__icon--active");
const locked = item.encrypted && item.closed;
const iconContent = locked
? getFileTreeIconHTML("", "lock")
: getFileTreeIconHTML(item.icon, "notebook");
const defaultIconAttr = getFileTreeDefaultIconAttr(locked ? "" : item.icon, locked ? "lock" : "notebook");
const isBoxDoc = !item.closed && window.siyuan.config.fileTree.boxDocEnabled;
const hasChildren = isBoxDoc && item.subFileCount > 0;
const iconAriaLabel = isBoxDoc ?
(hasChildren ? window.siyuan.languages.docIconClickExpand : window.siyuan.languages.openDocument) :
window.siyuan.languages.changeIcon;
const emojiHTML = `<span class="b3-list-item__icon b3-tooltips b3-tooltips__e${editingPublishAccess && !item.encrypted ? " fn__none" : ""}" aria-label="${iconAriaLabel}">${iconContent}</span>`;
const switchHTML = `<span class="b3-list-item__switch b3-tooltips b3-tooltips__e${editingPublishAccess && !item.encrypted ? "" : " fn__none"}" aria-label="${window.siyuan.languages.publishAccess}">${getPublishAccessOptionByLevel("public").iconHTML}</span>`;
if (item.closed) {
return `<li data-url="${item.id}" class="b3-list-item"${item.encrypted ? ' data-encrypted="true"' : ""}${defaultIconAttr}>
<span class="b3-list-item__toggle fn__hidden">
<svg class="b3-list-item__arrow"><use xlink:href="#iconRight"></use></svg>
</span>
${emojiHTML}
${switchHTML}
<span class="b3-list-item__text">${escapeHtml(item.name)}</span>
<span data-type="open" data-url="${item.id}" class="b3-list-item__action${(window.siyuan.config.readonly) ? " fn__none" : ""}">
<svg><use xlink:href="#iconOpen"></use></svg>
</span>
</li>`;
} else {
return `<ul class="b3-list b3-list--background" data-url="${item.id}" data-sortmode="${item.sortMode}"${item.encrypted ? " data-encrypted=\"true\"" : ""}>
<li class="b3-list-item" data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}" data-node-id="${window.siyuan.config.fileTree.boxDocEnabled ? item.id : ""}" style="--file-toggle-width:24px"${defaultIconAttr}>
<span class="b3-list-item__toggle${isBoxDoc && !hasChildren ? " fn__hidden" : ""}">
<svg class="b3-list-item__arrow"><use xlink:href="#iconRight"></use></svg>
</span>
${emojiHTML}
${switchHTML}
<span class="b3-list-item__text${item.closed ? " ft__on-surface" : ""}">${escapeHtml(item.name)}</span>
<span data-type="more-root" data-menu="true" class="b3-list-item__action${(window.siyuan.config.readonly || item.closed) ? " fn__none" : ""}">
<svg><use xlink:href="#iconMore"></use></svg>
</span>
<span data-type="new" class="b3-list-item__action${(window.siyuan.config.readonly || item.closed) ? " fn__none" : ""}">
<svg><use xlink:href="#iconAdd"></use></svg>
</span>
</li></ul>`;
}
}
public init(init = true) {
this.pinnedDocs?.scheduleRefresh();
let html = "";
let closeHtml = "";
let closeCounter = 0;
const scrollTop = this.element.scrollTop;
window.siyuan.notebooks.forEach((item) => {
if (item.closed) {
closeCounter++;
closeHtml += this.genNotebook(item);
} else {
html += this.genNotebook(item);
}
});
this.element.innerHTML = html;
this.closeElement.lastElementChild.innerHTML = closeHtml;
const counterElement = this.closeElement.querySelector(".counter");
counterElement.textContent = closeCounter.toString();
if (closeCounter) {
this.closeElement.classList.remove("fn__none");
} else {
this.closeElement.classList.add("fn__none");
}
const firstNotebook = this.element.firstElementChild;
void restoreFileTreePaths(window.siyuan.storage[Constants.LOCAL_FILESPATHS], async (notebookId, path) => {
if (this.element.firstElementChild !== firstNotebook) {
return;
}
const liElement = this.element.querySelector(`ul[data-url="${notebookId}"] li[data-path="${path}"]`);
if (!liElement || liElement.querySelector(".b3-list-item__arrow--open")) {
return;
}
const response = await fetchSyncPost("/api/filetree/listDocsByPath", {
notebook: notebookId,
path,
app: Constants.SIYUAN_APPID,
});
if (response.code !== 0 || !response.data || !this.element.contains(liElement) ||
liElement.querySelector(".b3-list-item__arrow--open")) {
return;
}
await this.onLsSelect(response.data, path, false, false);
}).then(() => {
if (this.element.firstElementChild === firstNotebook) {
this.refreshPublishAccessSwitch();
this.element.scrollTop = scrollTop;
}
});
this.refreshPublishAccessSwitch();
if (!init) {
return;
}
const svgElement = this.closeElement.querySelector("svg");
if (html !== "") {
this.closeElement.style.height = "42px";
svgElement.classList.remove("b3-list-item__arrow--open");
this.closeElement.lastElementChild.classList.add("fn__none");
} else {
this.closeElement.style.height = "40%";
svgElement.classList.add("b3-list-item__arrow--open");
this.closeElement.lastElementChild.classList.remove("fn__none");
}
}
private onMove(response: IWebSocketData) {
const moves = response.data.moves as IFileTreeMove[];
const hasParentChange = moves.some((move) =>
move.fromNotebook !== move.toNotebook ||
pathPosix().dirname(move.fromPath) !== pathPosix().dirname(move.newPath));
const refreshTargets = new Map<string, { element: HTMLElement, notebookId: string }>();
moves.forEach((move) => {
const expandedDocIDs = new Set<string>();
const movedItem = findMovedFileTreeItem(this.element, move);
const sourceElement = movedItem?.element;
const sourceAtTarget = movedItem?.isAtTarget;
let childListElement: HTMLElement;
if (sourceElement) {
childListElement = getFileTreeChildList(sourceElement);
collectExpandedDocIDs(sourceElement, childListElement, expandedDocIDs);
updateMovedSubtree(sourceElement, childListElement, move.fromPath, move.newPath, 20);
}
if (sourceElement && !sourceAtTarget) {
const sourceListElement = sourceElement.parentElement;
childListElement?.remove();
if (sourceListElement.childElementCount === 1) {
const parentLiElement = sourceListElement.previousElementSibling as HTMLElement;
if (parentLiElement) {
if (parentLiElement.getAttribute("data-type") !== "navigation-root" ||
parentLiElement.dataset.nodeId) {
parentLiElement.querySelector(".b3-list-item__toggle").classList.add("fn__hidden");
}
parentLiElement.querySelector(".b3-list-item__arrow").classList.remove(
"b3-list-item__arrow--open"
);
parentLiElement.setAttribute("data-count", "0");
this.updateDocActionElement(parentLiElement);
syncFileTreeItemDefaultIcon(parentLiElement);
}
sourceListElement.remove();
} else {
sourceElement.remove();
}
} else if (!sourceElement || sourceAtTarget) {
const parentPath = pathPosix().dirname(move.fromPath);
const parentElement = this.element.querySelector(
`ul[data-url="${move.fromNotebook}"] li[data-path="${parentPath === "/" ? "/" : parentPath + ".sy"}"]`
) as HTMLElement;
if (parentElement && parentElement.getAttribute("data-count") === "1") {
parentElement.querySelector(".b3-list-item__toggle").classList.add("fn__hidden");
parentElement.querySelector(".b3-list-item__arrow").classList.remove(
"b3-list-item__arrow--open"
);
syncFileTreeItemDefaultIcon(parentElement);
}
}
const targetElement = this.element.querySelector(
`[data-url="${move.toNotebook}"] li[data-path="${move.toPath}"]`
) as HTMLElement;
if (!targetElement) {
expandedDocIDs.forEach((id) => this.movedExpandedDocIDs.add(id));
return;
}
targetElement.querySelector(".b3-list-item__toggle").classList.remove("fn__hidden");
if (targetElement.getAttribute("data-type") === "navigation-root") {
targetElement.setAttribute(
"data-count",
Math.max(1, Number(targetElement.getAttribute("data-count"))).toString()
);
this.updateDocActionElement(targetElement);
}
syncFileTreeItemDefaultIcon(targetElement);
const targetListElement = getFileTreeChildList(targetElement);
const targetExpanded = Boolean(targetElement.querySelector(".b3-list-item__arrow--open"));
if (sourceElement && targetListElement && !sourceAtTarget) {
targetListElement.append(sourceElement);
if (childListElement) {
sourceElement.after(childListElement);
}
}
if (!targetExpanded || !sourceElement || (!sourceAtTarget && !targetListElement)) {
expandedDocIDs.forEach((id) => this.movedExpandedDocIDs.add(id));
}
if (targetExpanded) {
refreshTargets.set(`${move.toNotebook}:${move.toPath}`, {
element: targetElement,
notebookId: move.toNotebook,
});
}
});
if (hasParentChange) {
this.getOpenPaths();
}
if (response.callback !== Constants.CB_MOVE_NOLIST) {
refreshTargets.forEach((target) => {
this.getLeaf(target.element, target.notebookId, true);
});
}
getMovedFileTreeSortRefreshTargets(this.element, moves).forEach((target) => {
const notebookElement = Array.from(this.element.children).find((item) =>
item.getAttribute("data-url") === target.notebookId
);
const liElement = Array.from(notebookElement?.querySelectorAll("li[data-path]") || []).find((item) =>
item.getAttribute("data-path") === target.path
);
if (liElement) {
this.getLeaf(liElement, target.notebookId, true);
}
});
}
private restoreMovedExpandedItems(listElement: Element, notebookId: string) {
restoreMovedExpandedDocItems(listElement, this.movedExpandedDocIDs, (item) => {
this.getLeaf(item, notebookId, true);
});
}
private onRemove(data: IWebSocketData) {
removeFileTreeItems({
element: this.element,
closeElement: this.closeElement,
genNotebook: (notebook) => this.genNotebook(notebook),
updateDocActionElement: (element) => this.updateDocActionElement(element),
}, data);
}
public onRename(data: { path: string, title: string, box: string }) {
const fileItemElement = this.element.querySelector(`ul[data-url="${data.box}"] li[data-path="${data.path}"]`);
if (fileItemElement) {
fileItemElement.setAttribute("data-name", data.title);
fileItemElement.querySelector(".b3-list-item__text").innerHTML = escapeHtml(data.title);
}
const parentPath = pathPosix().dirname(data.path);
const listPath = parentPath === "/" ? "/" : `${parentPath}.sy`;
const parentElement = this.element.querySelector(`ul[data-url="${data.box}"] li[data-path="${listPath}"]`);
const listElement = parentElement?.nextElementSibling;
if (listElement?.tagName === "UL" && !isCustomFileTreeList(listElement)) {
this.onFiletreeSortChanged({notebook: data.box, parentPath});
}
}
public onFiletreeSortChanged(data: { notebook: string, parentPath: string }) {
const notebookElement = this.element.querySelector(`ul[data-url="${data.notebook}"]`);
if (!notebookElement) {
return;
}
const listPath = data.parentPath === "/" ? "/" : `${data.parentPath}.sy`;
const liElement = notebookElement.querySelector(`li[data-path="${listPath}"]`);
const listElement = liElement?.nextElementSibling;
if (!listElement || listElement.tagName !== "UL") {
return;
}
fetchPost("/api/filetree/listDocsByPath", {
notebook: data.notebook,
path: listPath,
app: Constants.SIYUAN_APPID,
}, response => {
this.onLsHTML(response.data);
});
}
public onDocsImported(data: { notebook: string, parentPath: string, rootIDs: string[] }) {
const rootID = data.rootIDs?.[0];
if (!rootID) {
return;
}
this.pinnedDocs?.scheduleRefresh();
const importedPath = data.parentPath === "/" ? `/${rootID}.sy` : `${data.parentPath}/${rootID}.sy`;
this.updateItemArrow(data.notebook, importedPath);
}
public onDocSortModeChanged(data: IDocSortModeChanged) {
this.pinnedDocs?.scheduleRefresh();
updateFileTreeSortMode(data, this.element);
this.docSortModeChanges.set(`${data.scope}:${data.box}:${data.id}:${data.path}`, data);
window.clearTimeout(this.docSortModeRefreshTimeout);
this.docSortModeRefreshTimeout = window.setTimeout(() => {
const changes = Array.from(this.docSortModeChanges.values());
this.docSortModeChanges.clear();
const refreshLists = () => {
getFileTreeSortRefreshTargets(this.element, changes).forEach((target) => {
const notebookElement = Array.from(this.element.children).find((item) =>
item.getAttribute("data-url") === target.notebookId
);
const liElement = Array.from(notebookElement?.querySelectorAll("li[data-path]") || []).find((item) =>
item.getAttribute("data-path") === target.path
);
if (liElement) {
this.getLeaf(liElement, target.notebookId, true);
}
});
};
if (changes.some((item) => item.scope === "global")) {
setNoteBook((notebooks) => {
reorderFileTreeNotebooks(this.element, this.closeElement.lastElementChild, notebooks);
refreshLists();
});
} else {
refreshLists();
}
}, 100);
}
public onNotebookSortChanged() {
if (window.siyuan.config.fileTree.sort !== 6) {
return;
}
setNoteBook((notebooks) => {
reorderFileTreeNotebooks(this.element, this.closeElement.lastElementChild, notebooks);
});
}
private onMount(data: IWebSocketData) {
if (data.data.existed) {
return;
}
const liElement = this.closeElement.querySelector(`li[data-url="${data.data.box.id}"]`) as HTMLElement;
if (liElement) {
liElement.remove();
const counterElement = this.closeElement.querySelector(".counter");
counterElement.textContent = (parseInt(counterElement.textContent) - 1).toString();
if (counterElement.textContent === "0") {
this.closeElement.classList.add("fn__none");
}
}
setNoteBook((notebooks: INotebook[]) => {
const notebook = notebooks.find((item) => item.id === data.data.box.id) || data.data.box;
const html = this.genNotebook(notebook);
if (this.element.childElementCount === 0) {
this.element.innerHTML = html;
} else {
let previousId;
notebooks.find((item, index) => {
if (item.id === data.data.box.id) {
while (index > 0) {
if (!notebooks[index - 1].closed) {
previousId = notebooks[index - 1].id;
break;
} else {
index--;
}
}
return true;
}
});
if (previousId) {
this.element.querySelector(`[data-url="${previousId}"]`).insertAdjacentHTML("afterend", html);
} else {
this.element.insertAdjacentHTML("afterbegin", html);
}
}
});
}
private onLsHTML(data: IFileTreeList, scrollTop?: number) {
if (data.files.length === 0) {
return;
}
const liElement = this.element.querySelector(`ul[data-url="${data.box}"] li[data-path="${data.path}"]`);
if (!liElement) {
return;
}
let fileHTML = "";
data.files.forEach((item: IFile) => {
fileHTML += this.genFileHTML(item);
});
const effectiveSortMode = getResponseEffectiveSortMode(data, data.box);
let nextElement = liElement.nextElementSibling;
if (nextElement && nextElement.tagName === "UL") {
// 文件展开时,刷新
const tempElement = document.createElement("template");
tempElement.innerHTML = fileHTML;
const focusedIDs = Array.from(nextElement.querySelectorAll(":scope > .b3-list-item--focus")).map((item) =>
item.getAttribute("data-node-id")
);
focusedIDs.forEach((id) => {
Array.from(tempElement.content.children).find((item) =>
item.getAttribute("data-node-id") === id
)?.classList.add("b3-list-item--focus");
});
// 保持文件夹展开状态
nextElement.querySelectorAll(":scope > .b3-list-item > .b3-list-item__toggle> .b3-list-item__arrow--open").forEach(item => {
const openLiElement = hasClosestByClassName(item, "b3-list-item");
if (openLiElement) {
const tempOpenLiElement = tempElement.content.querySelector(`.b3-list-item[data-node-id="${openLiElement.getAttribute("data-node-id")}"]`);
if (tempOpenLiElement) {
tempOpenLiElement.after(openLiElement.nextElementSibling);
tempOpenLiElement.querySelector(".b3-list-item__arrow").classList.add("b3-list-item__arrow--open");
}
}
});
nextElement.innerHTML = tempElement.innerHTML;
nextElement.setAttribute(FILE_TREE_EFFECTIVE_SORT_MODE, effectiveSortMode.toString());
this.restoreMovedExpandedItems(nextElement, data.box);
if (typeof scrollTop === "number") {
this.element.scroll({top: scrollTop, behavior: "smooth"});
}
this.refreshPublishAccessSwitch();
return;
}
liElement.querySelector(".b3-list-item__arrow").classList.add("b3-list-item__arrow--open");
liElement.insertAdjacentHTML("afterend", `<ul ${FILE_TREE_EFFECTIVE_SORT_MODE}="${effectiveSortMode}">${fileHTML}</ul>`);
nextElement = liElement.nextElementSibling;
this.restoreMovedExpandedItems(nextElement, data.box);
expandFileTree(nextElement as HTMLElement, () => {
if (typeof scrollTop === "number") {
this.element.scroll({top: scrollTop, behavior: "smooth"});
}
});
this.refreshPublishAccessSwitch();
}
private async onLsSelect(data: IFileTreeList, filePath: string, setStorage: boolean, isSetCurrent: boolean) {
if (data.files.length === 0) {
return;
}
const liElement = this.element.querySelector(`ul[data-url="${data.box}"] li[data-path="${data.path}"]`);
if (!liElement) {
return;
}
const arrowElement = liElement.querySelector(".b3-list-item__arrow");
arrowElement.parentElement.classList.remove("fn__hidden");
syncFileTreeItemDefaultIcon(liElement as HTMLElement);
this.onLsHTML(data);
let newLiElement;
for (let i = 0; i < data.files.length; i++) {
const item = data.files[i];
if (filePath === item.path) {
newLiElement = await this.selectItem(data.box, filePath, undefined, setStorage, isSetCurrent);
} else if (filePath.startsWith(item.path.replace(".sy", ""))) {
const response = await fetchSyncPost("/api/filetree/listDocsByPath", {
notebook: data.box,
path: item.path,
app: Constants.SIYUAN_APPID,
});
if (response.code === 0) {
newLiElement = await this.selectItem(response.data.box, filePath, response.data, setStorage, isSetCurrent);
}
}
}
if (isSetCurrent) {
this.setCurrent(newLiElement);
}
return newLiElement;
}
private toggleTreeItem(item: HTMLElement) {
const notebookId = item.closest("ul[data-url]")?.getAttribute("data-url");
if (!notebookId) {
return;
}
if (item.querySelector(".b3-list-item__arrow--open")) {
collapseFileTree(item, () => this.getOpenPaths());
} else if (!isFileTreeCollapsing(item)) {
this.getLeaf(item, notebookId);
}
this.setCurrent(item, false);
window.siyuan.menus.menu.remove();
}
private handleParentDocClick(item: HTMLElement, notebookId: string) {
const docId = item.getAttribute("data-node-id");
// 单击展开且不双击打开时立即切换,无需等待双击判定
if (window.siyuan.config.fileTree.parentDocTitleClickMode !== 2) {
this.parentDocClick.cancel();
this.toggleTreeItem(item);
return;
}
this.parentDocClick.click(item, async () => {
const expanded = !!item.querySelector(".b3-list-item__arrow--open");
const path = item.getAttribute("data-path");
const response = expanded ? undefined : await fetchSyncPost("/api/filetree/listDocsByPath", {
notebook: notebookId,
path,
app: Constants.SIYUAN_APPID,
});
return () => {
if (window.siyuan.config.fileTree.parentDocTitleClickMode !== 2 ||
item.getAttribute("data-node-id") !== docId || item.getAttribute("data-path") !== path ||
Number(item.getAttribute("data-count")) <= 0 ||
!!item.querySelector(".b3-list-item__arrow--open") !== expanded) { return; }
if (expanded) {
this.toggleTreeItem(item);
} else if (response.code === 0) {
this.onLsHTML(response.data);
this.getOpenPaths();
this.setCurrent(item, false);
window.siyuan.menus.menu.remove();
}
};
}, () => openMobileFileById(this.app, docId, [Constants.CB_GET_SCROLL], undefined, notebookId));
}
private insertMultiSelectMenu(item: HTMLElement) {
if (window.siyuan.config.readonly) {
return;
}
const menuItem = new MenuItem({
id: "multiSelect",
icon: "iconCheck",
label: window.siyuan.languages.multiSelect,
click: () => {
this.setCurrent(item, false);
this.setMultiSelect(true);
}
}).element;
insertMobileMultiSelectMenu(window.siyuan.menus.menu.element.lastElementChild, menuItem);
}
private setMultiSelect(enabled: boolean) {
this.parentDocClick.cancel();
this.multiSelect = enabled;
this.touchDragState = null;
this.openedFileSelection.cancel();
this.actionsElement.classList.toggle("fn__none", enabled);
this.selectionElement.classList.toggle("fn__none", !enabled);
if (enabled) {
showMessage(window.siyuan.languages.mobileFileTreeMultiSelectTip);
this.selectionObserver.observe(this.element, {childList: true, subtree: true, attributes: true, attributeFilter: ["class"]});
} else {
this.selectionObserver.disconnect();
}
this.updateMultiSelect();
if (!enabled) {
this.element.querySelectorAll(".b3-list-item--focus").forEach(item => {
item.classList.remove("b3-list-item--focus");
});
}
}
private updateMultiSelect() {
if (!this.multiSelect) {
return;
}
const count = this.element.querySelectorAll("li.b3-list-item--focus").length;
updateMultiSelectToolbar(this.selectionElement, count);
}
public setCurrent(target: HTMLElement, isScroll = true) {
if (!target || this.multiSelect) {
return;
}
this.pinnedDocs.clearSelection();
this.element.querySelectorAll("li.b3-list-item--focus").forEach((liItem) => {
liItem.classList.remove("b3-list-item--focus");
});
target.classList.add("b3-list-item--focus");
if (isScroll) {
const elementRect = this.element.getBoundingClientRect();
this.element.scrollTop = this.element.scrollTop + (target.getBoundingClientRect().top - (elementRect.top + elementRect.height / 2));
}
}
public async selectOpenedFile(notebookId: string, filePath: string) {
if (this.multiSelect) {
return;
}
const currentElement = this.element.querySelector(
`ul[data-url="${notebookId}"] li[data-path="${filePath}"]`
);
if (currentElement?.classList.contains("b3-list-item--focus")) {
this.openedFileSelection.cancel();
return;
}
const target = await this.openedFileSelection.resolve(
() => this.selectItem(notebookId, filePath, undefined, true, false),
() => {
const protyle = window.siyuan.mobile.editor?.protyle;
return window.siyuan.config.fileTree.alwaysSelectOpenedFile &&
!protyle?.element.classList.contains("fn__none") &&
protyle?.notebookId === notebookId && protyle.path === filePath;
}
);
this.setCurrent(target);
}
public getLeaf(liElement: Element, notebookId: string, focusUpdate = false) {
const toggleElement = liElement.querySelector(".b3-list-item__arrow");
if (cancelFileTreeCollapse(liElement)) {
this.getOpenPaths();
if (!focusUpdate) {
return;
}
}
const leafElement = liElement.nextElementSibling as HTMLElement;
if (toggleElement.classList.contains("b3-list-item__arrow--open") && !focusUpdate) {
toggleElement.classList.remove("b3-list-item__arrow--open");
leafElement?.remove();
this.getOpenPaths();
return;
}
fetchPost("/api/filetree/listDocsByPath", {
notebook: notebookId,
path: liElement.getAttribute("data-path"),
app: Constants.SIYUAN_APPID,
}, response => {
if (response.data.path === "/" && response.data.files.length === 0) {
if (!this.multiSelect) {
newFileInTree(this.app, notebookId, "/");
}
return;
}
this.onLsHTML(response.data);
this.getOpenPaths();
});
}
public async selectItem(notebookId: string, filePath: string, data?: IFileTreeList,
setStorage = true, isSetCurrent = true) {
const treeElement = this.element.querySelector(`[data-url="${notebookId}"]`);
if (!treeElement) {
// 有文件树和编辑器的布局初始化时,文件树还未挂载
return;
}
const boxDocID = window.siyuan.config.fileTree.boxDocEnabled ? notebookId : "";
if (boxDocID && filePath === `/${boxDocID}.sy`) {
const boxDocElement = treeElement.querySelector("[data-type=\"navigation-root\"]") as HTMLElement;
if (isSetCurrent) {
this.setCurrent(boxDocElement);
}
return boxDocElement;
}
let currentPath = filePath;
let liElement: HTMLElement;
while (!liElement) {
liElement = treeElement.querySelector(`[data-path="${currentPath}"]`);
if (!liElement) {
const dirname = pathPosix().dirname(currentPath);
if (dirname === "/") {
currentPath = dirname;
} else {
currentPath = dirname + ".sy";
}
}
}
if (liElement.getAttribute("data-path") === filePath) {
if (setStorage) {
this.getOpenPaths();
}
if (isSetCurrent) {
this.setCurrent(liElement);
}
return liElement;
}
if (data && data.path === currentPath) {
liElement = await this.onLsSelect(data, filePath, setStorage, isSetCurrent);
} else {
const response = await fetchSyncPost("/api/filetree/listDocsByPath", {
notebook: notebookId,
path: currentPath,
app: Constants.SIYUAN_APPID,
});
if (response.code === 0) {
liElement = await this.onLsSelect(response.data, filePath, setStorage, isSetCurrent);
}
}
this.refreshPublishAccessSwitch();
return liElement;
}
private getOpenPaths() {
saveOpenFileTreePaths(this.element);
}
private genFileHTML = (item: IFile) => {
let countHTML = "";
if (item.count && item.count > 0) {
countHTML = `<span class="counter">${item.count}</span>`;
}
const paddingLeft = (item.path.split("/").length - 1) * 20;
const editingPublishAccess = this.actionsElement.querySelector('[data-type="publish-access"]').classList.contains("block__icon--active");
const defaultIcon = item.subFileCount === 0 ? "file" : "folder";
const actionHTML = `<span data-type="more-file" data-menu="true" class="b3-list-item__action b3-tooltips b3-tooltips__nw" aria-label="${window.siyuan.languages.more}">
<svg><use xlink:href="#iconMore"></use></svg>
</span>
<span data-type="new" class="b3-list-item__action b3-tooltips b3-tooltips__nw${window.siyuan.config.readonly ? " fn__none" : ""}" aria-label="${window.siyuan.languages.newSubDoc}">
<svg><use xlink:href="#iconAdd"></use></svg>
</span>`;
return `<li data-node-id="${item.id}" data-name="${escapeHtmlTextAndAttr(item.name)}" data-count="${item.subFileCount}" ${FILE_TREE_CHILDREN_SORT_MODE}="${item.childrenSortMode ?? ""}" data-type="navigation-file"
class="b3-list-item" data-path="${item.path}" style="--file-toggle-width:${paddingLeft + 20}px"${getFileTreeDefaultIconAttr(item.icon, defaultIcon)}>
<span style="padding-left: ${paddingLeft}px" class="b3-list-item__toggle${item.subFileCount === 0 ? " fn__hidden" : ""}">
<svg class="b3-list-item__arrow"><use xlink:href="#iconRight"></use></svg>
</span>
<span class="b3-list-item__icon"${editingPublishAccess ? " fn__none" : ""}>${getFileTreeIconHTML(item.icon, defaultIcon)}</span>
<span class="b3-list-item__switch${editingPublishAccess ? "" : " fn__none"}">${getPublishAccessOptionByLevel("public").iconHTML}</span>
<span class="b3-list-item__text">${getDocDisplayName(item.name, item.titleEmpty, true)}</span>
${getTreeItemTailHTML(countHTML, actionHTML, true)}
</li>`;
};
private updatePublishAccessControls(editingPublishAccess: boolean) {
this.element.querySelectorAll(".b3-list-item__icon").forEach(item => {
const encrypted = Boolean(item.closest("[data-encrypted=true]"));
item.classList.toggle("fn__none", editingPublishAccess && !encrypted);
const switchElement = item.nextElementSibling;
if (switchElement) {
switchElement.classList.toggle("fn__none", !editingPublishAccess || encrypted);
}
});
}
private refreshPublishAccessSwitch() {
const editingPublishAccess = this.actionsElement.querySelector('[data-type="publish-access"]').classList.contains("block__icon--active");
this.updatePublishAccessControls(editingPublishAccess);
if (window.siyuan.config.readonly || window.siyuan.isPublish || !editingPublishAccess) {
return;
}
const ids: string[] = [];
this.element.querySelectorAll("[data-url]").forEach((element: HTMLElement) => {
if (!element.closest("[data-encrypted=true]")) {
ids.push(element.getAttribute("data-url"));
}
});
this.element.querySelectorAll("[data-type=\"navigation-file\"][data-node-id]").forEach((element: HTMLElement) => {
if (!element.closest("[data-encrypted=true]")) {
ids.push(element.getAttribute("data-node-id"));
}
});
fetchPost("/api/filetree/getPublishAccess", {
ids
}, response => {
response.data.publishAccess.forEach((item: IPublishAccessItem) => {
const element = this.element.querySelector(`[data-url="${item.id}"] .b3-list-item__switch`) || this.element.querySelector(`[data-node-id="${item.id}"] .b3-list-item__switch`);
if (element) {
element.innerHTML = getPublishAccessOptionByLevel(getPublishAccessLevel(item.visible, item.password, item.disable)).iconHTML;
}
});
});
}
}