同步插件源代码并补齐标准项目文件

This commit is contained in:
XIGE
2026-11-26 15:04:45 +08:00
parent 373b563f86
commit 588e7a51f6
28 changed files with 8229 additions and 1 deletions

81
view/add_metasl.ts Normal file
View File

@@ -0,0 +1,81 @@
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();
}
}

38
view/article_preview.ts Normal file
View File

@@ -0,0 +1,38 @@
import { App, Modal } from "obsidian";
export class ArticlePreview extends Modal {
private animationTimeout: number | null = null;
private htmlContent: string;
constructor(app: App, htmlContent: string) {
super(app);
this.htmlContent = htmlContent;
}
onOpen() {
const { contentEl } = this;
contentEl.empty();
contentEl.addClass("article-preview-modal");
// 初始状态:透明 + 缩小
contentEl.addClass("fade-enter");
contentEl.innerHTML = this.htmlContent;
// 延迟触发进入动画,确保浏览器能识别初始状态
requestAnimationFrame(() => {
contentEl.removeClass("fade-enter");
contentEl.addClass("fade-enter-active");
});
}
onClose() {
const { contentEl } = this;
contentEl.addClass("fade-exit");
contentEl.removeClass("fade-enter-active");
// 设置动画持续时间,确保动画完成后再清空内容
this.animationTimeout = window.setTimeout(() => {
contentEl.empty();
}, 300); // 与 CSS 中的 transition 时间匹配
}
}

878
view/article_type.ts Normal file

File diff suppressed because it is too large Load Diff

192
view/browse_articles.ts Normal file
View File

@@ -0,0 +1,192 @@
import { App, Modal, htmlToMarkdown, setIcon } from "obsidian";
import { HttpUtils } from "../utils/request";
import i18n from "../utils/i18n";
import { ArticlePreview } from "./article_preview";
export class BrowseArticles extends Modal {
data: any;
currentPage = 1;
totalPages = 1;
contentContainer: HTMLElement;
type: string;
constructor(app: App, data: any,type: string) {
super(app);
this.data = data;
this.type = type;
this.modalEl.addClass("browse-articles-modal");
}
async onOpen() {
const { contentEl } = this;
contentEl.empty();
const header = contentEl.createEl("div", { cls: "modal-header" });
header.createEl("h2", {
text: `${this.data.name}-${i18n.t("field.article")}`,
});
// 创建内容容器
this.contentContainer = contentEl.createEl("div", {
cls: "modal-content",
});
await this.loadPage(this.currentPage);
}
async loadPage(page: number) {
this.contentContainer.empty();
const loadingEl = this.contentContainer.createEl("div", {
text: i18n.t("common.loading"),
});
try {
const params = {
page: page.toString(),
pageSize: "10",
filterType: this.type ?? '',
filterSlug: this.data.slug ?? '',
};
let url = "/posts?";
for (const key in params) {
url += `${key}=${params[key as keyof typeof params]}&`;
}
const response = await HttpUtils.get(url);
if (
response.status === "success" &&
response.data?.dataSet?.length > 0
) {
loadingEl.setText("");
this.totalPages = response.data.pages;
this.currentPage = page;
response.data.dataSet.forEach((post: any) => {
const postEl = this.contentContainer.createEl("div", {
cls: "browse-article-item",
});
// 标题部分
const titleEl = postEl.createEl("div", {
cls: "article-title",
});
titleEl.createEl("a", {
text: post.title,
href: post.permalink,
attr: { target: "_blank" },
});
// 日期部分
postEl.createEl("div", {
cls: "article-date",
text: `${post.year}-${post.month}-${post.day}`,
});
// 保存本地
const downloadIcon = titleEl.createEl("span", {
cls: "download-icon",
});
setIcon(downloadIcon, "hard-drive-download");
downloadIcon.addEventListener("click", async (e) => {
const content = htmlToMarkdown(post.digest).toString();
const fileName = `${post.title}.md`;
// 构建带 frontmatter 的内容
const frontmatter = `---
title: ${post.title}
typecho:
cid: ${post.cid}
slug: ${post.slug}
permalink: ${post.permalink}
created: ${post.year}-${post.month}-${post.day}
---
`;
const fullContent = frontmatter + content;
let file = this.app.vault.getFileByPath(fileName);
if (file) {
await this.app.vault.modify(file, fullContent);
} else {
file = await this.app.vault.create(fileName, fullContent);
}
// 打开文件
if (file) {
this.app.workspace.openLinkText(file.path, "", true);
}
this.close();
});
// 点击预览内容
postEl.addEventListener("click", (e) => {
const target = e.target as HTMLElement;
if (target.closest("a") || target.closest("svg")) {
return;
}
e.stopPropagation();
e.preventDefault();
new ArticlePreview(this.app, post.digest).open();
});
});
// 清除旧的分页控件再重新渲染
this.paginationEl?.remove();
this.renderPagination();
} else {
this.contentContainer.createEl("p", {
cls: "no-articles",
text: i18n.t("field.no_articles_found"),
});
}
} catch (error) {
loadingEl.setText("");
this.contentContainer.createEl("p", {
text: i18n.t("common.error_occurred"),
});
console.error("Failed to fetch articles:", error);
}
}
private paginationEl: HTMLElement | null = null;
renderPagination() {
// 先清除旧的分页控件
this.paginationEl?.remove();
// 创建新的分页控件并保存引用
this.paginationEl = this.contentContainer.createEl("div", {
cls: "pagination",
});
const prevBtn = this.paginationEl.createEl("button", {
text: i18n.t("common.previousPage"),
});
prevBtn.disabled = this.currentPage <= 1;
prevBtn.addEventListener("click", () => {
if (this.currentPage > 1) {
this.loadPage(this.currentPage - 1);
}
});
this.paginationEl.createEl("span", {
text: i18n.t("common.pageOf", {
page: this.currentPage,
total: this.totalPages,
}),
});
const nextBtn = this.paginationEl.createEl("button", {
text: i18n.t("common.nextPage"),
});
nextBtn.disabled = this.currentPage >= this.totalPages;
nextBtn.addEventListener("click", () => {
if (this.currentPage < this.totalPages) {
this.loadPage(this.currentPage + 1);
}
});
}
onClose() {
const { contentEl } = this;
contentEl.empty();
}
}

520
view/category_tree.ts Normal file

File diff suppressed because it is too large Load Diff

133
view/comment_modal.ts Normal file
View File

@@ -0,0 +1,133 @@
import { App, Modal, Notice } from "obsidian";
import i18n from "../utils/i18n";
export interface CommentModalOptions {
title: string;
initial?: string;
placeholder?: string;
submitText: string;
onSubmit: (text: string) => Promise<void> | void;
}
/**
* 评论回复 / 编辑弹窗
*/
export class CommentModal extends Modal {
private options: CommentModalOptions;
private submitting = false;
constructor(app: App, options: CommentModalOptions) {
super(app);
this.options = options;
}
onOpen() {
const { contentEl } = this;
contentEl.empty();
contentEl.createEl("h2", { text: this.options.title });
const textarea = contentEl.createEl("textarea", {
cls: "otm-textarea",
attr: {
rows: "6",
placeholder: this.options.placeholder ?? "",
},
});
textarea.value = this.options.initial ?? "";
const footer = contentEl.createDiv({ cls: "otm-modal-actions" });
const submitButton = footer.createEl("button", {
cls: "mod-cta",
text: this.options.submitText,
});
submitButton.addEventListener("click", async () => {
if (this.submitting) return;
const text = textarea.value.trim();
if (!text) {
new Notice(i18n.t("manager.textRequired"));
return;
}
this.submitting = true;
submitButton.disabled = true;
try {
await this.options.onSubmit(text);
this.close();
} catch (error) {
console.error("提交评论操作失败", error);
} finally {
this.submitting = false;
submitButton.disabled = false;
}
});
const cancelButton = footer.createEl("button", {
text: i18n.t("manager.cancel"),
});
cancelButton.addEventListener("click", () => this.close());
textarea.focus();
}
onClose() {
this.contentEl.empty();
}
}
/**
* 通用确认弹窗(用于删除这类不可恢复操作)
*/
export class ConfirmModal extends Modal {
private titleText: string;
private message: string;
private onConfirm: () => Promise<void> | void;
constructor(
app: App,
titleText: string,
message: string,
onConfirm: () => Promise<void> | void
) {
super(app);
this.titleText = titleText;
this.message = message;
this.onConfirm = onConfirm;
}
onOpen() {
const { contentEl } = this;
contentEl.empty();
contentEl.createEl("h2", { text: this.titleText });
contentEl.createEl("p", { text: this.message });
const footer = contentEl.createDiv({ cls: "otm-modal-actions" });
const confirmButton = footer.createEl("button", {
cls: "mod-warning",
text: i18n.t("manager.confirm"),
});
confirmButton.addEventListener("click", async () => {
confirmButton.disabled = true;
try {
await this.onConfirm();
this.close();
} catch (error) {
console.error("确认操作失败", error);
confirmButton.disabled = false;
}
});
const cancelButton = footer.createEl("button", {
text: i18n.t("manager.cancel"),
});
cancelButton.addEventListener("click", () => this.close());
}
onClose() {
this.contentEl.empty();
}
}

182
view/meta_edit_modal.ts Normal file
View File

@@ -0,0 +1,182 @@
import { App, Modal, Notice, Setting } from "obsidian";
import { HttpUtils } from "../utils/request";
import i18n from "../utils/i18n";
export type MetaType = "category" | "tag";
/**
* 分类 / 标签的新增与编辑弹窗
*
* meta 为 null 时是新增,否则是编辑已有项。
*/
export class MetaEditModal extends Modal {
private type: MetaType;
private meta: any | null;
private onSaved: () => void | Promise<void>;
private nameValue: string;
private slugValue: string;
private descriptionValue: string;
private parentValue: string;
private categories: any[] = [];
private saving = false;
constructor(
app: App,
type: MetaType,
meta: any | null,
onSaved: () => void | Promise<void>
) {
super(app);
this.type = type;
this.meta = meta;
this.onSaved = onSaved;
this.nameValue = meta?.name ?? "";
this.slugValue = meta?.slug ?? "";
this.descriptionValue = meta?.description ?? "";
this.parentValue = String(meta?.parent ?? 0);
}
async onOpen() {
const { contentEl } = this;
contentEl.empty();
const isEdit = !!this.meta;
const isCategory = this.type === "category";
contentEl.createEl("h2", {
text: i18n.t(
isEdit
? isCategory
? "manager.editCategoryTitle"
: "manager.editTagTitle"
: isCategory
? "manager.newCategoryTitle"
: "manager.newTagTitle"
),
});
new Setting(contentEl)
.setName(i18n.t("manager.metaName"))
.addText((text) =>
text.setValue(this.nameValue).onChange((value) => {
this.nameValue = value;
})
);
new Setting(contentEl)
.setName(i18n.t("manager.metaSlug"))
.setDesc(i18n.t("manager.metaSlugDesc"))
.addText((text) =>
text
.setValue(this.slugValue)
.setPlaceholder(this.meta?.slug ?? "")
.onChange((value) => {
this.slugValue = value;
})
);
new Setting(contentEl)
.setName(i18n.t("manager.metaDescription"))
.addTextArea((area) =>
area.setValue(this.descriptionValue).onChange((value) => {
this.descriptionValue = value;
})
);
if (isCategory) {
await this.loadCategories();
if (this.categories.length > 0) {
new Setting(contentEl)
.setName(i18n.t("manager.metaParent"))
.addDropdown((dropdown) => {
dropdown.addOption("0", i18n.t("manager.metaParentNone"));
for (const category of this.categories) {
if (
this.meta &&
Number(category.mid) === Number(this.meta.mid)
) {
// 不能把自己设成自己的父级
continue;
}
dropdown.addOption(
String(category.mid),
category.name
);
}
dropdown.setValue(this.parentValue);
dropdown.onChange((value) => {
this.parentValue = value;
});
});
}
}
const footer = contentEl.createDiv({ cls: "otm-modal-actions" });
const saveButton = footer.createEl("button", {
cls: "mod-cta",
text: i18n.t("manager.save"),
});
saveButton.addEventListener("click", () => this.save(saveButton));
const cancelButton = footer.createEl("button", {
text: i18n.t("manager.cancel"),
});
cancelButton.addEventListener("click", () => this.close());
}
private async loadCategories() {
try {
const response = await HttpUtils.get("/categories", {}, true);
this.categories = response?.data ?? [];
} catch (error) {
this.categories = [];
}
}
private async save(button: HTMLButtonElement) {
if (this.saving) return;
const name = this.nameValue.trim();
if (!name) {
new Notice(i18n.t("manager.nameRequired"));
return;
}
this.saving = true;
button.disabled = true;
try {
if (this.meta) {
await HttpUtils.post("/editMeta", {
mid: this.meta.mid,
name,
slug: this.slugValue.trim(),
description: this.descriptionValue,
parent: Number(this.parentValue) || 0,
});
} else {
await HttpUtils.post("/addMetas", {
name,
type: this.type,
slug: this.slugValue.trim(),
description: this.descriptionValue,
parent: Number(this.parentValue) || 0,
});
}
new Notice(i18n.t("manager.saved"));
await this.onSaved();
this.close();
} catch (error) {
console.error("保存分类/标签失败", error);
} finally {
this.saving = false;
button.disabled = false;
}
}
onClose() {
this.contentEl.empty();
}
}

943
view/push.ts Normal file

File diff suppressed because it is too large Load Diff

1562
view/site_manager.ts Normal file

File diff suppressed because it is too large Load Diff