82 lines
2.5 KiB
TypeScript
82 lines
2.5 KiB
TypeScript
|
|
import { App, Modal, Notice } from "obsidian";
|
|||
|
|
import { HttpUtils } from "../utils/request";
|
|||
|
|
import i18n from "../utils/i18n";
|
|||
|
|
export class addMetas extends Modal {
|
|||
|
|
notice: Notice;
|
|||
|
|
type: string;
|
|||
|
|
type_name: string;
|
|||
|
|
name: string;
|
|||
|
|
fun: () => Promise<void>;
|
|||
|
|
/** 正在提交:防止连按回车重复新建同名分类/标签 */
|
|||
|
|
private submitting = false;
|
|||
|
|
constructor(app: App, type: string, fun: () => Promise<void>) {
|
|||
|
|
super(app);
|
|||
|
|
this.type = type; // "tag" | "category"
|
|||
|
|
this.type_name = type === "tag" ? i18n.t("field.tag") : i18n.t("field.category");
|
|||
|
|
this.fun = fun;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
async onOpen() {
|
|||
|
|
const { contentEl } = this;
|
|||
|
|
contentEl.createEl("h2", {
|
|||
|
|
text: i18n.t("common.add") + ` ${this.type_name}`,
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
const titleInput = contentEl.createEl("input", {
|
|||
|
|
attr: {
|
|||
|
|
type: "text",
|
|||
|
|
placeholder:
|
|||
|
|
i18n.t("common.input") + `${this.type_name} ` + i18n.t("common.enter"),
|
|||
|
|
style: "width: 100%; margin-top: 15px; margin-bottom: 15px; border: 1px solid var(--background-modifier-border); border-radius: 4px; color: var(--text-normal);",
|
|||
|
|
},
|
|||
|
|
});
|
|||
|
|
titleInput.addEventListener("input", (event) => {
|
|||
|
|
const inputValue = (event.target as HTMLInputElement).value;
|
|||
|
|
this.name = inputValue;
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
titleInput.addEventListener("keydown", async (event) => {
|
|||
|
|
if (event.key !== "Enter") return;
|
|||
|
|
if (this.submitting) return;
|
|||
|
|
|
|||
|
|
// 直接读输入框,别用 this.name:它只在 input 事件里赋值,
|
|||
|
|
// 打开弹窗直接敲回车时还是 undefined,会把空名字发到服务器
|
|||
|
|
const name = titleInput.value.trim();
|
|||
|
|
if (name === "") {
|
|||
|
|
new Notice(`${this.type_name}` + i18n.t("common.empty"));
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
this.submitting = true;
|
|||
|
|
const pending = new Notice(i18n.t("sync.adding") + "...");
|
|||
|
|
try {
|
|||
|
|
const response = await HttpUtils.post("/addMetas", {
|
|||
|
|
name,
|
|||
|
|
type: this.type,
|
|||
|
|
});
|
|||
|
|
if (response.status === "success") {
|
|||
|
|
new Notice(`${this.type_name}` + i18n.t("sync.addSuccess"));
|
|||
|
|
await this.fun();
|
|||
|
|
this.close();
|
|||
|
|
}
|
|||
|
|
} catch (error) {
|
|||
|
|
// 具体原因 HttpUtils 已经弹过(重复名称、未登录、接口不存在…),
|
|||
|
|
// 这里只在它没弹过时补一句,避免两条提示叠在一起
|
|||
|
|
HttpUtils.notifyError(
|
|||
|
|
error,
|
|||
|
|
`${this.type_name} ` + i18n.t("error.requestFailed")
|
|||
|
|
);
|
|||
|
|
console.error("add meta failed:", error);
|
|||
|
|
} finally {
|
|||
|
|
pending.hide();
|
|||
|
|
this.submitting = false;
|
|||
|
|
}
|
|||
|
|
});
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
onClose() {
|
|||
|
|
const { contentEl } = this;
|
|||
|
|
contentEl.empty();
|
|||
|
|
}
|
|||
|
|
}
|