Files
obsidian-rss-union/view/main_view.ts

1547 lines
45 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, Notice, WorkspaceLeaf, setIcon } from "obsidian";
import {
RuCategory,
RuItem,
RuSite,
fetchItems,
fetchTree,
isConfigured,
tagLabels,
} from "../utils/api";
import { formatListDate } from "../utils/datetime";
import { hasCached, getCached, setCached } from "../utils/cache";
import { fetchFullText, NoContentError } from "../utils/extract";
import {
countRead,
flushReadState,
isRead,
markRead,
markReadMany,
scopeKeyOf,
} from "../utils/read_state";
import { getSettings } from "../setting/store";
import { VIEW_TYPE_READER, ReaderState, ReaderView, setPendingReaderState } from "./reader_view";
import i18n from "../utils/i18n";
export const VIEW_TYPE_MAIN = "ru-main-view";
type SelectionType = "all" | "cat" | "site";
/** 列表筛选:全部 / 只看已读 / 只看未读 */
type ListFilter = "all" | "read" | "unread";
interface Selection {
type: SelectionType;
id: number;
title: string;
}
/** 已读 / 未读筛选时,最多往回翻多少页、攒多少条(超出就只筛这部分,界面会给提示) */
const POOL_MAX_PAGES = 10;
const POOL_MAX_ITEMS = 1000;
/**
* 主视图:左侧分类树 + 右侧文章列表
*
* 列表数据全部来自网站(网站已经抓好 RSS),这里不发任何抓取请求;
* 只有点开某一篇时才去原文抓全文,抓完推到阅读窗口。
*/
export class RssUnionView extends ItemView {
private treeEl: HTMLElement | null = null;
private listEl: HTMLElement | null = null;
private headEl: HTMLElement | null = null;
private headLeftEl: HTMLElement | null = null;
private headRightEl: HTMLElement | null = null;
private pagerEl: HTMLElement | null = null;
private statusEl: HTMLElement | null = null;
private searchEl: HTMLInputElement | null = null;
private scopeEl: HTMLElement | null = null;
private refreshBtn: HTMLButtonElement | null = null;
private settingsBtn: HTMLButtonElement | null = null;
/** 当前面板是不是「未配置」提示页(true 时刷新需要重建整个布局) */
private configMode = false;
/** 分栏打开失败过一次就不再试,免得每次点文章都被撞一下 */
private splitBroken = false;
/** 自动刷新定时器 */
private autoTimer: number | null = null;
private tree: RuCategory[] = [];
private selection: Selection = { type: "all", id: 0, title: "" };
private items: RuItem[] = [];
private page = 1;
private pages = 0;
/** 当前这一屏的条数(筛选时是筛选后的条数) */
private total = 0;
/** 当前范围未筛选的总条数(统计条「共 N 篇」用它,别被筛选带偏) */
private scopeTotal = 0;
/** 订阅范围内可读的文章总数(来自 tree 的 stats.feeds) */
private feedsTotal = 0;
/** 列表筛选(已读 / 未读可点,再点一次回到全部) */
private filter: ListFilter = "all";
/** 筛选时往回翻页攒下的文章池;poolKey 变了就重攒 */
private pool: RuItem[] = [];
private poolKey = "";
private poolTruncated = false;
/** 服务端接口版本(1.1.0 起才有,用来判断服务器上的文件有没有换) */
private serverVersion = "";
/** 多选模式:开着时每行最前面出现复选框,点整行改为选中/取消 */
private selecting = false;
/** 当前选中的文章 id(只在当前这一页里有意义) */
private selected = new Set<number>();
private keyword = "";
private expanded: number[] = [];
private treeLoading = false;
private listLoading = false;
private treeError = "";
private listError = "";
private hint = "";
private seq = 0;
private searchTimer: number | null = null;
constructor(leaf: WorkspaceLeaf) {
super(leaf);
}
getViewType(): string {
return VIEW_TYPE_MAIN;
}
getDisplayText(): string {
return i18n.t("view.title");
}
getIcon(): string {
return "rss";
}
async onOpen(): Promise<void> {
this.build();
this.startAutoRefresh();
await this.reload(false);
}
async onClose(): Promise<void> {
if (this.searchTimer !== null) {
window.clearTimeout(this.searchTimer);
this.searchTimer = null;
}
this.stopAutoRefresh();
flushReadState();
}
/**
* 设置改完后由插件调用
*
* @param reset 是否清空选中的分类与搜索词(改站点 / 授权码时清,改刷新间隔时不清)
*/
async reloadFromSettings(reset = true): Promise<void> {
if (reset) {
this.selection = { type: "all", id: 0, title: "" };
this.keyword = "";
this.filter = "all";
this.poolKey = "";
this.scopeTotal = 0;
this.selecting = false;
this.selected.clear();
if (this.searchEl) this.searchEl.value = "";
}
this.startAutoRefresh();
await this.reload(false);
}
/* ==================== 自动刷新 ==================== */
private startAutoRefresh(): void {
this.stopAutoRefresh();
const minutes = Number(getSettings().autoRefreshMin || 0);
if (!(minutes > 0)) return;
this.autoTimer = window.setInterval(() => {
void this.tickAutoRefresh();
}, minutes * 60 * 1000);
}
private stopAutoRefresh(): void {
if (this.autoTimer !== null) {
window.clearInterval(this.autoTimer);
this.autoTimer = null;
}
}
/**
* 静默刷新:保持当前页、分类、搜索词
*
* 正在加载时跳过这一轮,别把用户手动刷新的结果冲掉;
* 面板不可见时也跳过 —— 后台每 5 分钟打两次接口没有意义。
*/
private async tickAutoRefresh(): Promise<void> {
if (!isConfigured()) return;
if (this.treeLoading || this.listLoading) return;
if (!this.isVisible()) return;
await this.loadTree();
await this.loadItems(this.page);
this.paintAutoHint();
}
private isVisible(): boolean {
const el = this.containerEl as HTMLElement & { isShown?: () => boolean };
if (!el) return false;
/* Obsidian 的 isShown() 会考虑 tab 是否在后台、窗口是否最小化;
没有这个方法(老版本/测试环境)就当作可见,宁可多刷一次也别整片不刷 */
if (typeof el.isShown === "function") return el.isShown();
return true;
}
private paintAutoHint(): void {
const minutes = Number(getSettings().autoRefreshMin || 0);
if (!(minutes > 0) || !this.statusEl) return;
const hint = this.statusEl.querySelector(".ru-status__auto");
if (hint) hint.setText(i18n.t("view.autoRefreshHint", { n: minutes }));
}
/* ==================== 骨架 ==================== */
private build(): void {
const root = this.contentEl;
root.empty();
root.addClass("ru-view");
/* 顶栏三段式:左标题|中搜索|右动作。
搜索按需求放在「标题」和「刷新」之间的正中 —— 用 1fr auto 1fr 的栅格,
左右两侧一样宽,搜索永远在整条的正中间,不会被标题长度带偏。 */
const bar = root.createDiv({ cls: "ru-bar" });
const titleWrap = bar.createDiv({ cls: "ru-bar__title" });
const icon = titleWrap.createSpan({ cls: "ru-bar__icon" });
setIcon(icon, "rss");
this.scopeEl = titleWrap.createSpan({ cls: "ru-bar__scope", text: i18n.t("view.all") });
const searchWrap = bar.createDiv({ cls: "ru-bar__search" });
this.buildSearch(searchWrap);
const actions = bar.createDiv({ cls: "ru-bar__actions" });
this.refreshBtn = this.iconButton(actions, "refresh-cw", i18n.t("common.refresh"), () => {
void this.reload(true);
});
this.settingsBtn = this.iconButton(actions, "settings", i18n.t("view.openSettings"), () => {
this.openSettings();
});
const main = root.createDiv({ cls: "ru-main" });
this.treeEl = main.createDiv({ cls: "ru-tree" });
const listWrap = main.createDiv({ cls: "ru-listwrap" });
/* 统计条:左「共 N 篇」,右已读 / 未读。搜索已经搬到顶栏,
这一条只负责回答「这个范围多大、读了多少」。 */
this.headEl = listWrap.createDiv({ cls: "ru-listhead" });
this.headLeftEl = this.headEl.createDiv({ cls: "ru-listhead__left" });
this.headRightEl = this.headEl.createDiv({ cls: "ru-listhead__right" });
this.listEl = listWrap.createDiv({ cls: "ru-list" });
this.pagerEl = listWrap.createDiv({ cls: "ru-pager" });
this.statusEl = root.createDiv({ cls: "ru-status" });
this.renderListHead();
}
/** 搜索框:住在顶栏中间那一格 */
private buildSearch(parent: HTMLElement): void {
this.searchEl = parent.createEl("input", {
cls: "ru-search",
attr: {
type: "search",
placeholder: i18n.t("common.search"),
spellcheck: "false",
},
});
this.searchEl.value = this.keyword;
this.searchEl.addEventListener("input", () => {
if (this.searchTimer !== null) window.clearTimeout(this.searchTimer);
this.searchTimer = window.setTimeout(() => {
this.applyKeyword((this.searchEl?.value || "").trim());
}, 320);
});
this.searchEl.addEventListener("keydown", (event) => {
if (event.key === "Enter") {
event.preventDefault();
this.applyKeyword((this.searchEl?.value || "").trim());
}
});
}
/** 关键词变了:文章池作废,从第一页重来 */
private applyKeyword(next: string): void {
if (next === this.keyword) return;
this.keyword = next;
this.poolKey = "";
this.selected.clear();
/* 搜索时退出已读 / 未读筛选:筛选要先把整个范围的文章攒到本地,
搜索结果是个子集,两边叠在一起数字容易互相矛盾(已读 4 + 未读 28 ≠ 32),
所以搜索期间只给「共 N 篇」,清空搜索后筛选按钮再回来 */
if (next !== "") this.filter = "all";
void this.loadItems(1);
}
/** 清空搜索(统计条右侧那枚「搜索:xxx」胶囊) */
private clearSearch(): void {
if (this.searchEl) this.searchEl.value = "";
this.applyKeyword("");
}
private iconButton(
parent: HTMLElement,
icon: string,
label: string,
onClick: () => void
): HTMLButtonElement {
const button = parent.createEl("button", {
cls: "ru-icon-btn",
attr: { "aria-label": label, title: label },
});
setIcon(button, icon);
button.addEventListener("click", (event) => {
event.preventDefault();
onClick();
});
return button;
}
/* ==================== 取数 ==================== */
async reload(showNotice: boolean): Promise<void> {
if (!isConfigured()) {
this.renderConfigNeeded();
return;
}
// 之前是「未配置」提示页:重新搭一次骨架(顶栏 / 左树 / 列表都要回来)
if (this.configMode) {
this.configMode = false;
this.build();
}
this.setStatus(i18n.t("view.refreshing"));
await this.loadTree();
await this.loadItems(1);
if (showNotice) new Notice(i18n.t("view.refreshed"));
}
private async loadTree(): Promise<void> {
this.treeLoading = true;
this.renderTree();
try {
const res = await fetchTree();
this.tree = res.tree || [];
this.feedsTotal = (res.stats && res.stats.feeds) || 0;
this.serverVersion = String(res.apiVersion || "").trim();
this.hint = res.message || "";
this.treeError = "";
/* 树刷新了说明数据可能变了,筛选用的文章池作废,下次筛选重新攒 */
this.poolKey = "";
if (this.selection.type !== "all" && !this.findSelection()) {
this.selection = { type: "all", id: 0, title: "" };
this.filter = "all";
}
} catch (error: any) {
this.tree = [];
this.treeError = messageOf(error);
} finally {
this.treeLoading = false;
this.renderTree();
this.paintScope();
}
}
private async loadItems(page: number): Promise<void> {
const nextPage = page > 0 ? page : 1;
/* 翻页了:上一页勾的 id 在这页找不到对应条目,留着只会让计数骗人 */
if (nextPage !== this.page) this.selected.clear();
this.page = nextPage;
this.listLoading = true;
this.listError = "";
this.renderList();
this.renderPager();
this.renderListHead();
const seq = ++this.seq;
try {
if (this.filter === "all") {
const res = await fetchItems({
urlId: this.selection.type === "site" ? this.selection.id : 0,
catId: this.selection.type === "cat" ? this.selection.id : 0,
keyword: this.keyword,
page: this.page,
pageSize: getSettings().pageSize,
});
if (seq !== this.seq) return;
this.items = res.items || [];
this.pages = res.pages || 0;
this.total = res.total || 0;
this.scopeTotal = res.total || 0;
if (res.apiVersion) this.serverVersion = res.apiVersion;
if (res.message) this.hint = res.message;
} else {
await this.fillFromPool(seq);
if (seq !== this.seq) return;
}
} catch (error: any) {
if (seq !== this.seq) return;
this.items = [];
this.pages = 0;
this.total = 0;
this.listError = messageOf(error);
} finally {
if (seq === this.seq) {
this.listLoading = false;
this.renderList();
this.renderPager();
this.renderListHead();
this.renderStatus();
}
}
}
/* ==================== 已读 / 未读筛选 ==================== */
/**
* 切筛选
*
* 已读状态只在本机,服务端没法按它过滤,所以「已读 / 未读」这一层是
* 客户端把范围内的文章攒下来再筛。再点一次同一枚胶囊 = 回到全部。
*/
private setFilter(next: ListFilter): void {
if (this.filter === next) return;
this.filter = next;
this.page = 1;
/* 列表内容整套换了,旧的勾选没有意义 */
this.selected.clear();
void this.loadItems(1);
}
/** 把当前范围的文章攒进 pool(同一范围 + 同一关键词只攒一次) */
private async ensurePool(seq: number): Promise<void> {
const key = `${scopeKeyOf(this.selection.type, this.selection.id)}|${this.keyword}`;
if (this.poolKey === key) return;
/* 攒的时候一页要多拿一些:默认每页 30 条是「看」的节奏,
往回翻是为了「找有没有没读的」,取 50–100 条一次更省事 */
const size = Math.min(Math.max(Number(getSettings().pageSize) || 30, 50), 100);
const pool: RuItem[] = [];
let pages = 1;
let page = 1;
let truncated = false;
while (page <= pages) {
if (page > POOL_MAX_PAGES || pool.length >= POOL_MAX_ITEMS) {
truncated = page <= pages;
break;
}
const res = await fetchItems({
urlId: this.selection.type === "site" ? this.selection.id : 0,
catId: this.selection.type === "cat" ? this.selection.id : 0,
keyword: this.keyword,
page,
pageSize: size,
});
if (seq !== this.seq) return;
const got = res.items || [];
pool.push(...got);
pages = res.pages || 1;
this.scopeTotal = res.total || pool.length;
if (res.apiVersion) this.serverVersion = res.apiVersion;
if (got.length === 0) break;
page++;
}
this.pool = pool;
this.poolKey = key;
this.poolTruncated = truncated;
}
/** 从 pool 里筛出这一页 */
private async fillFromPool(seq: number): Promise<void> {
await this.ensurePool(seq);
if (seq !== this.seq) return;
const picked = this.pool.filter((item) =>
this.filter === "read" ? isRead(item.id) : !isRead(item.id)
);
const size = Math.max(1, Number(getSettings().pageSize) || 30);
this.total = picked.length;
this.pages = picked.length > 0 ? Math.ceil(picked.length / size) : 0;
this.page = this.pages > 0 ? Math.min(Math.max(this.page, 1), this.pages) : 1;
const offset = (this.page - 1) * size;
this.items = picked.slice(offset, offset + size);
}
private findSelection(): boolean {
if (this.selection.type === "cat") {
return this.tree.some((cat) => cat.id === this.selection.id);
}
if (this.selection.type === "site") {
return this.tree.some((cat) => cat.sites.some((site) => site.id === this.selection.id));
}
return true;
}
/* ==================== 左树 ==================== */
private renderTree(): void {
const el = this.treeEl;
if (!el) return;
el.empty();
if (this.treeLoading && this.tree.length === 0) {
const loading = el.createDiv({ cls: "ru-tree__state" });
loading.createDiv({ cls: "ru-spinner" });
loading.createEl("div", { text: i18n.t("common.loading") });
return;
}
if (this.treeError) {
const box = el.createDiv({ cls: "ru-tree__state is-error" });
box.createEl("div", { text: this.treeError });
const retry = box.createEl("button", { cls: "ru-linkbtn", text: i18n.t("common.retry") });
retry.addEventListener("click", () => void this.reload(false));
return;
}
if (this.tree.length === 0) {
const box = el.createDiv({ cls: "ru-tree__state" });
box.createEl("div", { cls: "ru-tree__state-title", text: i18n.t("view.emptyTree") });
box.createEl("div", { cls: "ru-tree__state-desc", text: this.hint || i18n.t("view.emptyTreeDesc") });
return;
}
/* 「全部订阅」的数字是「能读到的文章总数」。
原来是网站个数(6),和右边列表的 57 放在一起看很奇怪。 */
this.treeRow(
el,
i18n.t("view.all"),
this.feedsTotal > 0 ? String(this.feedsTotal) : "",
this.selection.type === "all",
() => {
this.select({ type: "all", id: 0, title: i18n.t("view.all") });
}
);
for (const cat of this.tree) {
const details = el.createEl("details", { cls: "ru-tree__cat" });
// 开合状态只看 expanded,别和 selection 挂钩:
// 否则「点一下就选中」会让它永远展开,再也收不起来
details.open = this.expanded.indexOf(cat.id) >= 0;
details.addEventListener("toggle", () => {
if (details.open) {
if (this.expanded.indexOf(cat.id) < 0) this.expanded.push(cat.id);
} else {
this.expanded = this.expanded.filter((id) => id !== cat.id);
}
});
const summary = details.createEl("summary", {
cls: "ru-tree__row ru-tree__row--cat",
attr: { "data-ru-kind": "cat", "data-ru-id": String(cat.id) },
});
if (this.selection.type === "cat" && this.selection.id === cat.id) {
summary.addClass("is-active");
}
const caret = summary.createSpan({ cls: "ru-tree__caret" });
setIcon(caret, "chevron-right");
summary.createSpan({ cls: "ru-tree__label", text: cat.name });
/* 数字是「我订阅范围内」的篇数,和点进去看到的列表总数一致。
全站有多少篇放在悬浮提示里,避免出现「写着 8451、点进去 47」。 */
summary.createSpan({
cls: "ru-tree__count",
text: cat.feedCount > 0 ? String(cat.feedCount) : "",
});
if (cat.feedTotal && cat.feedTotal > cat.feedCount) {
summary.setAttribute(
"title",
i18n.t("view.catTip", { total: cat.feedTotal, mine: cat.feedCount })
);
}
summary.addEventListener("click", () => {
// 展开/收起交给 <details> 自己处理,这里只在「换了分类」时去取列表
if (this.selection.type === "cat" && this.selection.id === cat.id) return;
this.select({ type: "cat", id: cat.id, title: cat.name });
});
const sites = details.createDiv({ cls: "ru-tree__sites" });
for (const site of cat.sites) {
this.siteRow(sites, site);
}
}
}
private siteRow(parent: HTMLElement, site: RuSite): void {
// 用 div 而不是 button:Obsidian 主题给 button 的边框和背景会渗进来
const row = parent.createEl("div", {
cls: "ru-tree__row ru-tree__row--site",
attr: { role: "button", tabindex: "0", "data-ru-kind": "site", "data-ru-id": String(site.id) },
});
if (this.selection.type === "site" && this.selection.id === site.id) {
row.addClass("is-active");
}
row.createSpan({ cls: "ru-tree__label", text: site.title || site.url });
row.createSpan({ cls: "ru-tree__count", text: site.feedCount ? String(site.feedCount) : "" });
const activate = (event: Event) => {
event.preventDefault();
event.stopPropagation();
this.select({ type: "site", id: site.id, title: site.title || site.url });
};
row.addEventListener("click", activate);
row.addEventListener("keydown", (event) => {
if (event.key === "Enter" || event.key === " ") activate(event);
});
}
private treeRow(
parent: HTMLElement,
label: string,
count: string,
active: boolean,
onClick: () => void
): void {
// 同样用 div:button 在 Obsidian 主题里带边框和底色
const row = parent.createEl("div", {
cls: "ru-tree__row",
attr: { role: "button", tabindex: "0", "data-ru-kind": "all", "data-ru-id": "0" },
});
if (active) row.addClass("is-active");
row.createSpan({ cls: "ru-tree__label", text: label });
row.createSpan({ cls: "ru-tree__count", text: count });
const activate = (event: Event) => {
event.preventDefault();
onClick();
};
row.addEventListener("click", activate);
row.addEventListener("keydown", (event) => {
if (event.key === "Enter" || event.key === " ") activate(event);
});
}
private select(selection: Selection): void {
this.selection = selection;
this.page = 1;
this.scopeTotal = 0;
this.total = 0;
/* 换了范围:之前勾的文章不一定还在列表里,退出多选更稳妥 */
this.selected.clear();
this.selecting = false;
// 只改高亮,不重建树:重建会把 <details> 换掉,展开状态就丢了
this.paintTreeSelection();
this.paintScope();
void this.loadItems(1);
}
/** 按当前 selection 刷新树里的高亮(不碰 DOM 结构) */
private paintTreeSelection(): void {
const el = this.treeEl;
if (!el) return;
const rows = Array.from(el.querySelectorAll<HTMLElement>(".ru-tree__row"));
for (const row of rows) {
const kind = row.dataset.ruKind || "";
const id = Number(row.dataset.ruId || "0");
const active =
(this.selection.type === "all" && kind === "all") ||
(this.selection.type === "cat" && kind === "cat" && id === this.selection.id) ||
(this.selection.type === "site" && kind === "site" && id === this.selection.id);
row.classList.toggle("is-active", active);
}
}
private paintScope(): void {
if (this.scopeEl) {
this.scopeEl.setText(this.selection.type === "all" ? i18n.t("view.all") : this.selection.title);
}
}
/* ==================== 右侧列表 ==================== */
/**
* 列表顶部统计条
*
* 左:这个范围一共多少篇(未筛选的口径,等于左侧树里那个数字)
* 右:已读 / 未读,括号里是数量;两枚都能点,
* 点一下只看这一类,再点一次回到全部。
*
* 这一条只重画左右两格,不碰别的节点。
*/
private renderListHead(): void {
const left = this.headLeftEl;
const right = this.headRightEl;
if (!left || !right) return;
left.empty();
right.empty();
const scope = scopeKeyOf(this.selection.type, this.selection.id);
/* 「共 N 篇」用未筛选的总数:筛选时列表只剩一部分,
但这一栏要回答的是「这个范围有多大」 */
const total = this.scopeTotal > 0 ? this.scopeTotal : this.total;
const read = Math.min(countRead(scope), total);
const unread = Math.max(total - read, 0);
if (this.filter !== "all") left.addClass("is-filtered");
else left.removeClass("is-filtered");
const icon = left.createSpan({ cls: "ru-listhead__icon" });
setIcon(icon, "newspaper");
/* 就是一行文字,不用 button —— 主题给 button 的底色 / 边框 / hover
会把这行字弄成一个奇怪的方块。筛选时点它仍然能回全部。 */
const totalEl = left.createSpan({
cls: "ru-listhead__total",
text:
this.listLoading && total === 0
? i18n.t("common.loading")
: i18n.t("view.totalCount", { n: total }),
});
if (this.filter !== "all") {
totalEl.setAttribute("title", i18n.t("view.filterClear"));
totalEl.addClass("is-clearable");
totalEl.addEventListener("click", () => this.setFilter("all"));
}
/* 服务端还是旧文件时,数字会是「整个分类全站」的。
这件事必须在统计条上就能看到,不能只躺在底部状态栏里。 */
if (this.needsServerUpgrade()) {
const warn = left.createSpan({ cls: "ru-listhead__warn", text: i18n.t("view.serverBadge") });
warn.setAttribute("title", i18n.t("view.serverBadgeTip"));
}
if (this.keyword) {
this.searchPill(right);
}
/* 顺序按需求:选择 → 全选 → 设为已读 → 未读 → 已读。
全选和设为已读只在选择模式里出现 —— 没有复选框时它们无从下手。 */
this.selectChip(right);
if (this.selecting) {
this.selectAllChip(right);
this.markReadChip(right);
}
/* 搜索期间不显示已读 / 未读:本地已读数跟搜索子集对不齐 */
if (!this.keyword) {
this.filterChip(right, "unread", i18n.t("view.unreadChip"), unread);
this.filterChip(right, "read", i18n.t("view.readChip"), read);
}
}
/** 「选择」:进出多选模式 */
private selectChip(parent: HTMLElement): void {
const active = this.selecting;
const chip = parent.createEl("button", {
cls: `ru-chip ru-chip--tool${active ? " is-active" : ""}`,
attr: {
type: "button",
"aria-pressed": active ? "true" : "false",
title: active ? i18n.t("view.selectExitTip") : i18n.t("view.selectTip"),
},
});
chip.createSpan({
cls: "ru-chip__label",
text: active ? i18n.t("view.selectCancel") : i18n.t("view.selectMode"),
});
chip.addEventListener("click", (event) => {
event.preventDefault();
event.stopPropagation();
this.setSelecting(!active);
});
}
/** 「全选」:把当前列表这一页全选上;已全选时再点取消(选中态实心区分) */
private selectAllChip(parent: HTMLElement): void {
const all = this.items.length > 0 && this.items.every((item) => this.selected.has(item.id));
const chip = parent.createEl("button", {
cls: `ru-chip ru-chip--tool${all ? " is-active" : ""}`,
attr: {
type: "button",
"aria-pressed": all ? "true" : "false",
title: all ? i18n.t("view.selectNoneTip") : i18n.t("view.selectAllTip"),
},
});
chip.createSpan({ cls: "ru-chip__label", text: i18n.t("view.selectAll") });
chip.addEventListener("click", (event) => {
event.preventDefault();
event.stopPropagation();
this.toggleSelectAll();
});
}
/** 「设为已读」:把选中的文章一次标成已读;没选时禁用 */
private markReadChip(parent: HTMLElement): void {
const n = this.selected.size;
const chip = parent.createEl("button", {
cls: "ru-chip ru-chip--tool ru-chip--action",
attr: {
type: "button",
title: n > 0 ? i18n.t("view.markReadTip", { n }) : i18n.t("view.markReadEmpty"),
},
});
chip.createSpan({ cls: "ru-chip__label", text: i18n.t("view.markRead") });
if (n > 0) chip.createSpan({ cls: "ru-chip__n", text: `(${n})` });
else chip.disabled = true;
chip.addEventListener("click", (event) => {
event.preventDefault();
event.stopPropagation();
this.markSelectedRead();
});
}
/** 搜索期间右格的替代品:显示关键词,点一下清空 */
private searchPill(parent: HTMLElement): void {
const pill = parent.createEl("button", {
cls: "ru-chip ru-chip--search",
attr: { type: "button", title: i18n.t("view.clearSearch") },
});
pill.createSpan({ cls: "ru-chip__label", text: i18n.t("view.searching", { q: this.keyword }) });
pill.addEventListener("click", (event) => {
event.preventDefault();
this.clearSearch();
});
}
/** 一枚可点的筛选胶囊 */
private filterChip(parent: HTMLElement, kind: "read" | "unread", label: string, n: number): void {
const active = this.filter === kind;
const chip = parent.createEl("button", {
cls: `ru-chip ru-chip--${kind}${active ? " is-active" : ""}`,
attr: {
type: "button",
"aria-pressed": active ? "true" : "false",
title: active
? i18n.t("view.filterClear")
: i18n.t("view.filterTip", { label }),
},
});
chip.createSpan({ cls: "ru-chip__dot" });
chip.createSpan({ cls: "ru-chip__label", text: label });
chip.createSpan({ cls: "ru-chip__n", text: `(${n})` });
chip.addEventListener("click", (event) => {
event.preventDefault();
event.stopPropagation();
this.setFilter(active ? "all" : kind);
});
}
/* ==================== 多选 / 批量已读 ==================== */
/**
* 进出多选模式
*
* 复选框是渲染时插进来的,所以进出要重画列表 —— 列表容器本身不换,
* 滚动位置不会跳回顶部。
*/
private setSelecting(next: boolean): void {
if (this.selecting === next) return;
this.selecting = next;
if (!next) this.selected.clear();
this.renderList();
this.renderListHead();
}
private toggleSelect(item: RuItem): void {
if (this.selected.has(item.id)) this.selected.delete(item.id);
else this.selected.add(item.id);
this.paintSelection();
this.renderListHead();
}
private toggleSelectAll(): void {
const all = this.items.length > 0 && this.items.every((item) => this.selected.has(item.id));
if (all) {
this.selected.clear();
} else {
for (const item of this.items) this.selected.add(item.id);
}
this.paintSelection();
this.renderListHead();
}
/** 按 selected 刷新每行的选中态(不重画列表,滚动位置不动) */
private paintSelection(): void {
const el = this.listEl;
if (!el) return;
for (const row of Array.from(el.querySelectorAll<HTMLElement>(".ru-item"))) {
const id = Number(row.dataset.id || "0");
const on = this.selecting && this.selected.has(id);
row.classList.toggle("is-selected", on);
const box = row.querySelector<HTMLInputElement>(".ru-pick");
if (box) box.checked = on;
}
}
/**
* 把选中的文章一次标成已读
*
* 只认当前列表里真实存在的条目 —— 已读状态存在本机,需要 item 上的
* 分类 / 网站 id 才能把三个范围的索引一起写好。
*/
private markSelectedRead(): void {
if (!this.selecting || this.selected.size === 0) return;
const picked = this.items.filter((item) => this.selected.has(item.id));
if (picked.length === 0) return;
const changed = markReadMany(picked);
this.selected.clear();
this.renderListHead();
/* 「未读」视图里这些行现在该消失了,从池子里重筛一遍;
其他视图原地改样式即可,别整页重画 */
if (this.filter === "unread") {
void this.loadItems(this.page);
} else {
this.paintSelection();
for (const item of picked) {
const row = this.listEl?.querySelector<HTMLElement>(`.ru-item[data-id="${item.id}"]`);
if (!row) continue;
row.addClass("is-read");
row.dataset.read = "1";
}
}
new Notice(
changed > 0
? i18n.t("view.markReadDone", { n: changed })
: i18n.t("view.markReadNone")
);
}
private renderList(): void {
const el = this.listEl;
if (!el) return;
el.empty();
if (this.listLoading && this.items.length === 0) {
const loading = el.createDiv({ cls: "ru-list__state" });
loading.createDiv({ cls: "ru-spinner" });
loading.createEl("div", { text: i18n.t("view.loadingList") });
return;
}
if (this.listError) {
const box = el.createDiv({ cls: "ru-list__state is-error" });
box.createEl("div", { cls: "ru-list__state-title", text: i18n.t("common.error") });
box.createEl("div", { cls: "ru-list__state-desc", text: this.listError });
const retry = box.createEl("button", { cls: "ru-linkbtn", text: i18n.t("common.retry") });
retry.addEventListener("click", () => void this.loadItems(this.page));
return;
}
if (this.items.length === 0) {
const box = el.createDiv({ cls: "ru-list__state" });
if (this.filter === "read") {
box.createEl("div", { cls: "ru-list__state-title", text: i18n.t("view.emptyRead") });
box.createEl("div", { cls: "ru-list__state-desc", text: i18n.t("view.emptyReadDesc") });
} else if (this.filter === "unread") {
box.createEl("div", { cls: "ru-list__state-title", text: i18n.t("view.emptyUnread") });
box.createEl("div", { cls: "ru-list__state-desc", text: i18n.t("view.emptyUnreadDesc") });
} else {
box.createEl("div", { cls: "ru-list__state-title", text: i18n.t("view.emptyList") });
box.createEl("div", { cls: "ru-list__state-desc", text: this.hint || "" });
}
return;
}
for (const item of this.items) {
this.itemRow(el, item);
}
}
private itemRow(parent: HTMLElement, item: RuItem): void {
const read = isRead(item.id);
const picked = this.selecting && this.selected.has(item.id);
const row = parent.createDiv({
cls: [
"ru-item",
read ? "is-read" : "",
this.selecting ? "is-selecting" : "",
picked ? "is-selected" : "",
]
.filter(Boolean)
.join(" "),
attr: { "data-id": String(item.id), "data-read": read ? "1" : "0" },
});
const head = row.createDiv({ cls: "ru-item__head" });
/* 多选模式:行首复选框。点它只切换选中,不打开文章 */
if (this.selecting) {
const box = head.createEl("input", {
cls: "ru-pick",
attr: { type: "checkbox", "aria-label": i18n.t("view.selectItem") },
});
box.checked = picked;
box.addEventListener("click", (event) => {
event.preventDefault();
event.stopPropagation();
this.toggleSelect(item);
});
}
/* 未读圆点:已读时 CSS 把它收成空心灰色,一眼能看出哪些没看过 */
head.createSpan({ cls: "ru-item__dot" });
const title = head.createSpan({ cls: "ru-item__title", text: item.title || i18n.t("reader.unknownTitle") });
if (hasCached(item.id)) {
title.addClass("is-cached");
const mark = head.createSpan({ cls: "ru-badge ru-badge--cached" });
setIcon(mark.createSpan({ cls: "ru-badge__icon" }), "check");
mark.createSpan({ text: i18n.t("view.fetchedMark") });
}
if (item.isPinned) head.createSpan({ cls: "ru-badge ru-badge--pin", text: "置顶" });
if (item.isFeatured) head.createSpan({ cls: "ru-badge ru-badge--feature", text: "推荐" });
if (item.isHot) head.createSpan({ cls: "ru-badge ru-badge--hot", text: "热议" });
const meta = row.createDiv({ cls: "ru-item__meta" });
const bits = [item.siteTitle, item.categoryName, formatListDate(item.pubDate)].filter(Boolean);
meta.setText(bits.join(" · "));
if (item.excerpt) {
row.createDiv({ cls: "ru-item__excerpt", text: item.excerpt });
}
const tags = tagLabels(item.tags);
if (tags.length > 0) {
const tagWrap = row.createDiv({ cls: "ru-item__tags" });
for (const tag of tags.slice(0, 6)) {
tagWrap.createSpan({ cls: "ru-item__tag", text: `#${tag}` });
}
}
row.addEventListener("click", (event) => {
const target = event.target as HTMLElement;
if (target.closest("a, button, input")) return;
/* 多选模式下点整行 = 勾上 / 取消,不打开文章 */
if (this.selecting) {
this.toggleSelect(item);
return;
}
void this.openArticle(item);
});
}
/** 标记已读:改这一行的样式 + 刷新顶部统计,不重画列表 */
private markItemRead(item: RuItem): void {
if (!markRead(item)) return;
/* 正开着「未读」筛选时,这篇刚变成已读,应该从列表里挪走;
开着「已读」时它本来就该在这儿,重排一次就行。
两种情况都从文章池重算,页面不跳。 */
if (this.filter !== "all") {
void this.loadItems(this.page);
return;
}
const row = this.listEl?.querySelector<HTMLElement>(`.ru-item[data-id="${item.id}"]`);
if (row) {
row.addClass("is-read");
row.dataset.read = "1";
}
this.renderListHead();
}
/** 给某一行补上「已抓取」徽标(原地更新,不动列表其他部分) */
private markItemCached(itemId: number): void {
const row = this.listEl?.querySelector<HTMLElement>(`.ru-item[data-id="${itemId}"]`);
if (!row) return;
const head = row.querySelector<HTMLElement>(".ru-item__head");
const title = row.querySelector<HTMLElement>(".ru-item__title");
if (!head || !title) return;
if (head.querySelector(".ru-badge--cached")) return;
title.addClass("is-cached");
const mark = head.createSpan({ cls: "ru-badge ru-badge--cached" });
setIcon(mark.createSpan({ cls: "ru-badge__icon" }), "check");
mark.createSpan({ text: i18n.t("view.fetchedMark") });
// 挪到标题后面,和其他徽标排在一起
head.insertBefore(mark, title.nextSibling);
}
private renderPager(): void {
const el = this.pagerEl;
if (!el) return;
el.empty();
if (this.pages <= 1) {
el.addClass("is-hidden");
return;
}
el.removeClass("is-hidden");
const prev = el.createEl("button", { cls: "ru-icon-btn", attr: { "aria-label": i18n.t("common.previousPage") } });
setIcon(prev, "chevron-left");
prev.disabled = this.page <= 1;
prev.addEventListener("click", () => {
if (this.page > 1) void this.loadItems(this.page - 1);
});
el.createSpan({ cls: "ru-pager__info", text: i18n.t("common.pageOf", { page: this.page, total: this.pages }) });
const next = el.createEl("button", { cls: "ru-icon-btn", attr: { "aria-label": i18n.t("common.nextPage") } });
setIcon(next, "chevron-right");
next.disabled = this.page >= this.pages;
next.addEventListener("click", () => {
if (this.page < this.pages) void this.loadItems(this.page + 1);
});
}
private renderStatus(): void {
if (!this.statusEl) return;
this.statusEl.empty();
if (this.listLoading) {
this.setStatus(i18n.t("common.loading"));
return;
}
if (this.filter !== "all") {
this.statusEl.createSpan({
cls: "ru-status__filter",
text: i18n.t("view.filterOn", {
label: this.filter === "read" ? i18n.t("view.readChip") : i18n.t("view.unreadChip"),
n: this.total,
}),
});
}
if (this.filter !== "all" && this.poolTruncated) {
this.statusEl.createSpan({
cls: "ru-status__hint",
text: i18n.t("view.filterPartial", { n: this.pool.length }),
});
}
if (this.hint && this.filter === "all") {
this.statusEl.createSpan({ cls: "ru-status__hint", text: this.hint });
}
/* 服务端接口版本对不上 = 服务器上的 Obsidian.php 还是旧文件,
分类 / 列表的数字会是「整个分类全站」而不是「我订阅的」 */
if (this.needsServerUpgrade()) {
this.statusEl.createSpan({
cls: "ru-status__warn",
text: this.serverVersion
? i18n.t("view.serverOld", { v: this.serverVersion })
: i18n.t("view.serverUnknown"),
});
}
const minutes = Number(getSettings().autoRefreshMin || 0);
if (minutes > 0) {
this.statusEl.createSpan({
cls: "ru-status__auto",
text: i18n.t("view.autoRefreshHint", { n: minutes }),
});
}
}
/**
* 服务端接口低于 1.2.0(或压根没返回版本)= 旧文件
*
* 1.2.0 起左侧每个数字都直接取自列表的 total;低于这个版本,
* 分类数字是「整个分类全站」的,所以必须提示到位 —— 这是唯一会让
* 用户觉得「改了也没用」的情况。
*/
private needsServerUpgrade(): boolean {
if (!this.serverVersion) return true;
return compareVersion(this.serverVersion, "1.2.0") < 0;
}
private setStatus(text: string): void {
if (!this.statusEl) return;
this.statusEl.empty();
this.statusEl.createSpan({ text });
}
/* ==================== 打开阅读窗口 ==================== */
private async openArticle(item: RuItem): Promise<void> {
// 点开就算读过:先本地记一笔,右侧统计立刻跟着变
this.markItemRead(item);
const cached = getCached(item.id);
const initial: ReaderState = cached
? { item, article: cached, loading: false, error: "" }
: { item, article: null, loading: true, error: "" };
// 先落「待渲染」,再开面板:面板刚建好时 onOpen 会自己取这份数据
setPendingReaderState(initial);
try {
await this.ensureReaderView();
} catch (error: any) {
console.error("RssUnion: 打开阅读窗口失败", error);
new Notice(`打开阅读窗口失败:${messageOf(error) || "看控制台日志"}`);
return;
}
// 能直接拿到面板就立刻推一份,拿不到也不影响——onOpen 会自己补
this.pushReaderState(initial);
if (cached) return;
try {
const article = await fetchFullText(item.link);
setCached(item.id, article);
const done: ReaderState = { item, article, loading: false, error: "" };
setPendingReaderState(done);
this.pushReaderState(done);
// 只给这一行补「已抓取」徽标,别重画整个列表——否则滚动位置会跳回顶部
this.markItemCached(item.id);
} catch (error: any) {
const message =
error instanceof NoContentError
? `${i18n.t("reader.noContent")}`
: messageOf(error);
const failed: ReaderState = { item, article: null, loading: false, error: message };
setPendingReaderState(failed);
this.pushReaderState(failed);
}
}
/** 把状态推给所有已打开的阅读面板(面板可能是多个) */
private pushReaderState(state: ReaderState): void {
for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_READER)) {
const view = asReaderView(leaf);
if (view) {
view.showData(state);
continue;
}
// 面板还没就绪(延迟加载的壳):强制加载后补推一次
void this.pushWhenReady(leaf, state);
}
}
private async pushWhenReady(leaf: WorkspaceLeaf, state: ReaderState): Promise<void> {
try {
const loader = (leaf as unknown as { loadIfDeferred?: () => Promise<void> }).loadIfDeferred;
if (typeof loader === "function") await loader.call(leaf);
} catch (error) {
// 加载失败也不影响:onOpen 会从待渲染状态里取
}
const view = asReaderView(leaf);
if (view) view.showData(state);
}
/** 打开(或聚焦)阅读面板。只管「窗口有没有」,数据走 pushReaderState */
private async ensureReaderView(): Promise<void> {
const { workspace } = this.app;
const existing = workspace.getLeavesOfType(VIEW_TYPE_READER);
if (existing.length > 0) {
await workspace.revealLeaf(existing[0]);
return;
}
const wantSplit = getSettings().openMode === "split" && !this.splitBroken;
const mode = wantSplit ? "split" : "tab";
// split 出来的新 leaf 在部分版本里 header 结构还没就绪,setViewState 会在
// 内部对 null 调 setText 而抛错。失败了就退回中心区新标签,别再让用户看到空白。
try {
await this.openInLeaf(mode);
} catch (error) {
if (mode === "tab") throw error;
/* eslint-disable-next-line no-console */
console.warn("RssUnion: 分栏打开失败,改用新标签页", error);
this.splitBroken = true;
await this.openInLeaf("tab");
}
}
private async openInLeaf(mode: "tab" | "split"): Promise<void> {
const { workspace } = this.app;
const leaf = workspace.getLeaf(mode);
if (!leaf) throw new Error("拿不到新的面板(可能是布局被锁定)");
try {
await leaf.setViewState({ type: VIEW_TYPE_READER, active: true });
} catch (error) {
// 失败的 tab 留着只会让下次复用又崩一次
try {
leaf.detach();
} catch (detachError) {
// 无所谓
}
throw error;
}
await workspace.revealLeaf(leaf);
}
/* ==================== 未配置 / 设置 ==================== */
private renderConfigNeeded(): void {
const root = this.contentEl;
this.configMode = true;
this.selecting = false;
this.selected.clear();
this.treeEl = null;
this.listEl = null;
this.headEl = null;
this.headLeftEl = null;
this.headRightEl = null;
this.pagerEl = null;
this.statusEl = null;
this.searchEl = null;
this.scopeEl = null;
root.empty();
root.addClass("ru-view");
const box = root.createDiv({ cls: "ru-config" });
const icon = box.createDiv({ cls: "ru-config__icon" });
setIcon(icon, "rss");
box.createEl("div", { cls: "ru-config__title", text: i18n.t("view.notConfigured") });
box.createEl("div", { cls: "ru-config__desc", text: i18n.t("view.notConfiguredDesc") });
const button = box.createEl("button", { cls: "ru-primary", text: i18n.t("view.openSettings") });
button.addEventListener("click", () => this.openSettings());
}
/** 从「未配置」状态恢复回正常布局(设置填好后刷新时用) */
private openSettings(): void {
const app: any = this.app;
try {
if (app.setting && typeof app.setting.open === "function") {
app.setting.open();
if (typeof app.setting.openTabById === "function") {
app.setting.openTabById("obsidian-rss-union");
}
return;
}
} catch (error) {
console.error("RssUnion: 打开设置失败", error);
}
new Notice("请到「设置 → 第三方插件 → RSS Union Reader」里填写站点地址和授权码");
}
}
function messageOf(error: any): string {
if (!error) return "";
if (typeof error === "string") return error;
return String(error.message || error);
}
/**
* 比较 "1.1.0" 这样的版本号:a < b 返回负数
*
* 只比数字段,缺位按 0 算("1.1" == "1.1.0"),非数字后缀忽略 ——
* 这里只需要判断「服务端是不是 1.1.0 之前的老接口」。
*/
function compareVersion(a: string, b: string): number {
const left = String(a || "").split(".").map((part) => parseInt(part, 10) || 0);
const right = String(b || "").split(".").map((part) => parseInt(part, 10) || 0);
const len = Math.max(left.length, right.length);
for (let i = 0; i < len; i++) {
const x = left[i] || 0;
const y = right[i] || 0;
if (x !== y) return x - y;
}
return 0;
}
/**
* 把 WorkspaceLeaf 安全地转成 ReaderView
*
* 不能直接 `leaf.view as ReaderView` —— Obsidian 有时给的是「延迟加载的壳」,
* 类型对但方法不全,调 showData 会 TypeError 且位置很隐蔽。
* 这里用 instanceof 卡一道,拿不到就返回 null,交给待渲染状态兜底。
*/
function asReaderView(leaf: WorkspaceLeaf): ReaderView | null {
const view = leaf.view;
return view instanceof ReaderView ? view : null;
}