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 consistency and reuse of single-input dialogs https://github.com/siyuan-note/siyuan/issues/19420
Vanessae90437ccce54
diff --git a/app/src/ai/chat.ts b/app/src/ai/chat.tsindex 6bf9327a4a..a64557ba5b 100644--- a/app/src/ai/chat.ts+++ b/app/src/ai/chat.ts@@ -1,5 +1,4 @@-import {Dialog} from "../dialog";-import {isMobile} from "../util/functions";+import {openInputDialog} from "../dialog/inputDialog";import {clearAIEditorHistory, startAIWriting} from "./editor";import {showMessage} from "../dialog/message";import {isDisabledFeature} from "../protyle/util/compatibility";@@ -8,36 +7,22 @@ export const AIChat = (protyle: IProtyle, element: HTMLElement) => {if (isDisabledFeature("ai")) {return;}- const dialog = new Dialog({+ openInputDialog({title: "✨ " + window.siyuan.languages.aiWriting,- content: `<div class="b3-dialog__content fn__flex"><textarea class="b3-text-field fn__flex-1" style="resize:none"></textarea></div>-<div class="b3-dialog__action">- <button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button><div class="fn__space"></div>- <button class="b3-button b3-button--text">${window.siyuan.languages.confirm}</button>-</div>`,- width: isMobile() ? "92vw" : "520px",- });- const inputElement = dialog.element.querySelector("textarea");- const btnsElement = dialog.element.querySelectorAll(".b3-button");- dialog.bindInput(inputElement, () => {- (btnsElement[1] as HTMLButtonElement).click();- });- inputElement.focus();- btnsElement[0].addEventListener("click", () => {- dialog.destroy();- });- btnsElement[1].addEventListener("click", () => {- const inputValue = inputElement.value;- if (!inputValue.trim()) {- showMessage(window.siyuan.languages["_kernel"][142]);- return;- }- dialog.destroy();- if (inputValue === "Clear context") {- clearAIEditorHistory(protyle);- showMessage(window.siyuan.languages.clearContextSucc);- return;- }- startAIWriting(protyle, element, inputValue);+ value: "",+ multiline: true,+ onConfirm: (inputValue, dialog) => {+ if (!inputValue.trim()) {+ showMessage(window.siyuan.languages["_kernel"][142]);+ return;+ }+ dialog.destroy();+ if (inputValue === "Clear context") {+ clearAIEditorHistory(protyle);+ showMessage(window.siyuan.languages.clearContextSucc);+ return;+ }+ startAIWriting(protyle, element, inputValue);+ },});};diff --git a/app/src/config/tabs/accessTab.ts b/app/src/config/tabs/accessTab.tsindex 03000e33d4..3aabea4c51 100644--- a/app/src/config/tabs/accessTab.ts+++ b/app/src/config/tabs/accessTab.ts@@ -794,45 +794,35 @@ const mountEncryptedNotebook = (root: HTMLElement) => {return;}// 导入前需输入主密码校验(备份文件不含密码,校验用导入备份对应的主密码)- const passwordDialog = new Dialog({+ openInputDialog({title: window.siyuan.languages.masterPassword,- content: `<div class="b3-dialog__content">- <input type="password" placeholder="${window.siyuan.languages.masterPassword}" class="b3-text-field fn__block">-</div>-<div class="b3-dialog__action">- <button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button>- <div class="fn__space"></div>- <button class="b3-button b3-button--text">${window.siyuan.languages.confirm}</button>-</div>`,+ value: "",+ type: "password",+ placeholder: window.siyuan.languages.masterPassword,width: "520px",- });- const pwdInput = passwordDialog.element.querySelector(".b3-text-field") as HTMLInputElement;- passwordDialog.element.querySelector(".b3-button--cancel")?.addEventListener("click", () => {- passwordDialog.destroy();- });- passwordDialog.element.querySelector(".b3-button--text")?.addEventListener("click", () => {- const password = pwdInput.value.trim();- if (!password) {- showMessage(window.siyuan.languages.masterPassword);- return;- }- const formData = new FormData();- formData.append("file", file);- formData.append("password", password);- fetch("/api/notebook/importNotebookCryptoBackup", {- method: "POST",- body: formData,- }).then((res) => res.json()).then((response: IWebSocketData) => {- if (response.code === -1) {- showMessage(response.msg, 6000, "error");+ onConfirm: (value, passwordDialog) => {+ const password = value.trim();+ if (!password) {+ showMessage(window.siyuan.languages.masterPassword);return;}- showMessage(window.siyuan.languages.importNotebookCryptoBackupTip);- passwordDialog.destroy();- refresh();- });+ const formData = new FormData();+ formData.append("file", file);+ formData.append("password", password);+ fetch("/api/notebook/importNotebookCryptoBackup", {+ method: "POST",+ body: formData,+ }).then((res) => res.json()).then((response: IWebSocketData) => {+ if (response.code === -1) {+ showMessage(response.msg, 6000, "error");+ return;+ }+ showMessage(window.siyuan.languages.importNotebookCryptoBackupTip);+ passwordDialog.destroy();+ refresh();+ });+ },});- pwdInput.focus();};fileInput.click();});diff --git a/app/src/config/tabs/syncTab.ts b/app/src/config/tabs/syncTab.tsindex c53eabb0a3..856dafffda 100644--- a/app/src/config/tabs/syncTab.ts+++ b/app/src/config/tabs/syncTab.ts@@ -1,3 +1,4 @@+import {openInputDialog} from "../../dialog/inputDialog";import type {SettingTabBuilder} from "../setting/builder";import {registerAccountGroup} from "./accountUi";import {Constants} from "../../constants";@@ -7,7 +8,6 @@ import {showMessage} from "../../dialog/message";import {processSync} from "../../dialog/processSystem";import {writeText} from "../../protyle/util/compatibility";import {bindSyncCloudListEvent, renderSyncCloudList, setKey} from "../../sync/syncGuide";-import {Dialog} from "../../dialog";import {genConfigItemMainHtml, genConfigItemName} from "../render/fragments";import {getLANSyncSearchAvailability, getSyncProviderConfigKeywords} from "./syncUi";import {mountLANSyncStatus, mountSyncAssetDownloadMode, patchSyncConfig} from "./syncRuntime";@@ -224,31 +224,20 @@ const mountRepoKey = (root: HTMLElement) => {};toggleRepoKeyActions();root.querySelector("#importKey")?.addEventListener("click", () => {- const passwordDialog = new Dialog({+ const passwordDialog = openInputDialog({title: "🔑 " + window.siyuan.languages.key,- content: `<div class="b3-dialog__content">- <input type="text" spellcheck="false" class="b3-text-field fn__block" placeholder="${window.siyuan.languages.keyPlaceholder}">-</div>-<div class="b3-dialog__action">- <button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button><div class="fn__space"></div>- <button class="b3-button b3-button--text">${window.siyuan.languages.confirm}</button>-</div>`,+ value: "",+ placeholder: window.siyuan.languages.keyPlaceholder,width: "520px",+ onConfirm: (value, passwordDialog) => {+ fetchPost("/api/repo/importRepoKey", {key: value}, (response) => {+ window.siyuan.config.repo.key = response.data.key;+ toggleRepoKeyActions();+ passwordDialog.destroy();+ });+ },});passwordDialog.element.setAttribute("data-key", Constants.DIALOG_PASSWORD);- const inputElement = passwordDialog.element.querySelector("input");- inputElement.focus();- const btnsElement = passwordDialog.element.querySelectorAll(".b3-button");- btnsElement[0].addEventListener("click", () => {- passwordDialog.destroy();- });- btnsElement[1].addEventListener("click", () => {- fetchPost("/api/repo/importRepoKey", {key: inputElement.value}, (response) => {- window.siyuan.config.repo.key = response.data.key;- toggleRepoKeyActions();- passwordDialog.destroy();- });- });});root.querySelector("#initKey")?.addEventListener("click", () => {confirmDialog("🔑 " + window.siyuan.languages.genKey, window.siyuan.languages.initRepoKeyTip, () => {diff --git a/app/src/dialog/inputDialog.test.ts b/app/src/dialog/inputDialog.test.tsnew file mode 100644index 0000000000..c5a603a7d3--- /dev/null+++ b/app/src/dialog/inputDialog.test.ts@@ -0,0 +1,186 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {it} from "node:test";+import {runInNewContext} from "node:vm";+import {createSourceFile, forEachChild, isCallExpression, ModuleKind, ScriptTarget, transpileModule} from "typescript";++class Control {+ value = "";+ disabled = false;+ dataset: Record<string, string> = {};+ listeners: Record<string, () => void> = {};+ addEventListener(type: string, listener: () => void) {+ this.listeners[type] = listener;+ }+ click() {+ if (!this.disabled) {+ this.listeners.click?.();+ }+ }+ focus() {}+ select() {}+}++class Input extends Control {+ type = "text";+}++const loadDialog = () => {+ class TestDialog {+ input: Control;+ cancel = new Control();+ confirm = new Control();+ actions: Control[];+ closed = false;+ enter?: () => void;+ element: {+ querySelector: (selector: string) => Control,+ querySelectorAll: (selector: string) => Control[],+ };+ constructor(public options: {content: string}) {+ this.input = options.content.includes("<textarea") ? new Control() : new Input();+ this.actions = Array.from(options.content.matchAll(/data-input-action="(\d+)"/g), match => {+ const control = new Control();+ control.dataset.inputAction = match[1];+ return control;+ });+ this.element = {+ querySelector: selector => ({+ "[data-dialog-input]": this.input,+ "[data-input-cancel]": this.cancel,+ "[data-input-confirm]": this.confirm,+ })[selector],+ querySelectorAll: () => this.actions,+ };+ }+ bindInput(input: Control, enter: () => void) {+ assert.equal(input, this.input);+ this.enter = enter;+ }+ destroy() {+ this.closed = true;+ }+ }+ const exports = {} as {openInputDialog: (options: Record<string, unknown>) => TestDialog};+ runInNewContext(transpileModule(readFileSync("src/dialog/inputDialog.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2020},+ }).outputText, {+ exports,+ HTMLInputElement: Input,+ window: {siyuan: {languages: {confirm: "Confirm", cancel: "Cancel"}}},+ require: (name: string) => {+ if (name === "./index") {+ return {Dialog: TestDialog};+ }+ if (name === "../util/functions") {+ return {isMobile: () => false};+ }+ if (name === "../util/escape") {+ return {escapeHtml: (value: string) => value.replace(/</g, "<")};+ }+ throw new Error(name);+ },+ });+ return exports.openInputDialog;+};++it("keeps validation and closing with the caller and respects a disabled confirm button", () => {+ const open = loadDialog();+ let calls = 0;+ const dialog = open({+ title: "Password",+ value: "",+ type: "password",+ onConfirm: (value: string, current: {destroy: () => void}) => {+ calls++;+ if (value) {+ current.destroy();+ }+ },+ });+ assert.equal((dialog.input as Input).type, "password");+ dialog.enter();+ assert.equal(dialog.closed, false);+ dialog.confirm.disabled = true;+ dialog.enter();+ assert.equal(calls, 1);+ dialog.confirm.disabled = false;+ dialog.input.value = "secret";+ dialog.enter();+ assert.equal(dialog.closed, true);+});++it("uses the primary action for Enter and leaves extra content buttons independent", () => {+ const open = loadDialog();+ const calls: string[] = [];+ const dialog = open({+ title: "Template",+ value: "<name>",+ extraContent: '<button class="b3-button">Manager</button>',+ confirmText: "Update",+ actions: [{text: "Delete", position: "beforeCancel", onClick: (value: string) => calls.push("delete:" + value)},+ {text: "Rename", onClick: (value: string) => calls.push("rename:" + value)},+ {text: "Upload", position: "afterConfirm", onClick: (value: string) => calls.push("upload:" + value)}],+ onConfirm: (value: string) => calls.push("confirm:" + value),+ });+ assert.equal(dialog.input.value, "<name>");+ assert.equal(dialog.options.content.includes("<name>"), false);+ assert.deepEqual(dialog.actions.map(action => action.dataset.inputAction), ["0", "1", "2"]);+ dialog.input.value = "changed";+ dialog.enter();+ dialog.actions.forEach(action => action.click());+ assert.deepEqual(calls, ["confirm:changed", "delete:changed", "rename:changed", "upload:changed"]);+ assert.equal(dialog.closed, false);+ dialog.cancel.click();+ assert.equal(dialog.closed, true);+});++it("supports multiline values and lets autocomplete own keyboard events", () => {+ const open = loadDialog();+ const dialog = open({title: "AI", value: "one\ntwo", multiline: true, onConfirm: () => {}});+ assert.equal(dialog.input instanceof Input, false);+ assert.equal(dialog.input.value, "one\ntwo");+ const autocomplete = open({title: "Tag", value: "tag", bindInput: false, onConfirm: () => {}});+ assert.equal(autocomplete.enter, undefined);+});++for (const file of ["src/history/doc.ts", "src/history/history.ts"]) {+ it(`${file} keeps all page jump dialogs open for empty input and clamps valid pages`, () => {+ const source = createSourceFile(file, readFileSync(file, "utf8"), ScriptTarget.Latest, true);+ const dialogs: {onConfirm: (value: string, dialog: {destroy: () => void}) => void}[] = [];+ const pages: number[] = [];+ let messages = 0;+ const visit = (node: import("typescript").Node) => {+ if (isCallExpression(node) && node.expression.getText(source) === "openInputDialog" &&+ node.arguments[0].getText(source).includes("jumpToPage")) {+ runInNewContext(transpileModule(node.getText(source), {+ compilerOptions: {target: ScriptTarget.ES2020},+ }).outputText, {+ openInputDialog: (options: typeof dialogs[number]) => dialogs.push(options),+ window: {siyuan: {languages: {jumpToPage: "Page ${x}"}}},+ totalPage: 5, currentPage: 2, pageNumElement: {textContent: "2"}, target: {textContent: "2"},+ options: {id: "doc"}, fileElement: {}, repoElement: {}, firstPanelElement: {},+ showMessage: () => messages++,+ renderDoc: (element: unknown, page: number) => pages.push(page),+ renderRepo: (element: unknown, page: number) => pages.push(page),+ });+ }+ forEachChild(node, visit);+ };+ visit(source);+ assert.equal(dialogs.length, 2);+ for (const options of dialogs) {+ let closed = false;+ const dialog = {destroy: () => { closed = true; }};+ options.onConfirm("", dialog);+ assert.equal(closed, false);+ options.onConfirm("invalid", dialog);+ assert.equal(closed, false);+ options.onConfirm("99", dialog);+ assert.equal(closed, true);+ options.onConfirm("0", dialog);+ }+ assert.equal(messages, 4);+ assert.deepEqual(pages, [5, 1, 5, 1]);+ });+}diff --git a/app/src/dialog/inputDialog.ts b/app/src/dialog/inputDialog.tsindex c789383bea..a075e47ab1 100644--- a/app/src/dialog/inputDialog.ts+++ b/app/src/dialog/inputDialog.ts@@ -7,41 +7,69 @@ export const openInputDialog = (options: {value: string,label?: string,width?: string,+ positionId?: string,maxLength?: number,- type?: "text" | "number",+ type?: "text" | "number" | "password",+ multiline?: boolean,min?: string,max?: string,step?: string,placeholder?: string,// 说明沿用现有本地化文案的 HTML 语义。description?: string,+ // 附加控件由调用方提供可信 HTML 并绑定交互。+ extraContent?: string,+ confirmText?: string,+ actions?: {+ text: string,+ position?: "beforeCancel" | "beforeConfirm" | "afterConfirm",+ danger?: boolean,+ onClick: (value: string, dialog: Dialog) => void,+ }[],+ // 自动补全等入口可自行处理输入框键盘事件。+ bindInput?: boolean,onConfirm: (value: string, dialog: Dialog) => void,destroyCallback?: (options?: IObject) => void,}): Dialog => {- const inputHTML = '<input spellcheck="false" class="b3-text-field fn__block" value="">';+ const inputHTML = options.multiline ?+ '<textarea spellcheck="false" class="b3-text-field fn__block" style="resize:none" data-dialog-input></textarea>' :+ '<input spellcheck="false" class="b3-text-field fn__block" value="" data-dialog-input>';+ const actionsHTML = (position: "beforeCancel" | "beforeConfirm" | "afterConfirm") =>+ (options.actions || []).map((action, index) => (action.position || "beforeConfirm") === position ?+ `<button class="b3-button b3-button--${action.danger ? "remove" : "text"}" data-input-action="${index}">${escapeHtml(action.text)}</button>` : "").filter(Boolean).join('<div class="fn__space"></div>');+ const actionHTML = [+ actionsHTML("beforeCancel"),+ `<button class="b3-button b3-button--cancel" data-input-cancel>${window.siyuan.languages.cancel}</button>`,+ actionsHTML("beforeConfirm"),+ `<button class="b3-button b3-button--text" data-input-confirm>${escapeHtml(options.confirmText || window.siyuan.languages.confirm)}</button>`,+ actionsHTML("afterConfirm"),+ ].filter(Boolean).join('<div class="fn__space"></div>');const dialog = new Dialog({title: options.title,- content: `<div class="b3-dialog__content">${options.label ? `<label>${escapeHtml(options.label)}<div class="fn__hr"></div>${inputHTML}</label>` : inputHTML}${options.description ? `<div class="b3-label__text">${options.description}</div>` : ""}</div>+ positionId: options.positionId,+ content: `<div class="b3-dialog__content">${options.label ? `<label>${escapeHtml(options.label)}<div class="fn__hr"></div>${inputHTML}</label>` : inputHTML}${options.description ? `<div class="b3-label__text">${options.description}</div>` : ""}${options.extraContent || ""}</div><div class="b3-dialog__action">- <button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button><div class="fn__space"></div>- <button class="b3-button b3-button--text">${window.siyuan.languages.confirm}</button>+ ${actionHTML}</div>`,width: options.width || (isMobile() ? "92vw" : "520px"),destroyCallback: options.destroyCallback,});- const inputElement = dialog.element.querySelector("input") as HTMLInputElement;- const btnsElement = dialog.element.querySelectorAll<HTMLButtonElement>(".b3-button");- if (options.type !== undefined) {- inputElement.type = options.type;- }- if (options.min !== undefined) {- inputElement.min = options.min;- }- if (options.max !== undefined) {- inputElement.max = options.max;- }- if (options.step !== undefined) {- inputElement.step = options.step;+ const inputElement = dialog.element.querySelector<HTMLInputElement | HTMLTextAreaElement>("[data-dialog-input]");+ const cancelElement = dialog.element.querySelector<HTMLButtonElement>("[data-input-cancel]");+ const confirmElement = dialog.element.querySelector<HTMLButtonElement>("[data-input-confirm]");+ if (inputElement instanceof HTMLInputElement) {+ if (options.type !== undefined) {+ inputElement.type = options.type;+ }+ if (options.min !== undefined) {+ inputElement.min = options.min;+ }+ if (options.max !== undefined) {+ inputElement.max = options.max;+ }+ if (options.step !== undefined) {+ inputElement.step = options.step;+ }}if (options.placeholder !== undefined) {inputElement.placeholder = options.placeholder;@@ -50,16 +78,24 @@ export const openInputDialog = (options: {if (options.maxLength !== undefined) {inputElement.maxLength = options.maxLength;}- btnsElement[0].addEventListener("click", () => {+ cancelElement.addEventListener("click", () => {dialog.destroy();});- btnsElement[1].addEventListener("click", () => {+ confirmElement.addEventListener("click", () => {// 校验、提交和关闭时机由调用方决定。options.onConfirm(inputElement.value, dialog);});- dialog.bindInput(inputElement, () => {- btnsElement[1].click();+ dialog.element.querySelectorAll<HTMLButtonElement>("[data-input-action]").forEach(button => {+ button.addEventListener("click", () => {+ options.actions[Number(button.dataset.inputAction)].onClick(inputElement.value, dialog);+ });});+ if (options.bindInput !== false) {+ dialog.bindInput(inputElement, () => {+ confirmElement.click();+ });+ }+ inputElement.focus();inputElement.select();return dialog;};diff --git a/app/src/history/doc.ts b/app/src/history/doc.tsindex 226b54098e..51de74a025 100644--- a/app/src/history/doc.ts+++ b/app/src/history/doc.ts@@ -1,3 +1,5 @@+import {openInputDialog} from "../dialog/inputDialog";+import {showMessage} from "../dialog/message";import {Dialog} from "../dialog";import {confirmDialog} from "../dialog/confirmDialog";import {Constants} from "../constants";@@ -463,17 +465,21 @@ export const openDocHistory = (options: {break;} else if (type === "jumpRepoPage") {const totalPage = parseInt(target.getAttribute("data-totalpage") || "1");- confirmDialog(- window.siyuan.languages.jumpToPage.replace("${x}", totalPage),- `<input class="b3-text-field fn__block" type="number" min="1" max="${totalPage}" value="${pageNumElement.textContent}">`,- (confirmD) => {- const inputElement = confirmD.element.querySelector(".b3-text-field") as HTMLInputElement;- if (inputElement.value === "") {+ openInputDialog({+ title: window.siyuan.languages.jumpToPage.replace("${x}", totalPage),+ value: String(pageNumElement.textContent),+ type: "number",+ min: "1",+ max: String(totalPage),+ onConfirm: (value, dialog) => {+ if (!Number.isFinite(parseInt(value))) {+ showMessage(window.siyuan.languages.jumpToPage.replace("${x}", totalPage));return;}- renderDoc(fileElement, Math.max(1, Math.min(parseInt(inputElement.value), totalPage)), options.id);- }- );+ renderDoc(fileElement, Math.max(1, Math.min(parseInt(value), totalPage)), options.id);+ dialog.destroy();+ },+ });} else if ((type === "snapshotprevious" || type === "snapshotnext") &&target.getAttribute("disabled") !== "disabled") {const currentPage = parseInt(repoElement.getAttribute("data-page") || "1");@@ -483,17 +489,21 @@ export const openDocHistory = (options: {break;} else if (type === "jumpSnapshotPage") {const totalPage = parseInt(target.getAttribute("data-totalpage") || "1");- confirmDialog(- window.siyuan.languages.jumpToPage.replace("${x}", totalPage),- `<input class="b3-text-field fn__block" type="number" min="1" max="${totalPage}" value="${target.textContent}">`,- (confirmD) => {- const inputElement = confirmD.element.querySelector(".b3-text-field") as HTMLInputElement;- if (inputElement.value === "") {+ openInputDialog({+ title: window.siyuan.languages.jumpToPage.replace("${x}", totalPage),+ value: String(target.textContent),+ type: "number",+ min: "1",+ max: String(totalPage),+ onConfirm: (value, dialog) => {+ if (!Number.isFinite(parseInt(value))) {+ showMessage(window.siyuan.languages.jumpToPage.replace("${x}", totalPage));return;}- renderRepo(repoElement, Math.max(1, Math.min(parseInt(inputElement.value), totalPage)), options.id);- }- );+ renderRepo(repoElement, Math.max(1, Math.min(parseInt(value), totalPage)), options.id);+ dialog.destroy();+ },+ });}target = target.parentElement;}diff --git a/app/src/history/history.ts b/app/src/history/history.tsindex d1e1ffaf31..5c42aace64 100644--- a/app/src/history/history.ts+++ b/app/src/history/history.ts@@ -1,3 +1,5 @@+import {openInputDialog} from "../dialog/inputDialog";+import {showMessage} from "../dialog/message";import {Dialog} from "../dialog";import {confirmDialog} from "../dialog/confirmDialog";import {Constants} from "../constants";@@ -1060,48 +1062,40 @@ const bindEvent = (app: App, element: Element, dialog?: Dialog) => {event.preventDefault();break;} else if (type === "genTag") {- const genTagDialog = new Dialog({+ const genTagDialog = openInputDialog({title: window.siyuan.languages.tagSnapshot,- content: `<div class="b3-dialog__content">- <input class="b3-text-field fn__block" value="${dayjs().format("YYYYMMDDHHmmss")}" placeholder="${window.siyuan.languages.tagSnapshotTip}">-</div>-<div class="b3-dialog__action">- <button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button><div class="fn__space"></div>- <button class="b3-button b3-button--text">${window.siyuan.languages.tagSnapshot}</button><div class="fn__space"></div>- <button class="b3-button b3-button--text">${window.siyuan.languages.tagSnapshotUpload}</button>-</div>`,- width: isMobile() ? "92vw" : "520px",- });- genTagDialog.element.setAttribute("data-key", Constants.DIALOG_SNAPSHOTTAG);- const inputElement = genTagDialog.element.querySelector(".b3-text-field") as HTMLInputElement;- inputElement.select();- const btnsElement = genTagDialog.element.querySelectorAll(".b3-button");- btnsElement[0].addEventListener("click", () => {- genTagDialog.destroy();- });- btnsElement[2].addEventListener("click", () => {- fetchPost("/api/repo/tagSnapshot", {- id: target.parentElement.getAttribute("data-id"),- name: inputElement.value- }, () => {- fetchPost("/api/repo/uploadCloudSnapshot", {- tag: inputElement.value,- id: target.parentElement.getAttribute("data-id")+ value: dayjs().format("YYYYMMDDHHmmss"),+ placeholder: window.siyuan.languages.tagSnapshotTip,+ confirmText: window.siyuan.languages.tagSnapshot,+ actions: [{+ text: window.siyuan.languages.tagSnapshotUpload,+ position: "afterConfirm",+ onClick: (value, genTagDialog) => {+ fetchPost("/api/repo/tagSnapshot", {+ id: target.parentElement.getAttribute("data-id"),+ name: value+ }, () => {+ fetchPost("/api/repo/uploadCloudSnapshot", {+ tag: value,+ id: target.parentElement.getAttribute("data-id")+ }, () => {+ renderRepo(repoElement, 1);+ });+ });+ genTagDialog.destroy();+ },+ }],+ onConfirm: (value, genTagDialog) => {+ fetchPost("/api/repo/tagSnapshot", {+ id: target.parentElement.getAttribute("data-id"),+ name: value}, () => {renderRepo(repoElement, 1);});- });- genTagDialog.destroy();- });- btnsElement[1].addEventListener("click", () => {- fetchPost("/api/repo/tagSnapshot", {- id: target.parentElement.getAttribute("data-id"),- name: inputElement.value- }, () => {- renderRepo(repoElement, 1);- });- genTagDialog.destroy();+ genTagDialog.destroy();+ },});+ genTagDialog.element.setAttribute("data-key", Constants.DIALOG_SNAPSHOTTAG);event.stopPropagation();event.preventDefault();break;@@ -1116,38 +1110,46 @@ const bindEvent = (app: App, element: Element, dialog?: Dialog) => {const totalPage = parseInt(target.getAttribute("data-totalpage") || "1");if (totalPage > 1) {- confirmDialog(- window.siyuan.languages.jumpToPage.replace("${x}", totalPage),- `<input class="b3-text-field fn__block" type="number" min="1" max="${totalPage}" value="${currentPage}">`,- (confirmD) => {- const inputElement = confirmD.element.querySelector(".b3-text-field") as HTMLInputElement;- if (inputElement.value === "") {+ openInputDialog({+ title: window.siyuan.languages.jumpToPage.replace("${x}", totalPage),+ value: String(currentPage),+ type: "number",+ min: "1",+ max: String(totalPage),+ onConfirm: (value, dialog) => {+ if (!Number.isFinite(parseInt(value))) {+ showMessage(window.siyuan.languages.jumpToPage.replace("${x}", totalPage));return;}- let page = parseInt(inputElement.value);+ let page = parseInt(value);page = Math.max(1, Math.min(page, totalPage));renderRepo(repoElement, page);- }- );+ dialog.destroy();+ },+ });}} else if (type === "jumpHistoryPage") {const currentPage = parseInt(historyElement.getAttribute("data-page"));const totalPage = parseInt(target.getAttribute("data-totalpage") || "1");if (totalPage > 1) {- confirmDialog(- window.siyuan.languages.jumpToPage.replace("${x}", totalPage),- `<input class="b3-text-field fn__block" type="number" min="1" max="${totalPage}" value="${currentPage}">`,- (confirmD) => {- const inputElement = confirmD.element.querySelector(".b3-text-field") as HTMLInputElement;- if (inputElement.value === "") {+ openInputDialog({+ title: window.siyuan.languages.jumpToPage.replace("${x}", totalPage),+ value: String(currentPage),+ type: "number",+ min: "1",+ max: String(totalPage),+ onConfirm: (value, dialog) => {+ if (!Number.isFinite(parseInt(value))) {+ showMessage(window.siyuan.languages.jumpToPage.replace("${x}", totalPage));return;}- let page = parseInt(inputElement.value);+ let page = parseInt(value);page = Math.max(1, Math.min(page, totalPage));renderDoc(firstPanelElement, page);- }- );+ dialog.destroy();+ },+ });}} else if ((type === "docprevious" || type === "docnext") && target.getAttribute("disabled") !== "disabled") {const currentPage = parseInt(firstPanelElement.getAttribute("data-page"));diff --git a/app/src/menus/commonMenuItem.ts b/app/src/menus/commonMenuItem.tsindex ccd414afe9..cbf3c3e1d4 100644--- a/app/src/menus/commonMenuItem.ts+++ b/app/src/menus/commonMenuItem.ts@@ -584,19 +584,55 @@ export const exportMd = (id: string) => {<div>${window.siyuan.languages.duplicateMirror}<div class="b3-label__text">${window.siyuan.languages.templateDatabaseReferenceTip}</div></div></label>` : "";- const dialog = new Dialog({+ const maxNameLen = 32;+ const name = replaceFileName(info.name).substring(0, maxNameLen);+ const dialog = openInputDialog({title: window.siyuan.languages.fileName,- content: `<div class="b3-dialog__content"><input class="b3-text-field fn__block" value="">+ value: name,+ extraContent: `<div class="fn__hr"></div><label>${window.siyuan.languages.savePath}<div class="fn__hr"></div><select class="b3-select fn__block" data-template-directory><option value="">/</option></select></label><div class="fn__hr"></div><button type="button" class="b3-button b3-button--outline" data-template-manager>${window.siyuan.languages.templateManager}</button>-${databaseOptions}</div>-<div class="b3-dialog__action">- <button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button><div class="fn__space"></div>- <button class="b3-button b3-button--text">${window.siyuan.languages.confirm}</button>-</div>`,- width: isMobile() ? "92vw" : "520px",+${databaseOptions}`,+ onConfirm: (value, dialog) => {+ const inputElement = dialog.element.querySelector<HTMLInputElement>("[data-dialog-input]");+ let templateName = value.trim() === "" ? window.siyuan.languages.untitled :+ replaceFileName(value);+ if (templateName.length > maxNameLen) {+ templateName = templateName.substring(0, maxNameLen);+ }+ inputElement.value = templateName;+ const selectedDatabaseMode = (dialog.element.querySelector(+ "input[name=\"templateDatabaseMode\"]:checked") as HTMLInputElement)?.value;+ const databaseMode: "copy" | "reference" = selectedDatabaseMode === "reference" ?+ "reference" : "copy";+ const requestData = {+ id,+ name: templateName,+ directory: directoryElement.value,+ overwrite: false,+ databaseMode,+ };+ fetchPost("/api/template/docSaveAsTemplate", requestData, response => {+ if (response.code === 1) {+ // 重名+ confirmDialog(window.siyuan.languages.export, window.siyuan.languages.exportTplTip, () => {+ fetchPost("/api/template/docSaveAsTemplate", {+ ...requestData,+ overwrite: true+ }, resp => {+ if (resp.code === 0) {+ showMessage(window.siyuan.languages.exportTplSucc);+ }+ });+ });+ return;+ }+ showMessage(window.siyuan.languages.exportTplSucc);+ });+ dialog.destroy();+ },});dialog.element.setAttribute("data-key", Constants.DIALOG_EXPORTTEMPLATE);const directoryElement = dialog.element.querySelector<HTMLSelectElement>("[data-template-directory]");@@ -607,59 +643,6 @@ ${databaseOptions}</div>void loadTemplateDirectories(directoryElement).catch(console.error);});});- const inputElement = dialog.element.querySelector("input") as HTMLInputElement;- const btnsElement = dialog.element.querySelectorAll(".b3-dialog__action .b3-button");- dialog.bindInput(inputElement, () => {- (btnsElement[1] as HTMLButtonElement).click();- });- const maxNameLen = 32;- let name = replaceFileName(info.name);- if (name.length > maxNameLen) {- name = name.substring(0, maxNameLen);- }- inputElement.value = name;- inputElement.focus();- inputElement.select();- btnsElement[0].addEventListener("click", () => {- dialog.destroy();- });- btnsElement[1].addEventListener("click", () => {- let templateName = inputElement.value.trim() === "" ? window.siyuan.languages.untitled :- replaceFileName(inputElement.value);- if (templateName.length > maxNameLen) {- templateName = templateName.substring(0, maxNameLen);- }- inputElement.value = templateName;- const selectedDatabaseMode = (dialog.element.querySelector(- "input[name=\"templateDatabaseMode\"]:checked") as HTMLInputElement)?.value;- const databaseMode: "copy" | "reference" = selectedDatabaseMode === "reference" ?- "reference" : "copy";- const requestData = {- id,- name: templateName,- directory: directoryElement.value,- overwrite: false,- databaseMode,- };- fetchPost("/api/template/docSaveAsTemplate", requestData, response => {- if (response.code === 1) {- // 重名- confirmDialog(window.siyuan.languages.export, window.siyuan.languages.exportTplTip, () => {- fetchPost("/api/template/docSaveAsTemplate", {- ...requestData,- overwrite: true- }, resp => {- if (resp.code === 0) {- showMessage(window.siyuan.languages.exportTplSucc);- }- });- });- return;- }- showMessage(window.siyuan.languages.exportTplSucc);- });- dialog.destroy();- });}}, {id: "exportSiYuanZip",diff --git a/app/src/menus/dataMigration.ts b/app/src/menus/dataMigration.tsindex 7ffd04d4ac..5e699d8585 100644--- a/app/src/menus/dataMigration.ts+++ b/app/src/menus/dataMigration.ts@@ -1,3 +1,4 @@+import {openInputDialog} from "../dialog/inputDialog";import {Dialog} from "../dialog";import {Constants} from "../constants";import {escapeHtml} from "../util/escape";@@ -32,30 +33,21 @@ const getImportButton = (type: string, accept: string) => `<button class="b3-but</button>`;const openRepoKeyImport = (onComplete?: () => void) => {- const dialog = new Dialog({+ const dialog = openInputDialog({title: `🔑 ${window.siyuan.languages.key}`,- content: `<div class="b3-dialog__content">- <input type="text" spellcheck="false" class="b3-text-field fn__block" placeholder="${window.siyuan.languages.keyPlaceholder}">-</div>-<div class="b3-dialog__action">- <button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button><div class="fn__space"></div>- <button class="b3-button b3-button--text">${window.siyuan.languages.confirm}</button>-</div>`,+ value: "",+ placeholder: window.siyuan.languages.keyPlaceholder,width: "520px",+ onConfirm: (value, dialog) => {+ fetchPost("/api/repo/importRepoKey", {key: value}, (response) => {+ window.siyuan.config.repo.key = response.data.key;+ dialog.destroy();+ showMessage(window.siyuan.languages.imported);+ onComplete?.();+ });+ },});dialog.element.setAttribute("data-key", Constants.DIALOG_PASSWORD);- const inputElement = dialog.element.querySelector("input") as HTMLInputElement;- const buttons = dialog.element.querySelectorAll(".b3-button");- inputElement.focus();- buttons[0].addEventListener("click", () => dialog.destroy());- buttons[1].addEventListener("click", () => {- fetchPost("/api/repo/importRepoKey", {key: inputElement.value}, (response) => {- window.siyuan.config.repo.key = response.data.key;- dialog.destroy();- showMessage(window.siyuan.languages.imported);- onComplete?.();- });- });};const exportData = async () => {diff --git a/app/src/menus/workspace.ts b/app/src/menus/workspace.tsindex 2f20daa5b6..bfc3d71e2a 100644--- a/app/src/menus/workspace.ts+++ b/app/src/menus/workspace.ts@@ -44,99 +44,88 @@ import {getHostCapabilities} from "../util/hostCapabilities";import {openTemplateManager} from "../template/manager";const editLayout = (layoutName?: string) => {- const dialog = new Dialog({+ const dialog = openInputDialog({positionId: Constants.DIALOG_SAVEWORKSPACE,title: layoutName ? window.siyuan.languages.edit : window.siyuan.languages.save,- content: `<div class="b3-dialog__content">- <input class="b3-text-field fn__block" value="${layoutName || ""}" placeholder="${window.siyuan.languages.memo}">-</div>-<div class="b3-dialog__action">- <button class="b3-button b3-button--remove${layoutName ? "" : " fn__none"}">${window.siyuan.languages.delete}</button><div class="fn__space"></div>- <button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button><div class="fn__space"></div>- <button class="b3-button b3-button--text${layoutName ? "" : " fn__none"}">${window.siyuan.languages.rename}</button><div class="fn__space"></div>- <button class="b3-button b3-button--text">${window.siyuan.languages[layoutName ? "updateLayout" : "confirm"]}</button>-</div>`,+ value: layoutName || "",+ placeholder: window.siyuan.languages.memo,width: "520px",- });- dialog.element.setAttribute("data-key", Constants.DIALOG_SAVEWORKSPACE);- const btnsElement = dialog.element.querySelectorAll(".b3-button");- const inputElement = dialog.element.querySelector("input");- inputElement.select();- inputElement.focus();- dialog.bindInput(inputElement, () => {- btnsElement[3].dispatchEvent(new CustomEvent("click"));- });- btnsElement[0].addEventListener("click", () => {- window.siyuan.storage[Constants.LOCAL_LAYOUTS].find((layoutItem: ISaveLayout, index: number) => {- if (layoutItem.name === layoutName) {- window.siyuan.storage[Constants.LOCAL_LAYOUTS].splice(index, 1);- setStorageVal(Constants.LOCAL_LAYOUTS, window.siyuan.storage[Constants.LOCAL_LAYOUTS]);- return true;+ confirmText: window.siyuan.languages[layoutName ? "updateLayout" : "confirm"],+ actions: layoutName ? [{+ text: window.siyuan.languages.delete,+ danger: true,+ position: "beforeCancel",+ onClick: (value, dialog) => {+ window.siyuan.storage[Constants.LOCAL_LAYOUTS].find((layoutItem: ISaveLayout, index: number) => {+ if (layoutItem.name === layoutName) {+ window.siyuan.storage[Constants.LOCAL_LAYOUTS].splice(index, 1);+ setStorageVal(Constants.LOCAL_LAYOUTS, window.siyuan.storage[Constants.LOCAL_LAYOUTS]);+ return true;+ }+ });+ dialog.destroy();+ },+ }, {+ text: window.siyuan.languages.rename,+ onClick: (value, dialog) => {+ if (!value) {+ showMessage(window.siyuan.languages["_kernel"]["142"]);+ return;+ }+ dialog.destroy();+ window.siyuan.storage[Constants.LOCAL_LAYOUTS].find((layoutItem: ISaveLayout) => {+ if (layoutItem.name === layoutName) {+ layoutItem.name = value;+ layoutItem.time = Date.now();+ setStorageVal(Constants.LOCAL_LAYOUTS, window.siyuan.storage[Constants.LOCAL_LAYOUTS]);+ return true;+ }+ });+ },+ }] : [],+ onConfirm: (value, dialog) => {+ if (!value) {+ showMessage(window.siyuan.languages["_kernel"]["142"]);+ return;}- });- dialog.destroy();- });- btnsElement[1].addEventListener("click", () => {- dialog.destroy();- });- btnsElement[2].addEventListener("click", () => {- const value = inputElement.value;- if (!value) {- showMessage(window.siyuan.languages["_kernel"]["142"]);- return;- }- dialog.destroy();- window.siyuan.storage[Constants.LOCAL_LAYOUTS].find((layoutItem: ISaveLayout) => {- if (layoutItem.name === layoutName) {- layoutItem.name = value;- layoutItem.time = Date.now();- setStorageVal(Constants.LOCAL_LAYOUTS, window.siyuan.storage[Constants.LOCAL_LAYOUTS]);- return true;+ dialog.destroy();+ if (layoutName) {+ window.siyuan.storage[Constants.LOCAL_LAYOUTS].find((layoutItem: ISaveLayout) => {+ if (layoutItem.name === layoutName) {+ layoutItem.name = value;+ layoutItem.time = Date.now();+ layoutItem.layout = getAllLayout();+ layoutItem.filesPaths = window.siyuan.storage[Constants.LOCAL_FILESPATHS];+ setStorageVal(Constants.LOCAL_LAYOUTS, window.siyuan.storage[Constants.LOCAL_LAYOUTS]);+ return true;+ }+ });+ return;}- });- });- btnsElement[3].addEventListener("click", () => {- const value = inputElement.value;- if (!value) {- showMessage(window.siyuan.languages["_kernel"]["142"]);- return;- }- dialog.destroy();- if (layoutName) {- window.siyuan.storage[Constants.LOCAL_LAYOUTS].find((layoutItem: ISaveLayout) => {- if (layoutItem.name === layoutName) {- layoutItem.name = value;- layoutItem.time = Date.now();- layoutItem.layout = getAllLayout();- layoutItem.filesPaths = window.siyuan.storage[Constants.LOCAL_FILESPATHS];- setStorageVal(Constants.LOCAL_LAYOUTS, window.siyuan.storage[Constants.LOCAL_LAYOUTS]);+ const hadName = window.siyuan.storage[Constants.LOCAL_LAYOUTS].find((item: ISaveLayout) => {+ if (item.name === value) {+ confirmDialog(window.siyuan.languages.save, window.siyuan.languages.exportTplTip, () => {+ item.layout = getAllLayout();+ item.time = Date.now();+ item.filesPaths = window.siyuan.storage[Constants.LOCAL_FILESPATHS];+ setStorageVal(Constants.LOCAL_LAYOUTS, window.siyuan.storage[Constants.LOCAL_LAYOUTS]);+ });return true;}});- return;- }- const hadName = window.siyuan.storage[Constants.LOCAL_LAYOUTS].find((item: ISaveLayout) => {- if (item.name === value) {- confirmDialog(window.siyuan.languages.save, window.siyuan.languages.exportTplTip, () => {- item.layout = getAllLayout();- item.time = Date.now();- item.filesPaths = window.siyuan.storage[Constants.LOCAL_FILESPATHS];- setStorageVal(Constants.LOCAL_LAYOUTS, window.siyuan.storage[Constants.LOCAL_LAYOUTS]);- });- return true;+ if (hadName) {+ return;}- });- if (hadName) {- return;- }- window.siyuan.storage[Constants.LOCAL_LAYOUTS].push({- name: value,- time: Date.now(),- layout: getAllLayout(),- filesPaths: window.siyuan.storage[Constants.LOCAL_FILESPATHS]- });- setStorageVal(Constants.LOCAL_LAYOUTS, window.siyuan.storage[Constants.LOCAL_LAYOUTS]);+ window.siyuan.storage[Constants.LOCAL_LAYOUTS].push({+ name: value,+ time: Date.now(),+ layout: getAllLayout(),+ filesPaths: window.siyuan.storage[Constants.LOCAL_FILESPATHS]+ });+ setStorageVal(Constants.LOCAL_LAYOUTS, window.siyuan.storage[Constants.LOCAL_LAYOUTS]);+ },});+ dialog.element.setAttribute("data-key", Constants.DIALOG_SAVEWORKSPACE);};const togglePinDock = (id: "switchLeftDock" | "switchRightDock" | "switchBottomDock", dock: Dock, pinIcon: string, unpinIcon: string) => {diff --git a/app/src/protyle/util/table.ts b/app/src/protyle/util/table.tsindex f4e03f9747..b6fc62645c 100644--- a/app/src/protyle/util/table.ts+++ b/app/src/protyle/util/table.ts@@ -1,3 +1,4 @@+import {openInputDialog} from "../../dialog/inputDialog";import {updateTransaction} from "../wysiwyg/transaction";import {focusBlock,@@ -16,8 +17,6 @@ import {insertEmptyBlock} from "../../block/util";import {removeBlock} from "../wysiwyg/remove";import {hasNextSibling, hasPreviousSibling} from "../wysiwyg/getBlock";import * as dayjs from "dayjs";-import {Dialog} from "../../dialog";-import {isMobile} from "../../util/functions";import {getProjectedTableHeadRowCount,getTableHeadRowCount,@@ -769,16 +768,12 @@ export const updateTableTitle = (protyle: IProtyle, nodeElement: Element) => {}const captionElement = nodeElement.querySelector("caption");window.siyuan.menus.menu.remove();- const dialog = new Dialog({+ const html = nodeElement.outerHTML;+ openInputDialog({title: window.siyuan.languages.table,- width: isMobile() ? "92vw" : "520px",- content: `<div class="b3-dialog__content">- <label>- <div>${window.siyuan.languages.title}</div>- <div class="fn__hr"></div>- <input class="b3-text-field fn__block">- </label>- <div class="fn__hr--b"></div>+ label: window.siyuan.languages.title,+ value: captionElement?.textContent || "",+ extraContent: `<div class="fn__hr--b"></div><label><div>${window.siyuan.languages.position}</div><div class="fn__hr"></div>@@ -786,46 +781,28 @@ export const updateTableTitle = (protyle: IProtyle, nodeElement: Element) => {<option value="top">${window.siyuan.languages.up}</option><option value="bottom" ${captionElement?.style.captionSide === "bottom" ? "selected" : ""}>${window.siyuan.languages.down}</option></select>- </label>-</div>-<div class="b3-dialog__action">- <button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button><div class="fn__space"></div>- <button class="b3-button b3-button--text">${window.siyuan.languages.confirm}</button>-</div>-<div>`,- });- const html = nodeElement.outerHTML;- const inputElement = dialog.element.querySelector(".b3-text-field") as HTMLInputElement;- const btnsElement = dialog.element.querySelectorAll(".b3-button");- dialog.bindInput(inputElement, () => {- (btnsElement[1] as HTMLButtonElement).click();- });- btnsElement[0].addEventListener("click", () => {- dialog.destroy();- });- btnsElement[1].addEventListener("click", () => {- const title = inputElement.value.trim();- const location = (dialog.element.querySelector("select") as HTMLSelectElement).value;- if (title) {- const html = `<caption contenteditable="false" ${location === "bottom" ? 'style="caption-side: bottom;"' : ""}>${Lute.EscapeHTMLStr(title)}</caption>`;- if (captionElement) {- captionElement.outerHTML = html;+ </label>`,+ onConfirm: (value, dialog) => {+ const title = value.trim();+ const location = (dialog.element.querySelector("select") as HTMLSelectElement).value;+ if (title) {+ const html = `<caption contenteditable="false" ${location === "bottom" ? 'style="caption-side: bottom;"' : ""}>${Lute.EscapeHTMLStr(title)}</caption>`;+ if (captionElement) {+ captionElement.outerHTML = html;+ } else {+ nodeElement.querySelector("table").insertAdjacentHTML("afterbegin", html);+ }+ nodeElement.setAttribute("caption", Lute.EscapeHTMLStr(html));} else {- nodeElement.querySelector("table").insertAdjacentHTML("afterbegin", html);- }- nodeElement.setAttribute("caption", Lute.EscapeHTMLStr(html));- } else {- if (captionElement) {- captionElement.remove();+ if (captionElement) {+ captionElement.remove();+ }+ nodeElement.removeAttribute("caption");}- nodeElement.removeAttribute("caption");- }- updateTransaction(protyle, nodeElement, html);- dialog.destroy();+ updateTransaction(protyle, nodeElement, html);+ dialog.destroy();+ },});- inputElement.value = captionElement?.textContent || "";- inputElement.focus();- inputElement.select();};export interface ITableCellInfo {diff --git a/app/src/util/mount.ts b/app/src/util/mount.tsindex 2822f303f3..202232a840 100644--- a/app/src/util/mount.ts+++ b/app/src/util/mount.ts@@ -1,3 +1,4 @@+import {openInputDialog} from "../dialog/inputDialog";import {Constants} from "../constants";import {showMessage} from "../dialog/message";import {isMobile} from "./functions";@@ -381,45 +382,32 @@ export const openEncryptedNotebook = (app: App, notebookId: string, name: stringif (window.siyuan.dialogs.some((item) => item.element.getAttribute("data-key") === dialogKey)) {return;}- const dialog = new Dialog({+ const dialog = openInputDialog({title: window.siyuan.languages.unlockEncryptedNotebook.replace("${x}", escapeHtml(name)),- content: `<div class="b3-dialog__content">- <input type="password" placeholder="${window.siyuan.languages.masterPassword}" class="b3-text-field fn__block">- <div class="fn__hr--b"></div>- <div>${window.siyuan.languages.encryptedNotebookRiskTip}</div>-</div>-<div class="b3-dialog__action">- <button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button><div class="fn__space"></div>- <button class="b3-button b3-button--text">${window.siyuan.languages.confirm}</button>-</div>`,- width: isMobile() ? "92vw" : "520px"+ value: "",+ type: "password",+ placeholder: window.siyuan.languages.masterPassword,+ description: window.siyuan.languages.encryptedNotebookRiskTip,+ onConfirm: async (password, dialog) => {+ const inputElement = dialog.element.querySelector<HTMLInputElement>("[data-dialog-input]");+ const confirmElement = dialog.element.querySelector<HTMLButtonElement>("[data-input-confirm]");+ if (!password) {+ return false;+ }+ confirmElement.disabled = true;+ // 原子化解锁并挂载:UnlockBox 成功后立即 Mount,Mount 失败则后端自动 LockBox 回滚,避免 DEK 残留+ const response = await fetchSyncPost("/api/notebook/unlockAndOpenNotebook", {+ notebook: notebookId,+ password+ });+ if (response.code === 0) {+ dialog.destroy();+ } else {+ confirmElement.disabled = false;+ inputElement.value = "";+ inputElement.focus();+ }+ },});dialog.element.setAttribute("data-key", dialogKey);- const btnsElement = dialog.element.querySelectorAll<HTMLButtonElement>(".b3-button");- const inputElement = dialog.element.querySelector("input");- dialog.bindInput(inputElement, () => {- btnsElement[1].dispatchEvent(new CustomEvent("click"));- });- btnsElement[0].addEventListener("click", () => {- dialog.destroy();- });- btnsElement[1].addEventListener("click", async () => {- const password = inputElement.value;- if (!password) {- return false;- }- btnsElement[1].disabled = true;- // 原子化解锁并挂载:UnlockBox 成功后立即 Mount,Mount 失败则后端自动 LockBox 回滚,避免 DEK 残留- const response = await fetchSyncPost("/api/notebook/unlockAndOpenNotebook", {- notebook: notebookId,- password- });- if (response.code === 0) {- dialog.destroy();- } else {- btnsElement[1].disabled = false;- inputElement.value = "";- inputElement.focus();- }- });};diff --git a/app/src/util/noRelyPCFunction.ts b/app/src/util/noRelyPCFunction.tsindex 9f9842d088..634c13462c 100644--- a/app/src/util/noRelyPCFunction.ts+++ b/app/src/util/noRelyPCFunction.ts@@ -1,6 +1,5 @@-import {Dialog} from "../dialog";+import {openInputDialog} from "../dialog/inputDialog";import {fetchPost} from "./fetch";-import {isMobile} from "./functions";import {Constants} from "../constants";/// #if !MOBILEimport {getDockByType} from "../layout/tabUtil";@@ -36,40 +35,28 @@ export const genTagList = (listElement: Element, k: string) => {// 需独立出来,否则移动端引用的时候会引入 pc 端大量无用代码export const renameTag = (labelName: string) => {- const dialog = new Dialog({+ const dialog = openInputDialog({title: window.siyuan.languages.rename,- content: `<div class="b3-dialog__content">- <input class="b3-text-field fn__block">- <div class="b3-list fn__flex-1 b3-list--background fn__none protyle-hint" style="position: absolute;width: calc(100% - 48px);">+ value: labelName,+ bindInput: false,+ extraContent: `<div class="b3-list fn__flex-1 b3-list--background fn__none protyle-hint" style="position: absolute;width: calc(100% - 48px);"><img style="margin: 0 auto;display: block;width: 64px;height: 64px" src="/stage/loading-pure.svg">- </div>-</div>-<div class="b3-dialog__action">- <button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button><div class="fn__space"></div>- <button class="b3-button b3-button--text">${window.siyuan.languages.confirm}</button>-</div>`,- width: isMobile() ? "92vw" : "520px",+ </div>`,+ onConfirm: (value, dialog) => {+ fetchPost("/api/tag/renameTag", {oldLabel: labelName, newLabel: value}, () => {+ dialog.destroy();+ /// #if MOBILE+ window.siyuan.mobile.docks.tag.update();+ /// #else+ const dockTag = getDockByType("tag");+ (dockTag.data.tag as Tag).update();+ /// #endif+ });+ },});dialog.element.setAttribute("data-key", Constants.DIALOG_RENAMETAG);- const btnsElement = dialog.element.querySelectorAll(".b3-button");- btnsElement[0].addEventListener("click", () => {- dialog.destroy();- });- btnsElement[1].addEventListener("click", () => {- fetchPost("/api/tag/renameTag", {oldLabel: labelName, newLabel: inputElement.value}, () => {- dialog.destroy();- /// #if MOBILE- window.siyuan.mobile.docks.tag.update();- /// #else- const dockTag = getDockByType("tag");- (dockTag.data.tag as Tag).update();- /// #endif- });- });- const inputElement = dialog.element.querySelector("input");- inputElement.value = labelName;- inputElement.focus();- inputElement.select();+ const inputElement = dialog.element.querySelector<HTMLInputElement>("[data-dialog-input]");+ const confirmElement = dialog.element.querySelector<HTMLButtonElement>("[data-input-confirm]");const listElement = dialog.element.querySelector(".b3-list--background");inputElement.addEventListener("keydown", (event: KeyboardEvent) => {event.stopPropagation();@@ -86,7 +73,7 @@ export const renameTag = (labelName: string) => {event.preventDefault();} else if (!event.shiftKey && isNotCtrl(event) && event.key === "Enter") {if (listElement.classList.contains("fn__none")) {- (btnsElement[1] as HTMLButtonElement).click();+ confirmElement.click();} else {const currentElement = listElement.querySelector(".b3-list-item--focus") as HTMLElement;inputElement.value = currentElement.dataset.type === "new" ? currentElement.querySelector("mark").textContent.trim() : currentElement.textContent.trim();