Files
Obsidian-To-Typecho/view/site_manager.ts

1563 lines
43 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { ItemView, Menu, Notice, WorkspaceLeaf, setIcon } from "obsidian";
import { Util } from "../utils/util";
import i18n from "../utils/i18n";
import { HttpUtils } from "../utils/request";
import { getActiveSite, getSettings, getSite, getSites, setActiveSite } from "../main";
import { MetaEditModal } from "./meta_edit_modal";
import type { MetaType } from "./meta_edit_modal";
import { CommentModal, ConfirmModal } from "./comment_modal";
import { fuzzyScore } from "./category_tree";
import { createPostDraft, importPostAsMarkdown } from "../utils/post_import";
export const VIEW_TYPE = "obsidian-to-typecho-manager";
type CommentFilter = "all" | "pending" | "unreplied";
type TabKey = "posts" | "categories" | "tags" | "comments";
type MetaTab = "categories" | "tags";
interface TabDef {
key: TabKey;
labelKey: string;
}
/** 一个面板的公共骨架引用 */
interface PanelParts {
panelEl: HTMLElement;
headerEl: HTMLElement;
countEl: HTMLElement;
actionsEl: HTMLElement;
scrollEl: HTMLElement;
footerEl: HTMLElement;
}
/**
* 站点管理侧边栏
*
* 顶部四个 tab 切换:文章 / 分类 / 标签 / 评论。
* 每个 tab 独立滚动区、独立分页,互不挤压;数据按需加载,切过去才请求。
*/
export class SiteManagerView extends ItemView {
private static readonly TABS: TabDef[] = [
{ key: "posts", labelKey: "manager.posts" },
{ key: "categories", labelKey: "manager.categories" },
{ key: "tags", labelKey: "manager.tags" },
{ key: "comments", labelKey: "manager.comments" },
];
private activeTab: TabKey = "posts";
// 文章分页
private postPage = 1;
private postPageSize = 20;
private postsLoading = false;
private postsLoaded = false;
// 文章搜索:输入时先本地模糊过滤当前缓存,停手 300ms 再全站搜一次
private postQuery = "";
private postCache: any[] = [];
private postSeq = 0;
private postSearchTimer: number | null = null;
private postSearchInput: HTMLInputElement | null = null;
private postSearchClearEl: HTMLElement | null = null;
// 评论分页与筛选
private commentPage = 1;
private commentPageSize = 20;
private commentFilter: CommentFilter = "all";
private commentsLoading = false;
private commentsLoaded = false;
// 分类标签(一次拉全量,不分页)
private metasLoading = false;
private metasLoaded = false;
private tabButtons = new Map<TabKey, HTMLElement>();
private tabCountEls = new Map<TabKey, HTMLElement>();
private panels = new Map<TabKey, PanelParts>();
private pendingBadgeEl: HTMLElement | null = null;
// 各 tab 的统计数量(tab 标题后的小徽章 + 顶部待审核红字)
private postsTotal = 0;
private commentsTotal = 0;
private pendingComments = 0;
private postListEl: HTMLElement;
private categoryListEl: HTMLElement;
private tagListEl: HTMLElement;
private commentListEl: HTMLElement;
private commentTabsEl: HTMLElement;
private commentTabListEl: HTMLElement;
private commentCountEl: HTMLElement;
private categories: any[] = [];
private tags: any[] = [];
constructor(leaf: WorkspaceLeaf) {
super(leaf);
// 条数来自设置,视图创建时就定下来
this.postPageSize = this.pageSize();
this.commentPageSize = this.postPageSize;
}
getViewType(): string {
return VIEW_TYPE;
}
getDisplayText(): string {
return i18n.t("manager.title");
}
getIcon(): string {
return "obsidian-to-typecho";
}
async onOpen() {
await this.render();
// 窗口缩放 / 状态栏显隐 / 分栏拖动后重新量一次可视高度
this.registerDomEvent(window, "resize", () => this.updateBottomInset());
this.registerEvent(
this.app.workspace.on("resize", () => this.updateBottomInset())
);
}
/** 设置里改了每页条数后调用:同步到当前视图并重载当前 tab */
async reloadWithSettings() {
this.postPageSize = this.pageSize();
this.commentPageSize = this.postPageSize;
this.postPage = 1;
this.commentPage = 1;
this.postsLoaded = false;
this.commentsLoaded = false;
await this.showTab(this.activeTab, true);
void this.refreshCounts();
}
/**
* 定时自动刷新:只拉数据与数量,不重建 DOM,也不重置分页/搜索/筛选。
* 和 reloadWithSettings 的区别:后者是「每页条数改了」,强制回到第 1 页;
* 定时刷新要保持用户正在看的位置和条件不变,避免看着看着被弹回第一页。
*/
async autoRefresh() {
const isMetaTab =
this.activeTab === "categories" || this.activeTab === "tags";
// 徽章(总数、待审核红字)每次都更新;分类/标签 tab 由本方法自己加载,
// 避免 refreshCounts 里的 loadMetas 抢跑、在还原滚动位置后又重绘列表
void this.refreshCounts(!isMetaTab);
const parts = this.panels.get(this.activeTab);
const scrollEl = parts?.scrollEl;
const savedTop = scrollEl?.scrollTop ?? 0;
try {
if (this.activeTab === "posts") {
// 正在搜索框里打字时不打扰,交给搜索自己的防抖逻辑
if (document.activeElement !== this.postSearchInput && !this.postsLoading) {
await this.loadPosts(this.postPage);
}
} else if (this.activeTab === "comments") {
if (!this.commentsLoading) {
await this.loadComments(this.commentPage);
}
} else if (
(this.activeTab === "categories" || this.activeTab === "tags") &&
!this.metasLoading
) {
await this.loadMetas();
}
} finally {
// 列表被整体替换时浏览器会把滚动位置归零,刷新后还原
if (scrollEl && scrollEl.isConnected) scrollEl.scrollTop = savedTop;
}
}
/** 每页条数,取自插件设置,脏数据回落到 20 */
private pageSize(): number {
const value = Number(getSettings()?.managerPageSize);
if (!Number.isFinite(value) || value < 5) return 20;
return Math.min(200, Math.round(value));
}
async onClose() {
// 无需清理,视图销毁时 Obsidian 会回收 DOM
}
/**
* 整体布局:工具栏 → 主 tab → 面板区
*/
async render() {
const container = this.contentEl;
container.empty();
container.addClass("otm-container");
this.tabButtons.clear();
this.tabCountEls.clear();
this.panels.clear();
this.pendingBadgeEl = null;
this.postsLoaded = false;
this.metasLoaded = false;
this.commentsLoaded = false;
// 搜索状态跟着旧 DOM 一起作废,否则新面板里是空输入框、查询词却还在
this.postQuery = "";
this.postCache = [];
this.postSearchInput = null;
this.postSearchClearEl = null;
if (this.postSearchTimer !== null) {
window.clearTimeout(this.postSearchTimer);
this.postSearchTimer = null;
}
// 设置里可能刚改过每页条数
this.postPageSize = this.pageSize();
this.commentPageSize = this.postPageSize;
this.renderToolbar(container);
const tabsEl = container.createDiv({ cls: "otm-main-tabs" });
this.buildTabButtons(tabsEl);
const panelsEl = container.createDiv({ cls: "otm-panels" });
this.buildPostsPanel(panelsEl);
this.buildMetaPanel(panelsEl, "categories");
this.buildMetaPanel(panelsEl, "tags");
this.buildCommentsPanel(panelsEl);
this.syncGutter();
this.updateBottomInset();
await this.showTab(this.activeTab);
// 数量统计单独跑,不挡首屏渲染
void this.refreshCounts();
}
/**
* 底部分页栏会被 Obsidian 状态栏压住。
*
* 状态栏高度随主题/是否显示而变,写死像素不靠谱;而且部分主题下
* `height:100%` 解析不到(父级高度是 auto),容器会一直长到状态栏下面,
* 靠 padding 收不回来。这里直接量出「到状态栏顶边还剩多少」,把高度钉死。
*/
private updateBottomInset() {
const container = this.contentEl;
if (!container) return;
const rect = container.getBoundingClientRect();
// 隐藏或未挂载时量不出有效尺寸,跳过
if (rect.height <= 0 || rect.width <= 0) return;
const available = Math.round(this.visibleBottom() - rect.top);
if (available < 120) return;
container.style.setProperty("height", `${available}px`, "important");
container.style.setProperty("padding-bottom", "8px", "important");
}
/** 真正可见的下边界:窗口底边与状态栏顶边取更靠上的那个 */
private visibleBottom(): number {
let limit = window.innerHeight;
const statusBar = document.querySelector(".status-bar");
if (statusBar instanceof HTMLElement) {
const barRect = statusBar.getBoundingClientRect();
// 只在状态栏确实位于窗口底部时当边界,隐藏或贴顶的情况忽略
if (barRect.height > 0 && barRect.top > 0) {
limit = Math.min(limit, barRect.top);
}
}
return limit;
}
/**
* 顶部:站点选择器 · 待审核评论数 · 刷新(只刷新当前 tab)
*
* 三列网格,左右两列等宽,中间那格自然就落在正中间。
*/
private renderToolbar(parent: HTMLElement) {
const toolbar = parent.createDiv({ cls: "otm-toolbar" });
// 站点名和切换箭头做成一个整体,点哪儿都能下拉,不再是一个孤零零的小图标
const siteGroup = toolbar.createDiv({ cls: "otm-toolbar-site" });
const site = getActiveSite();
const switcher = siteGroup.createDiv({
cls: "otm-site-switcher",
attr: { title: site?.Host || "" },
});
switcher.createSpan({
cls: "otm-site-name",
text: site?.name || i18n.t("setting.unnamedSite"),
});
const chevron = switcher.createSpan({ cls: "otm-site-chevron" });
setIcon(chevron, "chevron-down");
switcher.addEventListener("click", (evt) => {
evt.stopPropagation();
this.openSiteMenu(evt);
});
// 待审核评论数:站点选择与刷新之间居中,带文案,有数量时为红色
this.pendingBadgeEl = toolbar.createSpan({
cls: "otm-pending-badge is-empty",
text: i18n.t("manager.pendingComments", { count: 0 }),
});
this.pendingBadgeEl.addEventListener("click", () => {
this.commentFilter = "pending";
if (this.commentTabsEl) this.renderCommentTabs();
void this.showTab("comments", true);
});
const rightGroup = toolbar.createDiv({ cls: "otm-toolbar-right" });
const refreshButton = rightGroup.createEl("button", {
cls: "otm-icon-button",
attr: {
"aria-label": i18n.t("manager.refresh"),
title: i18n.t("manager.refresh"),
},
});
setIcon(refreshButton, "rotate-ccw");
refreshButton.addEventListener("click", async () => {
refreshButton.disabled = true;
try {
await this.showTab(this.activeTab, true);
new Notice(i18n.t("manager.refreshed"));
// 刷新时把各处数量一起更新
void this.refreshCounts();
} finally {
refreshButton.disabled = false;
}
});
}
/**
* 网站下拉菜单:列出所有站点,当前项打勾
*/
private openSiteMenu(evt: MouseEvent) {
const sites = getSites();
if (sites.length === 0) {
new Notice(i18n.t("manager.noSites"));
return;
}
const activeId = getActiveSite()?.id;
const menu = new Menu();
for (const site of sites) {
menu.addItem((item) => {
item.setTitle(site.name || i18n.t("setting.unnamedSite"))
.setChecked(site.id === activeId)
.onClick(() => {
void this.switchSite(site.id);
});
});
}
menu.showAtMouseEvent(evt);
}
/**
* 切换当前站点:写入配置 → 同步请求地址 → 丢弃旧数据 → 整面板重绘
*/
private async switchSite(siteId: string) {
if (getActiveSite()?.id === siteId) return;
const ok = await setActiveSite(siteId);
if (!ok) return;
const site = getSite(siteId);
if (site) HttpUtils.setCurrentSite(site.Host, site.Token);
// 旧站点的列表、分类、标签、分页位置全部作废
this.postsLoaded = false;
this.metasLoaded = false;
this.commentsLoaded = false;
this.categories = [];
this.tags = [];
this.postPage = 1;
this.commentPage = 1;
await this.render();
}
private buildTabButtons(parent: HTMLElement) {
for (const tab of SiteManagerView.TABS) {
const button = parent.createDiv({ cls: "otm-main-tab" });
button.createSpan({
cls: "otm-tab-label",
text: i18n.t(tab.labelKey),
});
const countEl = button.createSpan({
cls: "otm-tab-count is-hidden",
text: "0",
});
this.tabCountEls.set(tab.key, countEl);
button.addEventListener("click", () => {
void this.showTab(tab.key);
});
this.tabButtons.set(tab.key, button);
}
}
/**
* 更新 tab 标题后的数量徽章
*/
private setTabCount(key: TabKey, count: number) {
const el = this.tabCountEls.get(key);
if (!el) return;
const value = Number.isFinite(count) && count > 0 ? count : 0;
el.setText(String(value));
el.removeClass("is-hidden");
el.setAttribute(
"title",
i18n.t("manager.totalItems", { count: value })
);
}
/**
* 顶部待审核红字
*/
private updatePendingBadge() {
if (!this.pendingBadgeEl) return;
const count = this.pendingComments;
this.pendingBadgeEl.setText(
i18n.t("manager.pendingComments", { count })
);
// 有数字才红,0 条时退成灰色,不抢视线
this.pendingBadgeEl.toggleClass("is-empty", count <= 0);
this.pendingBadgeEl.setAttribute(
"title",
i18n.t("manager.pendingCommentsTitle", { count })
);
}
/**
* 打开面板时补一次全部数量:分类/标签走 loadMetas(顺带预热列表),
* 评论总数与待审核数单独查一次(pageSize=1,只要 count)
*/
private async refreshCounts(includeMetas = true) {
if (includeMetas) void this.loadMetas();
// 默认打开文章 tab 时数量已由 loadPosts 填好,这里只补没加载过的情况
if (!this.postsLoaded) void this.refreshPostCount();
await this.refreshCommentCounts();
}
private async refreshPostCount() {
try {
const response = await HttpUtils.get(
"/posts?page=1&pageSize=1",
{},
true
);
const total = Number(response?.data?.count) || 0;
this.postsTotal = total;
this.setTabCount("posts", total);
} catch (error) {
console.error("获取文章总数失败", error);
}
}
private async refreshCommentCounts() {
try {
const [allResponse, pendingResponse] = await Promise.all([
HttpUtils.get(
"/manageComments?filter=all&page=1&pageSize=1",
{},
true
),
HttpUtils.get(
"/manageComments?filter=pending&page=1&pageSize=1",
{},
true
),
]);
this.commentsTotal = Number(allResponse?.data?.count) || 0;
this.pendingComments = Number(pendingResponse?.data?.count) || 0;
this.setTabCount("comments", this.commentsTotal);
this.updatePendingBadge();
} catch (error) {
console.error("获取评论统计失败", error);
}
}
/**
* 切换 tab:切 class + 按需拉数据
*/
private async showTab(key: TabKey, force = false) {
this.activeTab = key;
this.tabButtons.forEach((button, tabKey) =>
button.toggleClass("is-active", tabKey === key)
);
this.panels.forEach((parts, tabKey) =>
parts.panelEl.toggleClass("is-active", tabKey === key)
);
if (key === "posts") {
if (force || !this.postsLoaded) await this.loadPosts(1);
} else if (key === "categories" || key === "tags") {
if (force || !this.metasLoaded) await this.loadMetas();
} else if (key === "comments") {
if (force || !this.commentsLoaded) await this.loadComments(1);
}
// 分页栏出现/消失会改变布局,量一次可视高度
this.syncGutter();
this.updateBottomInset();
}
/**
* 量出滚动条实际占用的宽度,写进 CSS 变量 --otm-gutter。
*
* 面板头、工具栏、列表项的右内边距都按这个变量算,
* 所以不管主题/平台把滚动条做成多宽,右侧图标永远落在同一条竖线上。
*/
private syncGutter() {
const el = this.panels.get(this.activeTab)?.scrollEl;
if (!el || el.offsetWidth <= 0) return;
const gutter = Math.max(0, el.offsetWidth - el.clientWidth);
this.contentEl.style.setProperty("--otm-gutter", `${gutter}px`);
}
/**
* 面板骨架:header(计数 + 操作)+ 滚动区 + 分页栏
*/
private createPanel(parent: HTMLElement, key: TabKey): PanelParts {
const panelEl = parent.createDiv({ cls: "otm-panel" });
if (key === this.activeTab) panelEl.addClass("is-active");
const headerEl = panelEl.createDiv({ cls: "otm-panel-header" });
const countEl = headerEl.createDiv({ cls: "otm-panel-count" });
const actionsEl = headerEl.createDiv({ cls: "otm-panel-actions" });
const scrollEl = panelEl.createDiv({ cls: "otm-scroll" });
const footerEl = panelEl.createDiv({
cls: "otm-panel-footer is-hidden",
});
const parts: PanelParts = {
panelEl,
headerEl,
countEl,
actionsEl,
scrollEl,
footerEl,
};
this.panels.set(key, parts);
return parts;
}
private addHeaderAction(
container: HTMLElement,
icon: string,
title: string,
onClick: () => void
) {
const button = container.createEl("button", {
cls: "otm-icon-button",
attr: { "aria-label": title, title },
});
setIcon(button, icon);
button.addEventListener("click", (evt) => {
evt.stopPropagation();
onClick();
});
}
// ==================== 文章 ====================
private buildPostsPanel(parent: HTMLElement) {
const parts = this.createPanel(parent, "posts");
// 新增 = 在本地新建一篇空笔记,写完再从笔记里点发布
this.addHeaderAction(
parts.actionsEl,
"plus",
i18n.t("manager.newPost"),
() => {
void createPostDraft(this.app);
}
);
// 搜索行夹在「统计 + 新增」与列表之间:不随列表滚动
this.buildPostSearchRow(parts);
this.postListEl = parts.scrollEl.createDiv({ cls: "otm-list" });
}
/**
* 文章搜索行:输入框 + 清除按钮
*
* 输入即过滤(本地子序列匹配,几毫秒出结果),停手 300ms 再走服务端
* `/posts?filterType=search` 做全站搜索——本地只覆盖当前页,
* 服务端才是「所有文章」。
*/
private buildPostSearchRow(parts: PanelParts) {
const row = parts.panelEl.createDiv({ cls: "otm-search" });
parts.panelEl.insertBefore(row, parts.scrollEl);
const input = row.createEl("input", {
type: "text",
cls: "otm-search-input",
attr: {
placeholder: i18n.t("manager.searchPostsPlaceholder"),
spellcheck: "false",
"aria-label": i18n.t("manager.searchPostsPlaceholder"),
},
});
this.postSearchInput = input;
const clearEl = row.createEl("button", {
cls: "otm-icon-button otm-search-clear is-hidden",
attr: {
"aria-label": i18n.t("manager.clearSearch"),
title: i18n.t("manager.clearSearch"),
},
});
setIcon(clearEl, "x");
this.postSearchClearEl = clearEl;
const apply = (value: string) => {
this.postQuery = value.trim();
clearEl.toggleClass("is-hidden", this.postQuery === "");
// 本地过滤结果是「当前页里的匹配」,分页栏在这里没意义,先收起来
const footer = this.panels.get("posts")?.footerEl;
if (footer) {
footer.empty();
footer.addClass("is-hidden");
}
// 先本地过滤:不用等网络,输入即见结果
const matched = this.filterPosts(this.postCache, this.postQuery);
this.renderPostItems(
matched,
this.postQuery
? i18n.t("manager.searchNoMatch")
: i18n.t("common.noDataFound"),
this.postQuery
);
// 统计先按本地匹配数走,服务端搜完会换成全站的实际条数
const countEl = this.panels.get("posts")?.countEl;
if (countEl) {
const text = this.postQuery
? i18n.t("manager.searchCount", { count: matched.length })
: i18n.t("manager.totalItems", { count: this.postsTotal });
countEl.setText(text);
}
this.schedulePostSearch();
};
input.addEventListener("input", () => apply(input.value));
input.addEventListener("keydown", (evt) => {
if (evt.key === "Escape") {
evt.preventDefault();
input.value = "";
apply("");
} else if (evt.key === "Enter") {
evt.preventDefault();
// 回车立刻搜,不等防抖
if (this.postSearchTimer !== null) {
window.clearTimeout(this.postSearchTimer);
this.postSearchTimer = null;
}
void this.loadPosts(1);
}
});
clearEl.addEventListener("click", () => {
input.value = "";
apply("");
input.focus();
});
}
/** 防抖:停止输入 300ms 后再请求服务端 */
private schedulePostSearch() {
if (this.postSearchTimer !== null) {
window.clearTimeout(this.postSearchTimer);
}
this.postSearchTimer = window.setTimeout(() => {
this.postSearchTimer = null;
void this.loadPosts(1);
}, 300);
}
/**
* 本地模糊过滤
*
* 标题、缩略名、cid 都参与匹配:用户经常直接搜「416」找那篇文章。
* 命中多项时按相关度排序,标题匹配优先。
*/
private filterPosts(list: any[], query: string): any[] {
const keyword = query.trim();
if (!keyword) return list;
// 用户可能照着界面上的 #416 输入,带不带井号都算命中
const idKey = keyword.replace(/^#/, "");
const scored = list
.map((post) => {
const titleScore = fuzzyScore(post?.title || "", keyword);
const slugScore = fuzzyScore(post?.slug || "", keyword);
const idScore = String(post?.cid ?? "") === idKey ? 70 : -1;
const score = Math.max(titleScore, slugScore, idScore);
return { post, score };
})
.filter((entry) => entry.score >= 0)
.sort((a, b) => b.score - a.score)
.map((entry) => entry.post);
return scored;
}
private async loadPosts(targetPage: number) {
// 搜索会连续触发,用序号丢弃过期响应(先发后到的结果不能覆盖新结果)
const seq = ++this.postSeq;
this.postsLoading = true;
this.postPage = targetPage;
const parts = this.panels.get("posts");
if (parts) {
parts.footerEl.empty();
parts.footerEl.addClass("is-hidden");
}
// 只在列表还空着时占个 loading,搜索重载时保留旧结果,避免闪白
if (this.postListEl && this.postListEl.childElementCount === 0) {
this.postListEl.createDiv({
cls: "otm-loading",
text: i18n.t("common.loading"),
});
}
const query = this.postQuery;
let url = `/posts?page=${this.postPage}&pageSize=${this.postPageSize}`;
if (query) {
url += `&filterType=search&filterSlug=${encodeURIComponent(query)}`;
}
try {
const response = await HttpUtils.get(url, {}, true);
if (seq !== this.postSeq) return;
const data = response?.data ?? {};
const list: any[] = data.dataSet ?? [];
const pages = Number(data.pages) || 1;
const total = Number(data.count) || list.length;
// 缓存只存「无关键词」的那份列表:清空搜索时能立刻恢复原样,
// 也不会被搜索结果覆盖掉,导致再输入时本地过滤只剩上次搜到的几篇
if (!query) this.postCache = list;
if (parts) {
parts.countEl.setText(
query
? i18n.t("manager.searchCount", { count: total })
: i18n.t("manager.totalItems", { count: total })
);
}
if (!query) {
this.postsTotal = total;
this.setTabCount("posts", total);
}
this.renderPostItems(
list,
query ? i18n.t("manager.searchNoMatch") : i18n.t("common.noDataFound"),
query
);
this.postsLoaded = true;
if (parts) {
this.renderPager(parts.footerEl, this.postPage, pages, (page) => {
void this.loadPosts(page);
});
}
} catch (error) {
if (seq === this.postSeq) {
this.renderPostItems(
[],
i18n.t("common.errorOccurred"),
query
);
}
console.error("获取文章列表失败", error);
} finally {
if (seq === this.postSeq) this.postsLoading = false;
}
}
/** 渲染文章列表(loading 占位由调用方清掉) */
private renderPostItems(list: any[], emptyText: string, query = "") {
if (!this.postListEl) return;
this.postListEl.empty();
if (!list || list.length === 0) {
this.postListEl.createDiv({ cls: "otm-empty", text: emptyText });
return;
}
for (const post of list) {
this.buildPostItem(this.postListEl, post, query);
}
}
private buildPostItem(parent: HTMLElement, post: any, query = "") {
const item = parent.createDiv({ cls: "otm-post-item" });
const main = item.createDiv({ cls: "otm-post-main" });
const titleEl = main.createDiv({ cls: "otm-post-title" });
const titleText = post.title || i18n.t("manager.untitled");
if (post.permalink) {
const link = titleEl.createEl("a", {
href: post.permalink,
attr: { target: "_blank", rel: "noopener" },
});
this.renderHighlighted(link, titleText, query);
} else {
this.renderHighlighted(titleEl, titleText, query);
}
// 日期 · 评论数 · ID
// 评论数为 0 时不显示;ID 一直显示,方便和站点后台、日志里的编号对号
const metaRow = main.createDiv({ cls: "otm-post-meta" });
const dateText = this.formatPostDate(post);
const commentCount = Number(post.commentsNum) || 0;
if (dateText) {
const dateEl = metaRow.createSpan({ cls: "otm-post-date" });
setIcon(dateEl.createSpan({ cls: "otm-post-meta-icon" }), "calendar");
dateEl.createSpan({
cls: "otm-post-date-text",
text: dateText,
});
}
if (commentCount > 0) {
const countEl = metaRow.createSpan({
cls: dateText
? "otm-post-comments has-separator"
: "otm-post-comments",
attr: {
title: i18n.t("manager.commentCount", {
count: commentCount,
}),
},
});
setIcon(
countEl.createSpan({ cls: "otm-post-meta-icon" }),
"message-square"
);
countEl.createSpan({
cls: "otm-post-comments-count",
text: String(commentCount),
});
}
if (post.cid) {
// ID 前面用图标(与日期、评论数的图标同一套),不再写裸 "#"
const idText = String(post.cid);
const idEl = metaRow.createSpan({
cls:
dateText || commentCount > 0
? "otm-id otm-post-id has-separator"
: "otm-id otm-post-id",
attr: {
title: i18n.t("manager.copyId", { id: idText }),
},
});
setIcon(
idEl.createSpan({ cls: "otm-post-meta-icon" }),
"id-card"
);
idEl.appendText(idText);
idEl.addEventListener("click", (evt) => {
evt.stopPropagation();
evt.preventDefault();
this.copyId(post.cid);
});
}
const actions = item.createDiv({ cls: "otm-item-actions" });
const editButton = actions.createEl("button", {
cls: "otm-icon-button",
attr: {
"aria-label": i18n.t("manager.edit"),
title: i18n.t("manager.edit"),
},
});
setIcon(editButton, "pencil");
editButton.addEventListener("click", async (evt) => {
evt.stopPropagation();
editButton.disabled = true;
try {
await importPostAsMarkdown(this.app, Number(post.cid));
} catch (error) {
console.error("下载文章失败", error);
} finally {
editButton.disabled = false;
}
});
}
private formatPostDate(post: any): string {
const year = Number(post.year);
const month = Number(post.month);
const day = Number(post.day);
if (!year || !month || !day) return "";
return `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(
2,
"0"
)}`;
}
/**
* 评论所属文章的链接
*
* 服务端 2.0.6 起在评论列表里直接返回 postPermalink(已按站点的固定链接
* 规则拼好,含 {category}/{year} 这类自定义路由)。老版本服务端没有这个
* 字段时退到 postUrl / permalink;都拿不到就不显示成链接,只显示标题。
* 相对路径必须补成绝对地址,否则点开会被当成库内文件。
*/
private commentPostUrl(comment: any): string {
const raw = String(
comment?.postPermalink || comment?.postUrl || comment?.permalink || ""
).trim();
if (!raw || raw === "#" || raw.includes("{")) return "";
if (/^https?:\/\//i.test(raw)) return raw;
let root = "";
try {
root = Util.url.extractDomain(HttpUtils.getCurrentHost());
} catch {
return "";
}
if (!root) return "";
return root.replace(/\/+$/, "") + (raw.startsWith("/") ? raw : "/" + raw);
}
/**
* 标题里命中搜索词的那截标出来
*
* 只标「直接包含」的情况;本地模糊用的是子序列匹配,字符位置对不上就没法标,
* 那种情况整条照常显示(结果仍然是对的)。
*/
private renderHighlighted(parent: HTMLElement, text: string, query: string) {
const keyword = query.trim();
if (!keyword) {
parent.setText(text);
return;
}
const index = text.toLowerCase().indexOf(keyword.toLowerCase());
if (index < 0) {
parent.setText(text);
return;
}
if (index > 0) parent.createSpan({ text: text.slice(0, index) });
parent.createSpan({
cls: "otm-search-hit",
text: text.slice(index, index + keyword.length),
});
const rest = text.slice(index + keyword.length);
if (rest) parent.createSpan({ text: rest });
}
/** 点 ID 复制,方便贴到后台地址栏或日志里查 */
private copyId(rawId: any) {
const id = String(rawId ?? "").trim();
if (!id) return;
try {
const textarea = document.createElement("textarea");
textarea.value = id;
textarea.style.position = "absolute";
textarea.style.left = "-9999px";
document.body.appendChild(textarea);
textarea.select();
document.execCommand("copy");
document.body.removeChild(textarea);
new Notice(i18n.t("manager.idCopied", { id }));
} catch (error) {
console.error("复制 ID 失败", error);
}
}
// ==================== 分类 / 标签 ====================
private buildMetaPanel(parent: HTMLElement, key: MetaTab) {
const isCategory = key === "categories";
const { actionsEl, scrollEl } = this.createPanel(parent, key);
this.addHeaderAction(
actionsEl,
"plus",
isCategory ? i18n.t("manager.newCategory") : i18n.t("manager.newTag"),
() => {
const type: MetaType = isCategory ? "category" : "tag";
new MetaEditModal(this.app, type, null, () => {
void this.loadMetas();
}).open();
}
);
const list = scrollEl.createDiv({ cls: "otm-list" });
if (isCategory) {
this.categoryListEl = list;
} else {
this.tagListEl = list;
}
}
private async loadMetas() {
if (this.metasLoading) return;
this.metasLoading = true;
try {
const [categoryResponse, tagResponse] = await Promise.all([
HttpUtils.get("/categories", {}, true),
HttpUtils.get("/tags", {}, true),
]);
this.categories = categoryResponse?.data ?? [];
this.tags = tagResponse?.data ?? [];
this.metasLoaded = true;
} catch (error) {
this.categories = [];
this.tags = [];
console.error("获取分类/标签失败", error);
} finally {
this.metasLoading = false;
}
this.renderMetaList(this.categoryListEl, this.categories, "category");
this.renderMetaList(this.tagListEl, this.tags, "tag");
const categoryParts = this.panels.get("categories");
if (categoryParts) {
categoryParts.countEl.setText(
i18n.t("manager.totalItems", { count: this.categories.length })
);
}
const tagParts = this.panels.get("tags");
if (tagParts) {
tagParts.countEl.setText(
i18n.t("manager.totalItems", { count: this.tags.length })
);
}
this.setTabCount("categories", this.categories.length);
this.setTabCount("tags", this.tags.length);
}
private renderMetaList(
container: HTMLElement,
list: any[],
type: MetaType
) {
if (!container) return;
container.empty();
if (!list || list.length === 0) {
container.createDiv({
cls: "otm-empty",
text: i18n.t("common.noDataFound"),
});
return;
}
const entries =
type === "category"
? this.flattenCategories(list)
: list.map((meta: any) => ({ meta, depth: 0 }));
for (const entry of entries) {
const item = container.createDiv({ cls: "otm-meta-item" });
// 缩进叠加在统一的内容边距上,层级越深越往右
if (entry.depth > 0) {
item.style.paddingLeft = `calc(var(--otm-pad, 10px) + ${
entry.depth * 14
}px)`;
}
const nameEl = item.createDiv({ cls: "otm-meta-name" });
nameEl.createSpan({ text: entry.meta.name });
nameEl.createSpan({
cls: "otm-badge",
text: String(entry.meta.count ?? 0),
});
const editButton = item.createEl("button", {
cls: "otm-icon-button",
attr: {
"aria-label": i18n.t("manager.edit"),
title: i18n.t("manager.edit"),
},
});
setIcon(editButton, "pencil");
const openEditor = () =>
new MetaEditModal(this.app, type, entry.meta, () =>
this.loadMetas()
).open();
item.addEventListener("click", openEditor);
editButton.addEventListener("click", (evt) => {
evt.stopPropagation();
openEditor();
});
}
}
/**
* 计算分类层级并排序,父分类紧跟在子分类之前
*/
private flattenCategories(list: any[]): { meta: any; depth: number }[] {
const byId = new Map<number, any>();
list.forEach((item) => byId.set(Number(item.mid), item));
const depthOf = (item: any, seen: Set<number>): number => {
const parentId = Number(item.parent);
if (!parentId || !byId.has(parentId) || seen.has(parentId)) {
return 0;
}
seen.add(parentId);
return 1 + depthOf(byId.get(parentId), seen);
};
const entries = list.map((meta) => ({
meta,
depth: depthOf(meta, new Set<number>([Number(meta.mid)])),
order: Number(meta.order) || 0,
}));
entries.sort((a, b) => {
if (a.order !== b.order) return a.order - b.order;
return String(a.meta.name).localeCompare(String(b.meta.name), "zh");
});
return entries.map(({ meta, depth }) => ({ meta, depth }));
}
// ==================== 评论 ====================
private buildCommentsPanel(parent: HTMLElement) {
const parts = this.createPanel(parent, "comments");
// 评论这块头部只有统计,没有操作按钮;整行省掉,
// 统计挪到筛选行最右侧,跟「全部/待审核/待回复」同一行
parts.headerEl.addClass("is-hidden");
this.commentTabsEl = parts.panelEl.createDiv({ cls: "otm-tabs" });
parts.panelEl.insertBefore(this.commentTabsEl, parts.scrollEl);
this.commentTabListEl = this.commentTabsEl.createDiv({
cls: "otm-tabs-list",
});
this.commentCountEl = this.commentTabsEl.createSpan({
cls: "otm-tabs-count",
});
this.renderCommentTabs();
this.commentListEl = parts.scrollEl.createDiv({ cls: "otm-list" });
}
private renderCommentTabs() {
this.commentTabListEl.empty();
const tabs: { key: CommentFilter; label: string }[] = [
{ key: "all", label: i18n.t("manager.commentAll") },
{ key: "pending", label: i18n.t("manager.commentPending") },
{ key: "unreplied", label: i18n.t("manager.commentUnreplied") },
];
for (const tab of tabs) {
const tabEl = this.commentTabListEl.createDiv({
cls:
"otm-tab" +
(tab.key === this.commentFilter ? " is-active" : ""),
text: tab.label,
});
tabEl.addEventListener("click", () => {
if (this.commentFilter === tab.key) return;
this.commentFilter = tab.key;
this.renderCommentTabs();
void this.loadComments(1);
});
}
}
private async loadComments(targetPage: number) {
if (this.commentsLoading) return;
this.commentsLoading = true;
this.commentPage = targetPage;
const parts = this.panels.get("comments");
this.commentListEl.empty();
if (parts) {
parts.footerEl.empty();
parts.footerEl.addClass("is-hidden");
}
const loadingEl = this.commentListEl.createDiv({
cls: "otm-loading",
text: i18n.t("common.loading"),
});
try {
const response = await HttpUtils.get(
`/manageComments?filter=${this.commentFilter}&page=${this.commentPage}&pageSize=${this.commentPageSize}`,
{},
true
);
loadingEl.remove();
const data = response?.data ?? {};
const list: any[] = data.dataSet ?? [];
const pages = Number(data.pages) || 1;
const total = Number(data.count) || list.length;
// 统计显示在筛选行最右侧
if (this.commentCountEl) {
this.commentCountEl.setText(
i18n.t("manager.totalItems", { count: total })
);
}
// 全部 → 评论总数;待审核 → 顶部红字;待回复只影响列表
if (this.commentFilter === "all") {
this.commentsTotal = total;
this.setTabCount("comments", total);
} else if (this.commentFilter === "pending") {
this.pendingComments = total;
this.updatePendingBadge();
}
if (list.length === 0) {
this.commentListEl.createDiv({
cls: "otm-empty",
text: i18n.t("manager.noComments"),
});
} else {
for (const comment of list) {
this.buildCommentItem(comment);
}
}
this.commentsLoaded = true;
if (parts) {
this.renderPager(
parts.footerEl,
this.commentPage,
pages,
(page) => {
void this.loadComments(page);
}
);
}
} catch (error) {
if (loadingEl.isConnected) {
loadingEl.setText(i18n.t("common.errorOccurred"));
}
console.error("获取评论列表失败", error);
} finally {
this.commentsLoading = false;
}
}
private buildCommentItem(comment: any) {
const item = this.commentListEl.createDiv({
cls: "otm-comment-item",
});
const main = item.createDiv({ cls: "otm-comment-main" });
// 第一行:评论内容
main.createDiv({
cls: "otm-comment-text",
text: this.plainText(comment.text),
});
// 第二行:评论人 · 时间 · ID
const meta = main.createDiv({ cls: "otm-comment-meta" });
const author = String(comment.author || "").trim();
if (author) {
meta.createSpan({ cls: "otm-comment-author", text: author });
}
const time = String(comment.createdAt || "").trim();
if (time) {
if (author) {
meta.createSpan({ cls: "otm-comment-dot", text: "·" });
}
meta.createSpan({ cls: "otm-comment-time", text: time });
}
if (comment.coid) {
// 评论 ID 只显示数字(不带 "#"),点一下复制
const idText = String(comment.coid);
if (author || time) {
meta.createSpan({ cls: "otm-comment-dot", text: "·" });
}
const idEl = meta.createSpan({
cls: "otm-id otm-comment-id",
text: idText,
attr: {
title: i18n.t("manager.copyId", { id: idText }),
},
});
idEl.addEventListener("click", (evt) => {
evt.stopPropagation();
this.copyId(comment.coid);
});
}
if (comment.status === "waiting") {
meta.createSpan({
cls: "otm-badge otm-badge-waiting",
text: i18n.t("manager.commentPending"),
});
}
// 第三行:这条评论挂在哪篇文章下(不加图标,整行都是标题;能拿到链接就点开文章页)
const postTitle = String(comment.postTitle || "").trim();
if (postTitle) {
const postRow = main.createDiv({ cls: "otm-comment-post" });
const postUrl = this.commentPostUrl(comment);
if (postUrl) {
const link = postRow.createEl("a", {
cls: "otm-comment-post-title is-link",
text: postTitle,
href: postUrl,
attr: {
target: "_blank",
rel: "noopener noreferrer",
title: i18n.t("manager.openPost", { title: postTitle }),
},
});
// 别让点击冒泡到评论项(评论项本身有点击行为),
// 链接交给 Obsidian 的默认处理(用系统浏览器打开)
link.addEventListener("click", (evt) => evt.stopPropagation());
} else {
postRow.createSpan({
cls: "otm-comment-post-title",
text: postTitle,
attr: { title: postTitle },
});
}
}
const actions = item.createDiv({ cls: "otm-comment-actions" });
if (this.commentFilter === "pending") {
this.addActionButton(actions, "check", i18n.t("manager.approve"), () => {
void this.runCommentAction(comment, "approve");
});
return;
}
if (this.commentFilter === "all") {
if (comment.status === "waiting") {
this.addActionButton(
actions,
"check",
i18n.t("manager.approve"),
() => {
void this.runCommentAction(comment, "approve");
}
);
}
this.addActionButton(
actions,
"trash",
i18n.t("manager.delete"),
() => this.confirmDelete(comment),
"mod-warning"
);
}
this.addActionButton(actions, "reply", i18n.t("manager.reply"), () =>
this.openReplyModal(comment)
);
if (this.commentFilter === "all") {
this.addActionButton(actions, "pencil", i18n.t("manager.edit"), () =>
this.openEditModal(comment)
);
}
}
private addActionButton(
parent: HTMLElement,
icon: string,
title: string,
onClick: () => void,
extraCls = ""
) {
const button = parent.createEl("button", {
cls: `otm-icon-button ${extraCls}`.trim(),
attr: { "aria-label": title, title },
});
setIcon(button, icon);
button.addEventListener("click", (evt) => {
evt.stopPropagation();
onClick();
});
return button;
}
private openReplyModal(comment: any) {
new CommentModal(this.app, {
title: i18n.t("manager.replyTo", { name: comment.author || "" }),
initial: "",
placeholder: i18n.t("manager.replyPlaceholder"),
submitText: i18n.t("manager.replySubmit"),
onSubmit: async (text) => {
await this.runCommentAction(comment, "reply", text);
},
}).open();
}
private openEditModal(comment: any) {
new CommentModal(this.app, {
title: i18n.t("manager.editCommentTitle"),
initial: comment.text ?? "",
placeholder: "",
submitText: i18n.t("manager.editCommentSubmit"),
onSubmit: async (text) => {
await this.runCommentAction(comment, "edit", text);
},
}).open();
}
private confirmDelete(comment: any) {
new ConfirmModal(
this.app,
i18n.t("manager.deleteCommentTitle"),
i18n.t("manager.deleteCommentMessage"),
async () => {
await this.runCommentAction(comment, "delete");
}
).open();
}
private async runCommentAction(
comment: any,
action: "approve" | "delete" | "edit" | "reply",
text?: string
) {
const site = getActiveSite();
const payload: Record<string, any> = {
action,
coid: comment.coid,
};
if (text !== undefined) {
payload.text = text;
}
if (action === "reply") {
payload.author = site?.User?.screenName || site?.name || "";
payload.mail = site?.User?.mail || "";
payload.url = site?.User?.url || "";
}
const response = await HttpUtils.post("/manageComment", payload);
// 回复时后端会补触发邮件通知插件;没触发到就提示一下,回复本身已保存
if (action === "reply" && response?.data?.notified === false) {
new Notice(i18n.t("manager.replyNoMail"));
} else {
new Notice(i18n.t("manager.actionDone"));
}
if (action === "delete") {
await this.loadComments(this.commentPage);
if (this.postsLoaded) await this.loadPosts(this.postPage);
} else {
await this.loadComments(this.commentPage);
}
// 审核/删除/回复都会改变总数与待审核数,重新统计一次
void this.refreshCommentCounts();
}
// ==================== 通用 ====================
/**
* 分页栏:上一页 / 第 x 页 共 y 页 / 下一页
* 只有一页时整条隐藏,不占高度
*/
private renderPager(
footerEl: HTMLElement,
page: number,
pages: number,
go: (page: number) => void
) {
footerEl.empty();
if (!pages || pages <= 1) {
footerEl.addClass("is-hidden");
return;
}
footerEl.removeClass("is-hidden");
const prevButton = footerEl.createEl("button", {
cls: "otm-icon-button",
attr: {
"aria-label": i18n.t("common.previousPage"),
title: i18n.t("common.previousPage"),
},
});
setIcon(prevButton, "chevron-left");
if (page <= 1) prevButton.disabled = true;
prevButton.addEventListener("click", () => {
if (page > 1) go(page - 1);
});
footerEl.createSpan({
cls: "otm-pager-info",
text: i18n.t("common.pageOf", { page, total: pages }),
});
const nextButton = footerEl.createEl("button", {
cls: "otm-icon-button",
attr: {
"aria-label": i18n.t("common.nextPage"),
title: i18n.t("common.nextPage"),
},
});
setIcon(nextButton, "chevron-right");
if (page >= pages) nextButton.disabled = true;
nextButton.addEventListener("click", () => {
if (page < pages) go(page + 1);
});
}
/**
* 评论内容可能是 HTML,这里只取纯文本用于列表展示
*/
private plainText(html: string): string {
const temp = document.createElement("div");
temp.innerHTML = html || "";
return (temp.textContent || "").replace(/\s+/g, " ").trim();
}
}