359 lines
10 KiB
TypeScript
359 lines
10 KiB
TypeScript
import {
|
||
ItemView,
|
||
MarkdownRenderer,
|
||
Notice,
|
||
TFile,
|
||
WorkspaceLeaf,
|
||
setIcon,
|
||
} from "obsidian";
|
||
import { RuItem, tagLabels } from "../utils/api";
|
||
import { ExtractedArticle } from "../utils/extract";
|
||
import { dayStamp, formatFullDate, safeFileName } from "../utils/datetime";
|
||
import { getSettings } from "../setting/store";
|
||
import i18n from "../utils/i18n";
|
||
|
||
export const VIEW_TYPE_READER = "ru-reader-view";
|
||
|
||
export interface ReaderState {
|
||
item: RuItem | null;
|
||
article: ExtractedArticle | null;
|
||
loading: boolean;
|
||
error: string;
|
||
}
|
||
|
||
/**
|
||
* 待渲染状态(模块级)
|
||
*
|
||
* 列表那边点文章时先写这里,再去开面板。这样即使面板是刚创建的、
|
||
* `leaf.view` 还没就绪(DeferredView),`onOpen` 也能从这拿到数据自己画一遍,
|
||
* 不会出现「抓到了但窗口空白」。
|
||
*
|
||
* 只更新不取走:窗口关掉再打开还能恢复上一篇。
|
||
*/
|
||
let pendingState: ReaderState | null = null;
|
||
|
||
export function setPendingReaderState(state: ReaderState): void {
|
||
pendingState = state;
|
||
}
|
||
|
||
export function peekPendingReaderState(): ReaderState | null {
|
||
return pendingState;
|
||
}
|
||
|
||
/**
|
||
* 阅读窗口:全文抓完在这里渲染
|
||
*
|
||
* 用 MarkdownRenderer 渲染而不是塞 innerHTML —— 原文里带出来的脚本 / 事件属性
|
||
* 会被 Obsidian 的渲染管线挡掉,抓外站内容时这一点很重要。
|
||
*/
|
||
export class ReaderView extends ItemView {
|
||
private state: ReaderState = { item: null, article: null, loading: false, error: "" };
|
||
private bodyEl: HTMLElement | null = null;
|
||
private titleEl: HTMLElement | null = null;
|
||
private metaEl: HTMLElement | null = null;
|
||
private actionsEl: HTMLElement | null = null;
|
||
|
||
constructor(leaf: WorkspaceLeaf) {
|
||
super(leaf);
|
||
this.ensureChrome();
|
||
}
|
||
|
||
/**
|
||
* 补齐 ItemView 的头部结构
|
||
*
|
||
* 从 split 出来的新 leaf 打开时,Obsidian 内部会在 header 还没建好的情况下
|
||
* 去拿 `.view-header-title` 并调 setText,拿到 null 直接抛
|
||
* 「Cannot read properties of null (reading 'setText')」,整个 view 就没了。
|
||
* 这里在构造阶段先把元素建出来,让那一步无论如何都能拿到东西。
|
||
*/
|
||
private ensureChrome(): void {
|
||
const self = this as unknown as {
|
||
headerEl?: HTMLElement | null;
|
||
titleEl?: HTMLElement | null;
|
||
};
|
||
|
||
try {
|
||
if (!this.containerEl) return;
|
||
|
||
let header = self.headerEl || null;
|
||
|
||
if (!header) {
|
||
header = this.containerEl.createDiv({ cls: "view-header" });
|
||
self.headerEl = header;
|
||
}
|
||
|
||
let title = self.titleEl || null;
|
||
|
||
if (!title) {
|
||
title = header.createDiv({ cls: "view-header-title" });
|
||
self.titleEl = title;
|
||
}
|
||
} catch (error) {
|
||
console.warn("RssUnion: 补齐阅读窗口头部失败", error);
|
||
}
|
||
}
|
||
|
||
getViewType(): string {
|
||
return VIEW_TYPE_READER;
|
||
}
|
||
|
||
getDisplayText(): string {
|
||
// 构造期间 state 可能还没初始化,别让 Obsidian 取标题时踩空
|
||
return this.state?.item?.title || i18n.t("reader.title");
|
||
}
|
||
|
||
getIcon(): string {
|
||
return "book-open";
|
||
}
|
||
|
||
async onOpen(): Promise<void> {
|
||
this.build();
|
||
this.paint();
|
||
|
||
// 面板刚建出来时,列表那边可能已经把数据写进待渲染状态了
|
||
const pending = peekPendingReaderState();
|
||
|
||
if (pending) this.showData(pending);
|
||
}
|
||
|
||
/** 当前是否已经能安全接收数据(DOM 建好了) */
|
||
isReady(): boolean {
|
||
return this.bodyEl !== null;
|
||
}
|
||
|
||
async onClose(): Promise<void> {
|
||
this.bodyEl = null;
|
||
this.titleEl = null;
|
||
this.metaEl = null;
|
||
this.actionsEl = null;
|
||
}
|
||
|
||
/** 外部(列表)把数据推进来(不覆盖 ItemView.setState,那个是持久化状态用的) */
|
||
showData(next: ReaderState): void {
|
||
this.state = next;
|
||
this.paint();
|
||
}
|
||
|
||
/** 重新渲染当前状态(「重试」用) */
|
||
getCurrentItem(): RuItem | null {
|
||
return this.state.item;
|
||
}
|
||
|
||
private build(): void {
|
||
const root = this.contentEl;
|
||
|
||
root.empty();
|
||
root.addClass("ru-reader");
|
||
|
||
const bar = root.createDiv({ cls: "ru-reader__bar" });
|
||
|
||
this.titleEl = bar.createDiv({ cls: "ru-reader__title" });
|
||
this.actionsEl = bar.createDiv({ cls: "ru-reader__actions" });
|
||
this.metaEl = root.createDiv({ cls: "ru-reader__meta" });
|
||
this.bodyEl = root.createDiv({ cls: "ru-reader__content markdown-rendered" });
|
||
}
|
||
|
||
private paint(): void {
|
||
if (!this.bodyEl || !this.titleEl || !this.metaEl || !this.actionsEl) return;
|
||
|
||
const { item, article, loading, error } = this.state;
|
||
|
||
this.actionsEl.empty();
|
||
this.titleEl.setText(item?.title || i18n.t("reader.title"));
|
||
this.metaEl.empty();
|
||
this.bodyEl.empty();
|
||
|
||
if (item) {
|
||
const bits = [item.siteTitle, item.categoryName, formatFullDate(item.pubDate)].filter(Boolean);
|
||
|
||
this.metaEl.setText(bits.join(" · "));
|
||
this.metaEl.createSpan({ cls: "ru-reader__origin", text: item.link });
|
||
}
|
||
|
||
// 头部按钮:只在有原文地址时给「浏览器打开」,抓到了才给「保存为笔记」
|
||
if (item?.link) {
|
||
this.iconButton(this.actionsEl, "external-link", i18n.t("reader.openSource"), () => {
|
||
window.open(item.link, "_blank");
|
||
});
|
||
}
|
||
|
||
if (article) {
|
||
this.iconButton(this.actionsEl, "file-down", i18n.t("reader.saveNote"), () => {
|
||
void this.saveNote();
|
||
});
|
||
|
||
this.iconButton(this.actionsEl, "copy", i18n.t("reader.copyAll"), () => {
|
||
void this.copyAll();
|
||
});
|
||
}
|
||
|
||
if (loading) {
|
||
const box = this.bodyEl.createDiv({ cls: "ru-reader__state" });
|
||
|
||
box.createDiv({ cls: "ru-spinner" });
|
||
box.createEl("div", { cls: "ru-reader__state-title", text: i18n.t("reader.fetching") });
|
||
box.createEl("div", { cls: "ru-reader__state-desc", text: i18n.t("reader.fetchingHint") });
|
||
|
||
return;
|
||
}
|
||
|
||
if (error) {
|
||
const box = this.bodyEl.createDiv({ cls: "ru-reader__state is-error" });
|
||
|
||
box.createEl("div", { cls: "ru-reader__state-title", text: i18n.t("reader.failed") });
|
||
box.createEl("div", { cls: "ru-reader__state-desc", text: error });
|
||
|
||
const acts = box.createDiv({ cls: "ru-reader__state-acts" });
|
||
|
||
if (item?.link) {
|
||
const open = acts.createEl("button", { text: i18n.t("reader.openSource") });
|
||
|
||
open.addEventListener("click", () => window.open(item.link, "_blank"));
|
||
}
|
||
|
||
return;
|
||
}
|
||
|
||
if (!article) {
|
||
this.bodyEl.createEl("div", { cls: "ru-reader__state-desc", text: i18n.t("reader.fetchingHint") });
|
||
return;
|
||
}
|
||
|
||
if (article.usedFallback) {
|
||
this.bodyEl.createDiv({
|
||
cls: "ru-reader__notice",
|
||
text: "这篇用的是兜底抽取(正文结构不太标准),排版可能不完整;需要的话可以「浏览器打开」对照。",
|
||
});
|
||
}
|
||
|
||
const sourcePath = "";
|
||
|
||
void this.renderMarkdown(article.markdown, sourcePath);
|
||
|
||
// 字数放最后,避免和头部的 meta 抢视觉位置
|
||
this.metaEl.createSpan({ cls: "ru-reader__count", text: i18n.t("reader.words", { n: article.charCount }) });
|
||
}
|
||
|
||
private async renderMarkdown(markdown: string, sourcePath: string): Promise<void> {
|
||
if (!this.bodyEl) return;
|
||
|
||
const renderer: any = MarkdownRenderer;
|
||
|
||
try {
|
||
if (typeof renderer.render === "function") {
|
||
await renderer.render(this.app, markdown, this.bodyEl, sourcePath, this);
|
||
} else if (typeof renderer.renderMarkdown === "function") {
|
||
// 1.4 之前的旧 API
|
||
await renderer.renderMarkdown(markdown, this.bodyEl, sourcePath, this);
|
||
} else {
|
||
this.bodyEl.setText(markdown);
|
||
}
|
||
} catch (error) {
|
||
console.error("RssUnion: Markdown 渲染失败", error);
|
||
this.bodyEl.setText(markdown);
|
||
}
|
||
}
|
||
|
||
private iconButton(parent: HTMLElement, icon: string, label: string, onClick: () => void): HTMLElement {
|
||
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;
|
||
}
|
||
|
||
private async copyAll(): Promise<void> {
|
||
const markdown = this.state.article?.markdown || "";
|
||
|
||
if (!markdown) return;
|
||
|
||
try {
|
||
await navigator.clipboard.writeText(markdown);
|
||
new Notice(i18n.t("common.copied"));
|
||
} catch (error) {
|
||
new Notice("复制失败,可能浏览器不允许访问剪贴板");
|
||
}
|
||
}
|
||
|
||
private async saveNote(): Promise<void> {
|
||
const { item, article } = this.state;
|
||
|
||
if (!item || !article) return;
|
||
|
||
const folderRaw = String(getSettings().saveFolder || "").trim().replace(/^\/+|\/+$/g, "");
|
||
const folder = folderRaw === "" ? "" : folderRaw;
|
||
const fileName = `${dayStamp(item.pubDate)} ${safeFileName(item.title || article.title)}.md`;
|
||
const path = folder === "" ? fileName : `${folder}/${fileName}`;
|
||
|
||
try {
|
||
if (folder !== "") {
|
||
await this.ensureFolder(folder);
|
||
}
|
||
|
||
const content = this.noteContent(item, article);
|
||
const existing = this.app.vault.getAbstractFileByPath(path);
|
||
|
||
if (existing instanceof TFile) {
|
||
await this.app.vault.modify(existing, content);
|
||
} else {
|
||
await this.app.vault.create(path, content);
|
||
}
|
||
|
||
new Notice(i18n.t("reader.saved", { path }));
|
||
} catch (error: any) {
|
||
new Notice(`保存失败:${error?.message || error}`);
|
||
}
|
||
}
|
||
|
||
private async ensureFolder(folder: string): Promise<void> {
|
||
const parts = folder.split("/").filter(Boolean);
|
||
let current = "";
|
||
|
||
for (const part of parts) {
|
||
current = current === "" ? part : `${current}/${part}`;
|
||
|
||
if (!this.app.vault.getAbstractFileByPath(current)) {
|
||
await this.app.vault.createFolder(current);
|
||
}
|
||
}
|
||
}
|
||
|
||
private noteContent(item: RuItem, article: ExtractedArticle): string {
|
||
const escape = (value: string) => String(value || "").replace(/"/g, '\\"');
|
||
const tags = tagLabels(item.tags).join(", ");
|
||
|
||
const front = [
|
||
"---",
|
||
`title: "${escape(item.title || article.title)}"`,
|
||
`url: ${item.link}`,
|
||
`site: "${escape(item.siteTitle)}"`,
|
||
`category: "${escape(item.categoryName)}"`,
|
||
`published: ${item.pubDate}`,
|
||
`fetched: ${new Date().toISOString()}`,
|
||
"source: RssUnion",
|
||
tags ? `tags: [${tags}]` : null,
|
||
"---",
|
||
]
|
||
.filter((line): line is string => line !== null)
|
||
.join("\n");
|
||
|
||
return [
|
||
front,
|
||
"",
|
||
`# ${item.title || article.title}`,
|
||
"",
|
||
`> 来源:[${item.siteTitle || article.siteName}](${item.link}) · ${formatFullDate(item.pubDate)}`,
|
||
"",
|
||
article.markdown,
|
||
"",
|
||
].join("\n");
|
||
}
|
||
}
|