An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Improve the creation of new documents (#17959)
Jeffrey Chen887e5d8ed291
diff --git a/app/package.json b/app/package.jsonindex 8f9d31429c..ce10600b2d 100644--- a/app/package.json+++ b/app/package.json@@ -8,6 +8,7 @@"packageManager": "[email protected]","scripts": {"lint": "eslint . --fix --cache",+ "test": "node --import tsx --test","dev": "webpack --mode development","dev:mobile": "webpack --mode development --config webpack.mobile.js","dev:desktop": "webpack --mode development --config webpack.desktop.js",@@ -87,6 +88,7 @@"safer-buffer": "^2.1.2","sass": "^1.89.2","sass-loader": "^16.0.5",+ "tsx": "^4.22.4","typescript": "^4.9.5","webpack": "^5.104.1","webpack-bundle-analyzer": "^4.5.0",diff --git a/app/src/boot/globalEvent/command/global.ts b/app/src/boot/globalEvent/command/global.tsindex 31509153e3..55f2c98b3c 100644--- a/app/src/boot/globalEvent/command/global.ts+++ b/app/src/boot/globalEvent/command/global.ts@@ -435,10 +435,7 @@ export const globalCommand = (command: string, app: App) => {lockScreen(app);return true;case "newFile":- newFile({- app,- useSavePath: true- });+ newFile(app);return true;case "riffCard":openCard(app);diff --git a/app/src/boot/globalEvent/keydown.ts b/app/src/boot/globalEvent/keydown.tsindex 637698e0a1..a7b5f06fc4 100644--- a/app/src/boot/globalEvent/keydown.ts+++ b/app/src/boot/globalEvent/keydown.ts@@ -1395,10 +1395,7 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {return;}if (matchHotKey(window.siyuan.config.keymap.general.newFile.custom, event)) {- newFile({- app,- useSavePath: true- });+ newFile(app);event.preventDefault();return;}diff --git a/app/src/boot/globalEvent/searchKeydown.ts b/app/src/boot/globalEvent/searchKeydown.tsindex 4f70b180f7..c5b24d7163 100644--- a/app/src/boot/globalEvent/searchKeydown.ts+++ b/app/src/boot/globalEvent/searchKeydown.ts@@ -4,7 +4,7 @@ import * as path from "path";import {matchHotKey} from "../../protyle/util/hotKey";import {fetchPost} from "../../util/fetch";import {Constants} from "../../constants";-import {newFileByName} from "../../util/newFile";+import {newFile} from "../../util/newFile";import {App} from "../../index";import {Dialog} from "../../dialog";import {getAllModels} from "../../layout/getAll";@@ -62,7 +62,7 @@ export const searchKeydown = (app: App, event: KeyboardEvent) => {const searchInputElement = element.querySelector("#searchInput") as HTMLInputElement;if (searchType === "doc" && matchHotKey(window.siyuan.config.keymap.general.newFile.custom, event)) {if (config.method === 0) {- newFileByName(app, searchInputElement.value);+ newFile(app, searchInputElement.value);}return true;}@@ -90,7 +90,7 @@ export const searchKeydown = (app: App, event: KeyboardEvent) => {}if (currentList.getAttribute("data-type") === "search-new") {if (event.key === "Enter" && config.method === 0) {- newFileByName(app, searchInputElement.value);+ newFile(app, searchInputElement.value);return true;}return false;diff --git a/app/src/layout/Wnd.ts b/app/src/layout/Wnd.tsindex ee3d116112..caaa54007d 100644--- a/app/src/layout/Wnd.ts+++ b/app/src/layout/Wnd.ts@@ -135,10 +135,7 @@ export class Wnd {while (target && !target.isEqualNode(this.headersElement)) {if (target.classList.contains("block__icon") && target.getAttribute("data-type") === "new") {setPanelFocus(this.headersElement.parentElement.parentElement);- newFile({- app,- useSavePath: true- });+ newFile(app);break;} else if (target.classList.contains("block__icon") && target.getAttribute("data-type") === "more") {this.renderTabList(target);diff --git a/app/src/layout/dock/Files.ts b/app/src/layout/dock/Files.tsindex 14f44975fe..7f07a48c0f 100644--- a/app/src/layout/dock/Files.ts+++ b/app/src/layout/dock/Files.ts@@ -5,7 +5,7 @@ import {setPanelFocus} from "../util";import {getDockByType} from "../tabUtil";import {Constants} from "../../constants";import {getDocDisplayName, pathPosix, setNoteBook} from "../../util/pathName";-import {newFile} from "../../util/newFile";+import {newFileInTree} from "../../util/newFile";import {initFileMenu, initNavigationMenu, sortMenu} from "../../menus/navigation";import {MenuItem} from "../../menus/Menu";import {showMessage} from "../../dialog/message";@@ -244,13 +244,7 @@ export class Files extends Model {const pathString = target.parentElement.getAttribute("data-path");if (!window.siyuan.config.readonly) {if (type === "new") {- newFile({- app: options.app,- notebookId,- currentPath: pathString,- useSavePath: false,- listDocTree: true,- });+ newFileInTree(options.app, notebookId, pathString);} else if (type === "more-root") {initNavigationMenu(options.app, target.parentElement).popup({x: event.clientX,@@ -1299,13 +1293,7 @@ data-type="navigation-root" data-path="/">app: Constants.SIYUAN_APPID,}, response => {if (response.data.path === "/" && response.data.files.length === 0) {- newFile({- app: this.app,- notebookId,- currentPath: "/",- useSavePath: false,- listDocTree: true,- });+ newFileInTree(this.app, notebookId, "/");return;}this.onLsHTML(response.data);diff --git a/app/src/layout/tabUtil.ts b/app/src/layout/tabUtil.tsindex 8bc76a7601..bc744b651e 100644--- a/app/src/layout/tabUtil.ts+++ b/app/src/layout/tabUtil.ts@@ -309,10 +309,7 @@ export const newCenterEmptyTab = (app: App) => {event.preventDefault();break;} else if (target.id === "editorEmptyFile") {- newFile({- app,- useSavePath: true- });+ newFile(app);event.stopPropagation();event.preventDefault();break;diff --git a/app/src/menus/navigation.ts b/app/src/menus/navigation.tsindex b10a06f1ec..fc386a7918 100644--- a/app/src/menus/navigation.ts+++ b/app/src/menus/navigation.ts@@ -15,7 +15,7 @@ import {closePanel} from "../mobile/util/closePanel";import {popSearch} from "../mobile/menu/search";/// #endifimport {Constants} from "../constants";-import {newFile} from "../util/newFile";+import {newFileInTree} from "../util/newFile";import {hasClosestByTag, hasTopClosestByTag} from "../protyle/util/hasClosest";import {deleteFiles} from "../editor/deleteFile";import {getDockByType} from "../layout/tabUtil";@@ -451,14 +451,7 @@ export const initFileMenu = (app: App, notebookId: string, pathString: string, lpaths.push(item.getAttribute("data-path"));}});- newFile({- app,- notebookId,- currentPath: pathPosix().dirname(pathString),- paths,- useSavePath: false,- listDocTree: true,- });+ newFileInTree(app, notebookId, pathPosix().dirname(pathString), paths);}}).element);window.siyuan.menus.menu.append(new MenuItem({@@ -475,14 +468,7 @@ export const initFileMenu = (app: App, notebookId: string, pathString: string, l}}});- newFile({- app,- notebookId,- currentPath: pathPosix().dirname(pathString),- paths,- useSavePath: false,- listDocTree: true,- });+ newFileInTree(app, notebookId, pathPosix().dirname(pathString), paths);}}).element);window.siyuan.menus.menu.append(new MenuItem({id: "separator_1", type: "separator"}).element);diff --git a/app/src/mobile/dock/MobileFiles.ts b/app/src/mobile/dock/MobileFiles.tsindex 8d919d714f..f9d3e92283 100644--- a/app/src/mobile/dock/MobileFiles.ts+++ b/app/src/mobile/dock/MobileFiles.ts@@ -14,7 +14,7 @@ import {genUUID} from "../../util/genID";import {openMobileFileById} from "../editor";import {unicode2Emoji} from "../../emoji";import {mountHelp, newNotebook} from "../../util/mount";-import {newFile} from "../../util/newFile";+import {newFileInTree} from "../../util/newFile";import {MenuItem} from "../../menus/Menu";import {App} from "../../index";import {refreshFileTree} from "../../dialog/processSystem";@@ -184,13 +184,7 @@ export class MobileFiles extends Model {const notebookId = ulElement.getAttribute("data-url");if (!window.siyuan.config.readonly) {if (type === "new") {- newFile({- app,- notebookId,- currentPath: pathString,- useSavePath: false,- listDocTree: true,- });+ newFileInTree(app, notebookId, pathString);} else if (type === "more-root") {initNavigationMenu(app, target.parentElement);window.siyuan.menus.menu.fullscreen("bottom");@@ -959,13 +953,7 @@ export class MobileFiles extends Model {app: Constants.SIYUAN_APPID,}, response => {if (response.data.path === "/" && response.data.files.length === 0) {- newFile({- app: this.app,- notebookId,- currentPath: "/",- useSavePath: false,- listDocTree: true,- });+ newFileInTree(this.app, notebookId, "/");return;}this.onLsHTML(response.data);diff --git a/app/src/mobile/menu/index.ts b/app/src/mobile/menu/index.tsindex 183ee1210e..0caac93859 100644--- a/app/src/mobile/menu/index.ts+++ b/app/src/mobile/menu/index.ts@@ -133,10 +133,7 @@ export const initRightMenu = (app: App) => {event.stopPropagation();break;} else if (target.id === "menuNewDoc") {- newFile({- app,- useSavePath: true- });+ newFile(app);closePanel();event.preventDefault();event.stopPropagation();diff --git a/app/src/mobile/menu/search.ts b/app/src/mobile/menu/search.tsindex 6e73688e4d..5b8bd71b94 100644--- a/app/src/mobile/menu/search.ts+++ b/app/src/mobile/menu/search.ts@@ -10,7 +10,7 @@ import {getKeyByLiElement, initCriteriaMenu, moreMenu} from "../../search/menu";import {setStorageVal} from "../../protyle/util/compatibility";import {escapeHtml} from "../../util/escape";import {unicode2Emoji} from "../../emoji";-import {newFileByName} from "../../util/newFile";+import {newFile} from "../../util/newFile";import {showMessage} from "../../dialog/message";import {reloadProtyle} from "../../protyle/util/reload";import {activeBlur} from "../util/keyboardToolbar";@@ -670,7 +670,7 @@ const initSearchEvent = (app: App, element: Element, config: Config.IUILayoutTabbreak;} else if (target.classList.contains("b3-list-item")) {if (target.getAttribute("data-type") === "search-new") {- newFileByName(app, searchInputElement.value);+ newFile(app, searchInputElement.value);} else if (target.getAttribute("data-type") === "search-item") {const id = target.getAttribute("data-node-id");if (id) {@@ -830,7 +830,7 @@ export const popSearch = (app: App, searchConfig?: Config.IUILayoutTabSearchConf</div>`,bindEvent(element) {document.querySelector("#toolbarSearchNew").addEventListener("click", () => {- newFileByName(app, (document.querySelector("#toolbarSearch") as HTMLInputElement).value);+ newFile(app, (document.querySelector("#toolbarSearch") as HTMLInputElement).value);});const historyElement = document.querySelector('.toolbar [data-type="history"]');historyElement.addEventListener("click", () => {diff --git a/app/src/mobile/util/setEmpty.ts b/app/src/mobile/util/setEmpty.tsindex 84fdab03c5..2909912c99 100644--- a/app/src/mobile/util/setEmpty.ts+++ b/app/src/mobile/util/setEmpty.ts@@ -53,10 +53,7 @@ export const setEmpty = (app: App) => {event.preventDefault();break;} else if (target.id === "emptyNewFile") {- newFile({- app,- useSavePath: true- });+ newFile(app);event.stopPropagation();event.preventDefault();break;diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.tsindex 79a5d0b7ff..195a561825 100644--- a/app/src/protyle/hint/index.ts+++ b/app/src/protyle/hint/index.ts@@ -15,7 +15,7 @@ import {getSelectionPosition,} from "../util/selection";import {genHintItemHTML, hintEmbed, hintRef, hintSlash} from "./extend";-import {getSavePath, newFile} from "../../util/newFile";+import {newFileByRefHint, newFileInProtyle} from "../../util/newFile";import {isAbnormalItem, upDownHint} from "../../util/upDownHint";import {setPosition} from "../../util/setPosition";import {getContenteditableElement, hasNextSibling, hasPreviousSibling} from "../wysiwyg/getBlock";@@ -479,29 +479,21 @@ ${genHintItemHTML(item)}const realFileName = fileNames.length === 1 ? fileNames[0] : fileNames[1];const newID = Lute.NewNodeID();rowElement.dataset.id = newID;- getSavePath(protyle.path, protyle.notebookId, (pathString, targetNotebookId) => {- fetchPost("/api/filetree/createDocWithMd", {- notebook: targetNotebookId,- path: pathPosix().join(pathString, realFileName),- parentID: protyle.notebookId === targetNotebookId ? protyle.block.rootID : "",- markdown: "",- id: newID,- }, () => {- transaction(protyle, [{- action: "replaceAttrViewBlock",- avID,- previousID,- nextID: newID,- isDetached: false,- }], [{- action: "replaceAttrViewBlock",- avID,- previousID: newID,- nextID: previousID,- isDetached: true,- }]);- });- });+ newFileByRefHint(protyle, realFileName, () => {+ transaction(protyle, [{+ action: "replaceAttrViewBlock",+ avID,+ previousID,+ nextID: newID,+ isDetached: false,+ }], [{+ action: "replaceAttrViewBlock",+ avID,+ previousID: newID,+ nextID: previousID,+ isDetached: true,+ }]);+ }, newID);updateAttrViewCellAnimation(cellElement, {type: "block",isDetached: false,@@ -578,24 +570,17 @@ ${genHintItemHTML(item)}if (Constants.BLOCK_HINT_KEYS.includes(this.splitChar) && value.startsWith("((newFile ") && value.endsWith(`${Lute.Caret}'))`)) {const fileNames = value.substring(11, value.length - 4).split(`"${Constants.ZWSP}'`);const realFileName = fileNames.length === 1 ? fileNames[0] : fileNames[1];- getSavePath(protyle.path, protyle.notebookId, (pathString, targetNotebookId) => {- fetchPost("/api/filetree/createDocWithMd", {- notebook: targetNotebookId,- path: pathPosix().join(pathString, realFileName),- parentID: protyle.notebookId === targetNotebookId ? protyle.block.rootID : "",- markdown: ""- }, response => {- // https://github.com/siyuan-note/siyuan/issues/10133- protyle.toolbar.range = range;- const refElement = protyle.toolbar.setInlineMark(protyle, "block-ref", "range", {- type: "id",- color: `${response.data}${Constants.ZWSP}${refIsS ? "s" : "d"}${Constants.ZWSP}${(refIsS ? fileNames[0] : realFileName).substring(0, window.siyuan.config.editor.blockRefDynamicAnchorTextMaxLen)}`- });- if (refElement[0]) {- protyle.toolbar.range.setEnd(refElement[0].lastChild, refElement[0].lastChild.textContent.length);- }- protyle.toolbar.range.collapse(false);+ newFileByRefHint(protyle, realFileName, (id) => {+ // https://github.com/siyuan-note/siyuan/issues/10133+ protyle.toolbar.range = range;+ const refElement = protyle.toolbar.setInlineMark(protyle, "block-ref", "range", {+ type: "id",+ color: `${id}${Constants.ZWSP}${refIsS ? "s" : "d"}${Constants.ZWSP}${(refIsS ? fileNames[0] : realFileName).substring(0, window.siyuan.config.editor.blockRefDynamicAnchorTextMaxLen)}`});+ if (refElement[0]) {+ protyle.toolbar.range.setEnd(refElement[0].lastChild, refElement[0].lastChild.textContent.length);+ }+ protyle.toolbar.range.collapse(false);});return;}@@ -703,14 +688,8 @@ ${genHintItemHTML(item)}return;} else if (value === Constants.ZWSP + 4) {// 新建文档- newFile({- app: protyle.app,- notebookId: protyle.notebookId,- useSavePath: true,- currentPath: protyle.path,- afterCB: (createDocId, createDocTitle) => {- insertHTML(`<span data-type="block-ref" data-id="${createDocId}" data-subtype="d">${createDocTitle}</span>`, protyle);- }+ newFileInProtyle(protyle, (createDocId, createDocTitle) => {+ insertHTML(`<span data-type="block-ref" data-id="${createDocId}" data-subtype="d">${createDocTitle}</span>`, protyle);});return;} else if (value === Constants.ZWSP + 6) {diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.tsindex 7507765a3f..cbbc8c9e47 100644--- a/app/src/protyle/wysiwyg/keydown.ts+++ b/app/src/protyle/wysiwyg/keydown.ts@@ -67,7 +67,7 @@ import {countBlockWord} from "../../layout/status";import {moveToDown, moveToUp} from "./move";import {beforePaste, pasteAsPlainText} from "../util/paste";import {preventScroll} from "../scroll/preventScroll";-import {getSavePath, newFileBySelect} from "../../util/newFile";+import {getRefCreateSavePath, newFileBySelect} from "../../util/newFile";import {removeSearchMark} from "../toolbar/util";import {avKeydown} from "../render/av/keydown";import {checkFold} from "../../util/noRelyPCFunction";@@ -1252,8 +1252,8 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {newFileBySelect(protyle, selectText, nodeElement, response.data, protyle.notebookId);});} else {- getSavePath(protyle.path, protyle.notebookId, (pathString, targetNotebookId) => {- newFileBySelect(protyle, selectText, nodeElement, pathString, targetNotebookId);+ getRefCreateSavePath(protyle.notebookId, protyle.path, (targetNotebookId, hPath) => {+ newFileBySelect(protyle, selectText, nodeElement, hPath, targetNotebookId);});}}diff --git a/app/src/search/util.ts b/app/src/search/util.tsindex e17e1765cb..79ca026074 100644--- a/app/src/search/util.ts+++ b/app/src/search/util.ts@@ -17,7 +17,7 @@ import {getIconByType} from "../editor/getIcon";import {unicode2Emoji} from "../emoji";import {hasClosestBlock, hasClosestByClassName, hasClosestByTag} from "../protyle/util/hasClosest";import {isIPad, isNotCtrl, setStorageVal, updateHotkeyTip} from "../protyle/util/compatibility";-import {newFileByName} from "../util/newFile";+import {newFile} from "../util/newFile";import {filterMenu,getKeyByLiElement,@@ -799,7 +799,7 @@ export const genSearch = (app: App, config: Config.IUILayoutTabSearchConfig, eleconst searchAssetInputElement = element.querySelector("#searchAssetInput") as HTMLInputElement;if (type === "search-new") {if (config.method == 0) {- newFileByName(app, searchInputElement.value);+ newFile(app, searchInputElement.value);}} else if (type === "search-item") {const searchType = target.dataset.id ? "asset" : (unRefPanelElement.classList.contains("fn__none") ? "doc" : "unRef");diff --git a/app/src/util/mergePathSegments.ts b/app/src/util/mergePathSegments.tsnew file mode 100644index 0000000000..8a91e6b413--- /dev/null+++ b/app/src/util/mergePathSegments.ts@@ -0,0 +1,16 @@+/**+ * 将相对路径段合并进已有段数组:`..` 向上一级(已在根时不再上移),`.` 与空段忽略。+ * 会就地修改 `pathSegments` 并返回同一数组。+ */+export const mergePathSegments = (pathSegments: string[], segments: string[]): string[] => {+ for (const segment of segments) {+ if (segment === "..") {+ if (pathSegments.length > 0) {+ pathSegments.pop();+ }+ } else if (segment && segment !== ".") {+ pathSegments.push(segment);+ }+ }+ return pathSegments;+};diff --git a/app/src/util/newFile.ts b/app/src/util/newFile.tsindex b85fc19afe..f92ed5a6ed 100644--- a/app/src/util/newFile.ts+++ b/app/src/util/newFile.ts@@ -1,10 +1,10 @@import {showMessage} from "../dialog/message";-import {getAllModels} from "../layout/getAll";-import {hasClosestByClassName, hasTopClosestByTag} from "../protyle/util/hasClosest";-import {getDockByType} from "../layout/tabUtil";+import {hasTopClosestByTag} from "../protyle/util/hasClosest";/// #if !MOBILEimport {Files} from "../layout/dock/Files";+import {Editor} from "../editor";import {openFileById} from "../editor/util";+import {getActiveTab, getDockByType} from "../layout/tabUtil";/// #endifimport {fetchPost} from "./fetch";import {getDisplayName, getOpenNotebookCount, pathPosix} from "./pathName";@@ -13,235 +13,64 @@ import {replaceFileName, validateName} from "../editor/rename";import {hideElements} from "../protyle/ui/hideElements";import {openMobileFileById} from "../mobile/editor";import {App} from "../index";+import {NewDocTargetByHPath, NewDocTargetSubDoc, getNewDocTargetFromSavePath, getNewDocTargetFromTree} from "./parseNewDocTarget";-export const getNewFilePath = (useSavePath: boolean) => {- let notebookId = "";- let currentPath = "";- /// #if !MOBILE- getAllModels().editor.find((item) => {- const currentElement = item.parent.headElement;- if (currentElement.classList.contains("item--focus")) {- notebookId = item.editor.protyle.notebookId;- if (useSavePath) {- currentPath = item.editor.protyle.path;- } else {- currentPath = pathPosix().dirname(item.editor.protyle.path);- }- if (hasClosestByClassName(currentElement, "layout__wnd--active")) {- return true;- }- }- });- if (!notebookId) {- const fileModel = getDockByType("file").data.file;- if (fileModel instanceof Files) {- const currentElement = fileModel.element.querySelector(".b3-list-item--focus");- if (currentElement) {- const topElement = hasTopClosestByTag(currentElement, "UL");- if (topElement) {- notebookId = topElement.getAttribute("data-url");- }- const selectPath = currentElement.getAttribute("data-path");- if (useSavePath) {- currentPath = selectPath;- } else {- currentPath = pathPosix().dirname(selectPath);- }- }- }- }- /// #else- if (window.siyuan.mobile.editor && document.getElementById("empty").classList.contains("fn__none")) {- notebookId = window.siyuan.mobile.editor.protyle.notebookId;- if (useSavePath) {- currentPath = window.siyuan.mobile.editor.protyle.path;- } else {- currentPath = pathPosix().dirname(window.siyuan.mobile.editor.protyle.path);- }- }- /// #endif- if (!notebookId) {- window.siyuan.notebooks.find(item => {- if (!item.closed) {- notebookId = item.id;- currentPath = "/";- return true;- }- });- }- return {notebookId, currentPath};+type NewDocRequest = {+ app: App;+ notebookId: string;+ currentPath: string;+ /** 是否有来自编辑器或文件树选中项的焦点目标 */+ hasFocusTarget: boolean;+ name?: string;+ paths?: string[];+ listDocTree?: boolean;+ onCreated?: (id: string, title: string) => void;};-export const newFile = (optios: {- app: App,- notebookId?: string,- currentPath?: string,- paths?: string[],- useSavePath: boolean,- name?: string,- afterCB?: (id: string, title: string) => void- listDocTree?: boolean-}) => {+/** 按配置路径创建文档;从聚焦编辑器或文件树推断上下文;可选 name 指定文档名 */+export const newFile = (app: App, name?: string) => {if (getOpenNotebookCount() === 0) {showMessage(window.siyuan.languages.newFileTip);return;}- if (!optios.notebookId) {- const resultData = getNewFilePath(optios.useSavePath);- optios.notebookId = resultData.notebookId;- optios.currentPath = resultData.currentPath;+ const {notebookId, currentPath, hasFocusTarget} = getNewFilePath();+ if (name === undefined) {+ runNewDoc({+ app,+ notebookId,+ currentPath,+ hasFocusTarget,+ });+ } else {+ runNewDoc({+ app,+ notebookId,+ currentPath,+ hasFocusTarget,+ name: replaceFileName(name.trim()),+ onCreated: () => hideElements(["dialog"]),+ });}- fetchPost("/api/filetree/getDocCreateSavePath", {notebook: optios.notebookId}, (data) => {- if (!optios.useSavePath) {- data.data.box = optios.notebookId;- }- const docName = optios.name || window.siyuan.languages._kernel[16];- const titleEmpty = !optios.name;- if ((data.data.path.indexOf("/") > -1 && optios.useSavePath) || optios.name) {- if (data.data.path.startsWith("/") || optios.currentPath === "/") {- const createPath = pathPosix().join(data.data.path, docName);- fetchPost("/api/filetree/createDocWithMd", {- notebook: data.data.box,- path: createPath,- // 根目录时无法确定 parentID- markdown: "",- titleEmpty,- listDocTree: optios.listDocTree- }, response => {- if (optios.afterCB) {- optios.afterCB(response.data, pathPosix().basename(createPath));- }- /// #if !MOBILE- openFileById({- app: optios.app,- id: response.data,- action: [Constants.CB_GET_CONTEXT, Constants.CB_GET_OPENNEW]- });- /// #else- openMobileFileById(optios.app, response.data, [Constants.CB_GET_CONTEXT, Constants.CB_GET_OPENNEW]);- /// #endif- });- } else {- fetchPost("/api/filetree/getHPathByPath", {- notebook: data.data.box,- path: optios.notebookId === data.data.box ? (optios.currentPath.endsWith(".sy") ? optios.currentPath : optios.currentPath + ".sy") : (data.data.path || "/")- }, (responseHPath) => {- const createPath = pathPosix().join(responseHPath.data, data.data.path, docName);- fetchPost("/api/filetree/createDocWithMd", {- notebook: data.data.box,- path: createPath,- parentID: getDisplayName(optios.currentPath, true, true),- markdown: "",- titleEmpty,- listDocTree: optios.listDocTree- }, response => {- if (optios.afterCB) {- optios.afterCB(response.data, pathPosix().basename(createPath));- }- /// #if !MOBILE- openFileById({- app: optios.app,- id: response.data,- action: [Constants.CB_GET_CONTEXT, Constants.CB_GET_OPENNEW]- });- /// #else- openMobileFileById(optios.app, response.data, [Constants.CB_GET_CONTEXT, Constants.CB_GET_OPENNEW]);- /// #endif- });- });- }- } else {- const title = pathPosix().basename(data.data.path);- if (!validateName(title)) {- return;- }- if (optios.notebookId !== data.data.box) {- const createPath = pathPosix().join(data.data.path || "/", docName);- fetchPost("/api/filetree/createDocWithMd", {- notebook: data.data.box,- path: createPath,- markdown: "",- titleEmpty,- listDocTree: optios.listDocTree- }, response => {- if (optios.afterCB) {- optios.afterCB(response.data, pathPosix().basename(createPath));- }- /// #if !MOBILE- openFileById({- app: optios.app,- id: response.data,- action: [Constants.CB_GET_CONTEXT, Constants.CB_GET_OPENNEW]- });- /// #else- openMobileFileById(optios.app, response.data, [Constants.CB_GET_CONTEXT, Constants.CB_GET_OPENNEW]);- /// #endif- });- return;- }-- const id = Lute.NewNodeID();- const newPath = (pathPosix().join(getDisplayName(optios.currentPath, false, true), id + ".sy"));- if (optios.paths) {- optios.paths[optios.paths.indexOf(undefined)] = newPath;- }- fetchPost("/api/filetree/createDoc", {- notebook: data.data.box,- path: newPath,- title,- md: "",- sorts: optios.paths,- listDocTree: optios.listDocTree- }, () => {- if (optios.afterCB) {- optios.afterCB(id, title);- }- /// #if !MOBILE- openFileById({app: optios.app, id, action: [Constants.CB_GET_CONTEXT, Constants.CB_GET_OPENNEW]});- /// #else- openMobileFileById(optios.app, id, [Constants.CB_GET_CONTEXT, Constants.CB_GET_OPENNEW]);- /// #endif- });- }- });};-export const getSavePath = (pathString: string, notebookId: string, cb: (p: string, notebookId: string) => void) => {- fetchPost("/api/filetree/getRefCreateSavePath", {- notebook: notebookId- }, (data) => {- let targetPath = pathString;- if (notebookId !== data.data.box) {- targetPath = data.data.path || "/";- }- if (data.data.path) {- if (data.data.path.startsWith("/")) {- cb(getDisplayName(data.data.path, false, true), data.data.box);- } else {- fetchPost("/api/filetree/getHPathByPath", {- notebook: data.data.box,- path: targetPath- }, (response) => {- cb(getDisplayName(pathPosix().join(response.data, data.data.path), false, true), data.data.box);- });- }- } else {- fetchPost("/api/filetree/getHPathByPath", {- notebook: data.data.box,- path: targetPath- }, (response) => {- cb(getDisplayName(response.data, false, true), data.data.box);- });- }+export const newFileInProtyle = (protyle: IProtyle, onCreated: (id: string, title: string) => void) => {+ runNewDoc({+ app: protyle.app,+ notebookId: protyle.notebookId,+ currentPath: protyle.path,+ hasFocusTarget: true,+ onCreated,});};-export const newFileByName = (app: App, value: string) => {- hideElements(["dialog"]);- newFile({+export const newFileInTree = (app: App, notebookId: string, currentPath: string, paths?: string[]) => {+ runNewDocInTree({app,- useSavePath: true,- name: replaceFileName(value.trim())+ notebookId,+ currentPath,+ hasFocusTarget: true,+ paths,+ listDocTree: true,});};@@ -281,3 +110,258 @@ export const newFileBySelect = (protyle: IProtyle, selectText: string, nodeElemehideElements(["toolbar"], protyle);});};++export const getRefCreateSavePath = (notebookId: string, currentPath: string, cb: (targetNotebookId: string, hPath: string) => void) => {+ fetchPost("/api/filetree/getRefCreateSavePath", {+ notebook: notebookId+ }, (data) => {+ let targetPath = currentPath;+ if (notebookId !== data.data.box) {+ targetPath = data.data.path || "/";+ }+ if (data.data.path) {+ if (data.data.path.startsWith("/")) {+ cb(data.data.box, getDisplayName(data.data.path, false, true));+ } else {+ fetchPost("/api/filetree/getHPathByPath", {+ notebook: data.data.box,+ path: targetPath+ }, (response) => {+ cb(data.data.box, getDisplayName(pathPosix().join(response.data, data.data.path), false, true));+ });+ }+ } else {+ fetchPost("/api/filetree/getHPathByPath", {+ notebook: data.data.box,+ path: targetPath+ }, (response) => {+ cb(data.data.box, getDisplayName(response.data, false, true));+ });+ }+ });+};++function getNewFilePath(): Pick<NewDocRequest, "notebookId" | "currentPath" | "hasFocusTarget"> {+ let notebookId = "";+ let currentPath = "";+ let hasFocusTarget = false;+ /// #if !MOBILE+ const tab = getActiveTab(false);+ if (tab?.model instanceof Editor) {+ notebookId = tab.model.editor.protyle.notebookId;+ currentPath = tab.model.editor.protyle.path;+ hasFocusTarget = true;+ }+ if (!notebookId) {+ const fileModel = getDockByType("file").data.file;+ if (fileModel instanceof Files) {+ const currentElement = fileModel.element.querySelector(".b3-list-item--focus");+ if (currentElement) {+ const topElement = hasTopClosestByTag(currentElement, "UL");+ if (topElement) {+ notebookId = topElement.getAttribute("data-url");+ }+ currentPath = currentElement.getAttribute("data-path");+ hasFocusTarget = true;+ }+ }+ }+ /// #else+ if (window.siyuan.mobile.editor && document.getElementById("empty").classList.contains("fn__none")) {+ notebookId = window.siyuan.mobile.editor.protyle.notebookId;+ currentPath = window.siyuan.mobile.editor.protyle.path;+ hasFocusTarget = true;+ }+ /// #endif+ if (!notebookId) {+ const openNotebook = window.siyuan.notebooks.find(item => !item.closed);+ if (openNotebook) {+ notebookId = openNotebook.id;+ currentPath = "/";+ }+ }+ return {notebookId, currentPath, hasFocusTarget};+}++function runNewDoc(request: NewDocRequest) {+ fetchPost("/api/filetree/getDocCreateSavePath", {notebook: request.notebookId}, (savePathResponse) => {+ const templatePath = savePathResponse.data.path as string;+ const targetNotebookId = savePathResponse.data.box as string;+ getNewDocHPath(targetNotebookId, request.notebookId, request.currentPath, (hPath) => {+ createNewDoc(request, templatePath, targetNotebookId, hPath);+ });+ });+}++function getNewDocHPath(targetNotebookId: string, currentNotebookId: string, currentPath: string, callback: (hPath: string) => void) {+ if (targetNotebookId !== currentNotebookId) {+ // 跨笔记本时当前文档路径在目标笔记本中不存在,直接按目标笔记本根路径解析+ callback("/");+ return;+ }+ fetchPost("/api/filetree/getHPathByPath", {+ notebook: targetNotebookId,+ path: currentPath,+ }, (hPathResponse) => {+ callback(hPathResponse.data);+ });+}++function createNewDoc(request: NewDocRequest, templatePath: string, targetNotebookId: string, hPath: string) {+ const target = getNewDocTargetFromSavePath({+ templatePath,+ hPath: hPath || "/",+ targetNotebookId,+ currentNotebookId: request.notebookId,+ name: request.name,+ hasFocusTarget: request.hasFocusTarget,+ currentPath: request.currentPath,+ });+ if (target.kind === "hPath") {+ createNewDocByHPath(request, target);+ } else if (target.kind === "subDoc") {+ createNewDocAsSubDoc(request, target);+ }+}++function runNewDocInTree(request: NewDocRequest) {+ fetchPost("/api/filetree/getDocCreateSavePath", {notebook: request.notebookId}, (savePathResponse) => {+ const target = getNewDocTargetFromTree({+ templatePath: savePathResponse.data.path as string,+ currentNotebookId: request.notebookId,+ currentPath: request.currentPath,+ name: request.name,+ });+ createNewDocAsSubDoc(request, target);+ });+}++/** 同笔记本 + 有聚焦 + 非根路径 时取当前文档 ID */+function getCreateDocParentID(hasFocusTarget: boolean, notebookId: string, currentPath: string, targetNotebookId: string): string | undefined {+ return hasFocusTarget && notebookId === targetNotebookId && currentPath !== "/"+ ? getDisplayName(currentPath, true, true)+ : undefined;+}++function createNewDocByHPath(request: NewDocRequest, target: NewDocTargetByHPath) {+ if (target.title && !validateName(target.title)) {+ return;+ }+ const parentID = getCreateDocParentID(request.hasFocusTarget, request.notebookId, request.currentPath, target.targetNotebookId);+ fetchPost("/api/filetree/createDocWithMd", {+ notebook: target.targetNotebookId,+ path: target.hPath,+ parentID,+ markdown: "",+ titleEmpty: !target.title,+ }, (response) => {+ openCreatedDoc(request.app, response.data, request.onCreated, target.title);+ });+}++function createNewDocAsSubDoc(request: NewDocRequest, target: NewDocTargetSubDoc) {+ const id = Lute.NewNodeID();+ const newPath = pathPosix().join(getDisplayName(target.parentPath, false, true), id + ".sy");+ if (request.paths) {+ request.paths[request.paths.indexOf(undefined)] = newPath;+ }+ fetchPost("/api/filetree/createDoc", {+ notebook: target.targetNotebookId,+ path: newPath,+ title: target.title,+ md: "",+ sorts: request.paths,+ listDocTree: request.listDocTree,+ }, () => {+ openCreatedDoc(request.app, id, request.onCreated, target.title);+ });+}++function openCreatedDoc(app: App, id: string, onCreated?: (id: string, title: string) => void, title?: string) {+ if (onCreated) {+ onCreated(id, title || "");+ }+ /// #if !MOBILE+ openFileById({+ app,+ id,+ action: [Constants.CB_GET_CONTEXT, Constants.CB_GET_OPENNEW]+ });+ /// #else+ openMobileFileById(app, id, [Constants.CB_GET_CONTEXT, Constants.CB_GET_OPENNEW]);+ /// #endif+}++/**+ * 块引新建文档。+ *+ * 与 `newFile` 入口路径解析规则对齐;创建后仅回调插入引用,不打开新文档页签。+ * 独立于 `runNewDoc` 编排,避免给通用入口引入块引专用参数。+ */+export const newFileByRefHint = (+ protyle: IProtyle,+ name: string,+ onCreated?: (id: string, title: string) => void,+ presetId?: string,+) => {+ const requestName = replaceFileName(name.trim());+ fetchPost("/api/filetree/getRefCreateSavePath", {notebook: protyle.notebookId}, (savePathResponse) => {+ const templatePath = savePathResponse.data.path as string;+ const targetNotebookId = savePathResponse.data.box as string;+ getNewDocHPath(targetNotebookId, protyle.notebookId, protyle.path, (hPath) => {+ const target = getNewDocTargetFromSavePath({+ templatePath,+ hPath: hPath || "/",+ targetNotebookId,+ currentNotebookId: protyle.notebookId,+ name: requestName,+ hasFocusTarget: true,+ currentPath: protyle.path,+ });+ if (target.kind === "hPath") {+ createRefDocByHPath(protyle, target, onCreated, presetId);+ } else {+ createRefDocAsSubDoc(target, onCreated, presetId);+ }+ });+ });+};++function createRefDocByHPath(+ protyle: IProtyle,+ target: NewDocTargetByHPath,+ onCreated?: (id: string, title: string) => void,+ presetId?: string,+) {+ if (target.title && !validateName(target.title)) {+ return;+ }+ const parentID = getCreateDocParentID(true, protyle.notebookId, protyle.path, target.targetNotebookId);+ fetchPost("/api/filetree/createDocWithMd", {+ notebook: target.targetNotebookId,+ path: target.hPath,+ parentID,+ markdown: "",+ titleEmpty: !target.title,+ id: presetId,+ }, (response) => {+ onCreated?.(response.data, target.title || "");+ });+}++function createRefDocAsSubDoc(+ target: NewDocTargetSubDoc,+ onCreated?: (id: string, title: string) => void,+ presetId?: string,+) {+ const id = presetId || Lute.NewNodeID();+ const newPath = pathPosix().join(getDisplayName(target.parentPath, false, true), id + ".sy");+ fetchPost("/api/filetree/createDoc", {+ notebook: target.targetNotebookId,+ path: newPath,+ title: target.title,+ md: "",+ }, () => {+ onCreated?.(id, target.title || "");+ });+}diff --git a/app/src/util/parseNewDocTarget.test.ts b/app/src/util/parseNewDocTarget.test.tsnew file mode 100644index 0000000000..169ffe4d37--- /dev/null+++ b/app/src/util/parseNewDocTarget.test.ts@@ -0,0 +1,399 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {getNewDocTargetFromSavePath, getNewDocTargetFromTree, NewDocTarget} from "./parseNewDocTarget";++const assertSubDoc = (target: NewDocTarget, expected: {+ targetNotebookId?: string;+ parentPath: string;+ title: string;+}) => {+ assert.equal(target.kind, "subDoc");+ if (target.kind === "subDoc") {+ if (expected.targetNotebookId !== undefined) {+ assert.equal(target.targetNotebookId, expected.targetNotebookId);+ }+ assert.equal(target.parentPath, expected.parentPath);+ assert.equal(target.title, expected.title);+ }+};++const assertHPath = (target: NewDocTarget, expected: {+ targetNotebookId?: string;+ hPath: string;+ title: string;+}) => {+ assert.equal(target.kind, "hPath");+ if (target.kind === "hPath") {+ if (expected.targetNotebookId !== undefined) {+ assert.equal(target.targetNotebookId, expected.targetNotebookId);+ }+ assert.equal(target.hPath, expected.hPath);+ assert.equal(target.title, expected.title);+ }+};++describe("getNewDocTargetFromSavePath", () => {+ // 聚焦嵌套文档:内核路径与人类路径成对出现+ const nestedDocPath = "/20260628041644-ndcuikw/20260628040939-kkaajwr.sy";+ const nestedHPath = "/parent1/parent2/docName";+ // 聚焦根级文档+ const rootDocPath = "/20260628041702-kqfrg7p.sy";+ const rootHPath = "/docName";+ const notebookId = "nb";++ const nestedContext = {+ hPath: nestedHPath,+ targetNotebookId: notebookId,+ currentNotebookId: notebookId,+ hasFocusTarget: true,+ currentPath: nestedDocPath,+ };++ describe("空模板", () => {+ it("有页签/选中 + 无 name → 当前文档下子文档", () => {+ const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: ""});+ assertSubDoc(target, {targetNotebookId: notebookId, parentPath: nestedDocPath, title: ""});+ });++ it("有页签/选中 + 显式标题 → 当前 hPath 下按名称新建", () => {+ const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "", name: "docName2"});+ assertHPath(target, {hPath: "/parent1/parent2/docName/docName2", title: "docName2"});+ });++ it("聚焦根级文档 + 无 name → 子文档", () => {+ const target = getNewDocTargetFromSavePath({+ ...nestedContext,+ templatePath: "",+ hPath: rootHPath,+ currentPath: rootDocPath,+ });+ assertSubDoc(target, {parentPath: rootDocPath, title: ""});+ });++ it("聚焦根级文档 + 显式标题 → 当前 hPath 下按名称新建", () => {+ const target = getNewDocTargetFromSavePath({+ ...nestedContext,+ templatePath: "",+ hPath: rootHPath,+ currentPath: rootDocPath,+ name: "docName2",+ });+ assertHPath(target, {hPath: "/docName/docName2", title: "docName2"});+ });++ it("选中笔记本根(currentPath=/)+ 无 name → 子文档", () => {+ const target = getNewDocTargetFromSavePath({+ ...nestedContext,+ templatePath: "",+ hPath: "/",+ currentPath: "/",+ });+ assertSubDoc(target, {parentPath: "/", title: ""});+ });++ it("无页签无选中 → 笔记本根", () => {+ const target = getNewDocTargetFromSavePath({+ ...nestedContext,+ templatePath: "",+ hasFocusTarget: false,+ hPath: "/",+ currentPath: "/",+ });+ assertHPath(target, {hPath: "/", title: ""});+ });++ it("无页签无选中 + 显式标题 → 笔记本根下按名称新建", () => {+ const target = getNewDocTargetFromSavePath({+ ...nestedContext,+ templatePath: "",+ hasFocusTarget: false,+ hPath: "/",+ name: "docName2",+ });+ assertHPath(target, {hPath: "/docName2", title: "docName2"});+ });+ });++ describe("容器路径(尾 /)", () => {+ it("绝对 /parent3/", () => {+ const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "/parent3/"});+ assertHPath(target, {hPath: "/parent3/", title: ""});+ });++ it("绝对 /parent3/ + 显式标题", () => {+ const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "/parent3/", name: "docName2"});+ assertHPath(target, {hPath: "/parent3/docName2", title: "docName2"});+ });++ it("绝对 /", () => {+ const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "/", hPath: "/"});+ assertHPath(target, {hPath: "/", title: ""});+ });++ it("绝对 /parent1/parent2/", () => {+ const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "/parent1/parent2/"});+ assertHPath(target, {hPath: "/parent1/parent2/", title: ""});+ });++ it("相对 parent3/", () => {+ const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "parent3/"});+ assertHPath(target, {hPath: "/parent1/parent2/docName/parent3/", title: ""});+ });++ it("相对 parent3/parent4/", () => {+ const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "parent3/parent4/"});+ assertHPath(target, {hPath: "/parent1/parent2/docName/parent3/parent4/", title: ""});+ });++ it("相对 ../", () => {+ const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "../"});+ assertHPath(target, {hPath: "/parent1/parent2/", title: ""});+ });++ it("相对 ../ + 显式标题", () => {+ const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "../", name: "docName2"});+ assertHPath(target, {hPath: "/parent1/parent2/docName2", title: "docName2"});+ });++ it("相对 ../../", () => {+ const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "../../"});+ assertHPath(target, {hPath: "/parent1/", title: ""});+ });++ it("相对 ../parent3/", () => {+ const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "../parent3/"});+ assertHPath(target, {hPath: "/parent1/parent2/parent3/", title: ""});+ });++ it("相对 ../../parent3/parent4/", () => {+ const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "../../parent3/parent4/"});+ assertHPath(target, {hPath: "/parent1/parent3/parent4/", title: ""});+ });++ it("已在根时 ../", () => {+ const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "../", hPath: "/"});+ assertHPath(target, {hPath: "/", title: ""});+ });++ it("模板首尾空白 trim", () => {+ const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: " parent3/ "});+ assertHPath(target, {hPath: "/parent1/parent2/docName/parent3/", title: ""});+ });+ });++ describe("文档名路径", () => {+ it("相对 docName2", () => {+ const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "docName2"});+ assertHPath(target, {hPath: "/parent1/parent2/docName/docName2", title: "docName2"});+ });++ it("相对 docName2 + 显式标题替换末段", () => {+ const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "docName2", name: "docName3"});+ assertHPath(target, {hPath: "/parent1/parent2/docName/docName3", title: "docName3"});+ });++ it("模板首尾空白 trim", () => {+ const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: " docName2 "});+ assertHPath(target, {hPath: "/parent1/parent2/docName/docName2", title: "docName2"});+ });++ it("绝对 /docName2", () => {+ const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "/docName2"});+ assertHPath(target, {hPath: "/docName2", title: "docName2"});+ });++ it("绝对 /docName2 + 显式标题替换末段", () => {+ const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "/docName2", name: "docName3"});+ assertHPath(target, {hPath: "/docName3", title: "docName3"});+ });++ it("相对 parent3/docName2", () => {+ const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "parent3/docName2"});+ assertHPath(target, {hPath: "/parent1/parent2/docName/parent3/docName2", title: "docName2"});+ });++ it("绝对 /parent3/docName2", () => {+ const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "/parent3/docName2"});+ assertHPath(target, {hPath: "/parent3/docName2", title: "docName2"});+ });++ it("相对 ../docName2", () => {+ const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "../docName2"});+ assertHPath(target, {hPath: "/parent1/parent2/docName2", title: "docName2"});+ });++ it("相对 ../../docName2", () => {+ const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "../../docName2"});+ assertHPath(target, {hPath: "/parent1/docName2", title: "docName2"});+ });++ it("相对 ../parent3/docName2", () => {+ const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "../parent3/docName2"});+ assertHPath(target, {hPath: "/parent1/parent2/parent3/docName2", title: "docName2"});+ });++ it("已在根时 ../docName2(.. 在根无效)", () => {+ const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "../docName2", hPath: "/"});+ assertHPath(target, {hPath: "/docName2", title: "docName2"});+ });+ });++ describe("跨笔记本", () => {+ const crossNotebook = {+ ...nestedContext,+ targetNotebookId: "box-b",+ currentNotebookId: "box-a",+ hPath: "/",+ currentPath: nestedDocPath,+ };++ it("相对 docName2 → 补 / 后按目标笔记本根解析", () => {+ const target = getNewDocTargetFromSavePath({...crossNotebook, templatePath: "docName2"});+ assertHPath(target, {targetNotebookId: "box-b", hPath: "/docName2", title: "docName2"});+ });++ it("相对 parent3/parent4/ → 补 / 后按目标笔记本根解析", () => {+ const target = getNewDocTargetFromSavePath({...crossNotebook, templatePath: "parent3/parent4/"});+ assertHPath(target, {targetNotebookId: "box-b", hPath: "/parent3/parent4/", title: ""});+ });++ it("相对 ../docName2 → 补 / 后 .. 在根无效", () => {+ const target = getNewDocTargetFromSavePath({...crossNotebook, templatePath: "../docName2"});+ assertHPath(target, {targetNotebookId: "box-b", hPath: "/docName2", title: "docName2"});+ });++ it("绝对 /parent3/docName2 不受影响", () => {+ const target = getNewDocTargetFromSavePath({...crossNotebook, templatePath: "/parent3/docName2"});+ assertHPath(target, {targetNotebookId: "box-b", hPath: "/parent3/docName2", title: "docName2"});+ });++ it("空模板 + 无页签无选中 + 显式标题 → 目标笔记本根下按名称新建", () => {+ const target = getNewDocTargetFromSavePath({+ ...crossNotebook,+ templatePath: "",+ hasFocusTarget: false,+ name: "docName2",+ });+ assertHPath(target, {targetNotebookId: "box-b", hPath: "/docName2", title: "docName2"});+ });++ it("空模板 + 有聚焦 + 无 name → 回退到目标笔记本根空标题文档", () => {+ const target = getNewDocTargetFromSavePath({...crossNotebook, templatePath: ""});+ assertHPath(target, {targetNotebookId: "box-b", hPath: "/", title: ""});+ });++ it("空模板 + 有聚焦 + 显式标题 → 目标笔记本根下按名称新建(跨笔记本 hPath 基点为 /)", () => {+ const target = getNewDocTargetFromSavePath({...crossNotebook, templatePath: "", name: "docName2"});+ assertHPath(target, {targetNotebookId: "box-b", hPath: "/docName2", title: "docName2"});+ });+ });+});++describe("getNewDocTargetFromTree", () => {+ const notebookId = "nb";+ // 文档树 data-path:带 .sy 的内核路径+ const parentDocPath = "/20260628041644-ndcuikw.sy";+ const nestedDocPath = "/20260628041644-ndcuikw/20260628040939-kkaajwr.sy";+ // pathPosix().dirname():同级插入时传入的父目录(无 .sy、无尾斜杠)+ const parentDirPath = "/20260628041644-ndcuikw";+ const rootPath = "/";++ describe("文档树 + 新建子文档(currentPath 为 data-path)", () => {+ const treeContext = {currentNotebookId: notebookId, currentPath: parentDocPath};++ it("空模板", () => {+ const target = getNewDocTargetFromTree({...treeContext, templatePath: ""});+ assertSubDoc(target, {targetNotebookId: notebookId, parentPath: parentDocPath, title: ""});+ });++ it("空模板 + 显式标题", () => {+ const target = getNewDocTargetFromTree({...treeContext, templatePath: "", name: "docName2"});+ assertSubDoc(target, {parentPath: parentDocPath, title: "docName2"});+ });++ it("单段模板 docName2", () => {+ const target = getNewDocTargetFromTree({...treeContext, templatePath: "docName2"});+ assertSubDoc(target, {parentPath: parentDocPath, title: "docName2"});+ });++ it("单段模板 docName2 + 显式标题", () => {+ const target = getNewDocTargetFromTree({...treeContext, templatePath: "docName2", name: "docName3"});+ assertSubDoc(target, {parentPath: parentDocPath, title: "docName3"});+ });++ it("多段模板 parent3/docName2(仅取末段为标题,父路径不变)", () => {+ const target = getNewDocTargetFromTree({...treeContext, templatePath: "parent3/docName2"});+ assertSubDoc(target, {parentPath: parentDocPath, title: "docName2"});+ });++ it("绝对模板 /docName2(落点仍为 currentPath,仅影响标题)", () => {+ const target = getNewDocTargetFromTree({...treeContext, templatePath: "/docName2"});+ assertSubDoc(target, {parentPath: parentDocPath, title: "docName2"});+ });++ it("容器模板 docName2/(树入口不解析容器链,无 name 时空标题)", () => {+ const target = getNewDocTargetFromTree({...treeContext, templatePath: "docName2/"});+ assertSubDoc(target, {parentPath: parentDocPath, title: ""});+ });++ it("容器模板 docName2/ + 显式标题", () => {+ const target = getNewDocTargetFromTree({...treeContext, templatePath: "docName2/", name: "docName2"});+ assertSubDoc(target, {parentPath: parentDocPath, title: "docName2"});+ });++ it("模板首尾空白 trim", () => {+ const target = getNewDocTargetFromTree({...treeContext, templatePath: " docName2 "});+ assertSubDoc(target, {parentPath: parentDocPath, title: "docName2"});+ });++ it("嵌套文档下新建子文档", () => {+ const target = getNewDocTargetFromTree({+ currentNotebookId: notebookId,+ currentPath: nestedDocPath,+ templatePath: "docName2",+ });+ assertSubDoc(target, {parentPath: nestedDocPath, title: "docName2"});+ });+ });++ describe("同级插入(currentPath 为 dirname,无 .sy)", () => {+ it("嵌套文档的同级插入", () => {+ const target = getNewDocTargetFromTree({+ currentNotebookId: notebookId,+ currentPath: parentDirPath,+ templatePath: "docName2",+ });+ assertSubDoc(target, {parentPath: parentDirPath, title: "docName2"});+ });++ it("根级文档的同级插入(dirname 为 /)", () => {+ const target = getNewDocTargetFromTree({+ currentNotebookId: notebookId,+ currentPath: rootPath,+ templatePath: "",+ });+ assertSubDoc(target, {parentPath: rootPath, title: ""});+ });+ });++ describe("笔记本根(currentPath 为 /)", () => {+ it("空模板", () => {+ const target = getNewDocTargetFromTree({+ currentNotebookId: notebookId,+ currentPath: rootPath,+ templatePath: "",+ });+ assertSubDoc(target, {parentPath: rootPath, title: ""});+ });++ it("单段模板 + 显式标题", () => {+ const target = getNewDocTargetFromTree({+ currentNotebookId: notebookId,+ currentPath: rootPath,+ templatePath: "docName2",+ name: "docName3",+ });+ assertSubDoc(target, {parentPath: rootPath, title: "docName3"});+ });+ });+});diff --git a/app/src/util/parseNewDocTarget.ts b/app/src/util/parseNewDocTarget.tsnew file mode 100644index 0000000000..29a215ce1b--- /dev/null+++ b/app/src/util/parseNewDocTarget.ts@@ -0,0 +1,140 @@+/**+ * 新建文档路径解析。输入为内核渲染后的路径模板。+ *+ * 调用方先采集 `path`,再转为 `hPath` 传入;跨笔记本时 `hPath` 固定为 `/`。+ *+ * 标题优先级:`name` > 路径末段(文档名模式)> 空。`name` 替换末段,非拼接。+ *+ * 三种形态:+ * - 尾 `/` → 父文档路径:路径为父文档链,新文档建在最内层父文档内;未传 `name` 时空标题+ * - 非尾 `/` → 文档名:末段为标题,其余为父路径+ * - 空 → 同笔记本 + 有上下文则当前文档子文档;跨笔记本或无上下文则目标笔记本根路径+ *+ * `/` 开头从根解析,否则相对 `hPath`;`..` 向上一级,已在根则停在 `/`。+ * 跨笔记本时相对路径在开头补 `/`,按目标笔记本根解析;空路径也回退到目标笔记本根路径。+ */++import {mergePathSegments} from "./mergePathSegments";++/** 内核 `createDocsByHPath` 按 HPath 逐级创建 */+export type NewDocTargetByHPath = {+ kind: "hPath";+ targetNotebookId: string;+ hPath: string;+ title: string;+};++/** 在已知父路径下创建子文档 */+export type NewDocTargetSubDoc = {+ kind: "subDoc";+ targetNotebookId: string;+ parentPath: string;+ title: string;+};++export type NewDocTarget = NewDocTargetByHPath | NewDocTargetSubDoc;++/** 按保存路径配置解析新建目标 */+export const getNewDocTargetFromSavePath = (request: {+ templatePath: string;+ hPath: string;+ targetNotebookId: string;+ currentNotebookId: string;+ name?: string;+ hasFocusTarget: boolean;+ currentPath?: string;+}): NewDocTarget => {+ const {targetNotebookId} = request;++ let templatePath = request.templatePath.trim();+ let isAbsolute = templatePath.startsWith("/");+ if (targetNotebookId !== request.currentNotebookId && templatePath && !isAbsolute) {+ // 跨笔记本时相对路径无锚点,在开头补 `/` 按目标笔记本根路径解析+ templatePath = "/" + templatePath;+ isAbsolute = true;+ }++ // 空路径 + 同笔记本 + 有上下文 + 无 name:在已知父路径下建空标题子文档+ // 跨笔记本时 currentPath 属于当前笔记本,在目标笔记本中无效,落到下方 hPath 逻辑回退到目标笔记本根+ if (!templatePath && request.hasFocusTarget && !request.name+ && targetNotebookId === request.currentNotebookId) {+ return {+ kind: "subDoc",+ targetNotebookId,+ parentPath: request.currentPath || "/",+ title: "",+ };+ }++ let parentTemplate: string;+ let title = "";+ if (!templatePath) {+ // 空路径 + 有上下文 → 当前路径下;空路径 + 无上下文 → 笔记本根+ parentTemplate = request.hasFocusTarget ? "" : "/";+ title = request.name || "";+ } else if (templatePath.endsWith("/")) {+ // 尾部有 `/`:解析父文档链,在最内层父文档内新建+ parentTemplate = templatePath;+ title = request.name || "";+ } else {+ const segments = templatePath.split("/").filter(Boolean);+ if (segments.length <= 1) {+ // 文档名+ parentTemplate = isAbsolute ? "/" : "";+ } else {+ // 路径:去掉末段(文档名),余下段拼成父路径模板+ const parentSegmentPath = segments.slice(0, -1).join("/");+ parentTemplate = isAbsolute ? "/" + parentSegmentPath : parentSegmentPath;+ }+ title = request.name || segments[segments.length - 1];+ }++ // 将路径模板合并进 hPath+ const templateSegments = parentTemplate.split("/").filter(Boolean);+ let parentPathSegments: string[];+ if (parentTemplate.startsWith("/")) {+ // 绝对路径:从笔记本根起算+ parentPathSegments = mergePathSegments([], templateSegments);+ } else {+ // 相对路径:从当前 hPath 起算+ parentPathSegments = mergePathSegments(request.hPath.split("/").filter(Boolean), templateSegments);+ }++ let hPath: string;+ if (title) {+ hPath = "/" + [...parentPathSegments, title].join("/");+ } else {+ // 空标题时保留尾 `/` 使 hPath 末段为空,内核按父文档链在其内新建子文档+ hPath = parentPathSegments.length === 0 ? "/" : "/" + parentPathSegments.join("/") + "/";+ }++ return {+ kind: "hPath",+ targetNotebookId,+ hPath,+ title,+ };+};++/** 文件树指定位置:在 `currentPath` 下建子文档,标题规则同保存路径 */+export const getNewDocTargetFromTree = (request: {+ templatePath: string;+ currentNotebookId: string;+ currentPath: string;+ name?: string;+}): NewDocTargetSubDoc => {+ const templatePath = request.templatePath.trim();+ let title = "";+ if (request.name) {+ title = request.name;+ } else if (templatePath && !templatePath.endsWith("/")) {+ const segments = templatePath.split("/").filter(Boolean);+ title = segments[segments.length - 1];+ }+ return {+ kind: "subDoc",+ targetNotebookId: request.currentNotebookId,+ parentPath: request.currentPath || "/",+ title,+ };+};diff --git a/app/src/util/pathName.ts b/app/src/util/pathName.tsindex 5b6f1d9ac4..7f583766e4 100644--- a/app/src/util/pathName.ts+++ b/app/src/util/pathName.ts@@ -16,6 +16,7 @@ import {isOnlyMeta, isWindows, setStorageVal, updateHotkeyTip} from "../protyle/import {matchHotKey} from "../protyle/util/hotKey";import {Menu} from "../plugin/Menu";import {hasClosestByClassName} from "../protyle/util/hasClosest";+import {mergePathSegments} from "./mergePathSegments";export const useShell = (cmd: "showItemInFolder" | "openPath", filePath: string) => {/// #if !BROWSER@@ -777,16 +778,7 @@ export const setNoteBook = (cb?: (notebook: INotebook[]) => void, flashcard = fa* @returns 规范化后的相对路径(使用 /),若路径非法则返回替换后的合法路径*/export const normalizeStoragePath = (storageName: string): string | null => {- const parts = storageName.replace(/\\/g, "/").split("/");- const resolved: string[] = [];- for (const part of parts) {- if (part === "..") {- if (resolved.length > 0) {- resolved.pop();- }- } else if (part && part !== ".") {- resolved.push(part);- }- }- return resolved.length > 0 ? resolved.join("/") : storageName.replace(/[\/\\]+/g, "");+ const segments = storageName.replace(/\\/g, "/").split("/");+ const merged = mergePathSegments([], segments);+ return merged.length > 0 ? merged.join("/") : storageName.replace(/[\/\\]+/g, "");};diff --git a/kernel/api/notebook.go b/kernel/api/notebook.goindex 2a84904889..a196c4f852 100644--- a/kernel/api/notebook.go+++ b/kernel/api/notebook.go@@ -370,12 +370,9 @@ func setNotebookConf(c *gin.Context) {return}+ boxConf.DocCreateSavePath = util.TrimSpaceInPath(boxConf.DocCreateSavePath)+boxConf.RefCreateSavePath = util.TrimSpaceInPath(boxConf.RefCreateSavePath)- if "" != boxConf.RefCreateSavePath {- if !strings.HasSuffix(boxConf.RefCreateSavePath, "/") {- boxConf.RefCreateSavePath += "/"- }- }boxConf.DailyNoteSavePath = util.TrimSpaceInPath(boxConf.DailyNoteSavePath)if "" != boxConf.DailyNoteSavePath {@@ -399,8 +396,6 @@ func setNotebookConf(c *gin.Context) {}}- boxConf.DocCreateSavePath = util.TrimSpaceInPath(boxConf.DocCreateSavePath)-box.SaveConf(boxConf)ret.Data = boxConf}diff --git a/kernel/api/setting.go b/kernel/api/setting.goindex 71d327795e..6fcef13329 100644--- a/kernel/api/setting.go+++ b/kernel/api/setting.go@@ -476,15 +476,10 @@ func setFiletree(c *gin.Context) {return}- fileTree.RefCreateSavePath = util.TrimSpaceInPath(fileTree.RefCreateSavePath)- if "" != fileTree.RefCreateSavePath {- if !strings.HasSuffix(fileTree.RefCreateSavePath, "/") {- fileTree.RefCreateSavePath += "/"- }- }-fileTree.DocCreateSavePath = util.TrimSpaceInPath(fileTree.DocCreateSavePath)+ fileTree.RefCreateSavePath = util.TrimSpaceInPath(fileTree.RefCreateSavePath)+fileTree.ShorthandSavePath = util.TrimSpaceInPath(fileTree.ShorthandSavePath)if "" != fileTree.ShorthandSavePath {if !strings.HasPrefix(fileTree.ShorthandSavePath, "/") {