Files

890 lines
28 KiB
TypeScript
Raw Permalink Normal View History

import { Plugin, Notice, Modal, requestUrl, PluginSettingTab, App, Setting } from "obsidian";
interface XHSSyncSettings {
defaultFolder: string;
categories: string[];
lastCategory: string;
downloadMedia: boolean;
aiEnabled: boolean;
aiApiKey: string;
aiApiUrl: string;
aiModel: string;
}
const DEFAULT_SETTINGS: XHSSyncSettings = {
defaultFolder: "xhs",
categories: ["美食", "旅行", "娱乐", "知识", "工作", "情感", "个人成长", "优惠", "搞笑", "育儿"],
lastCategory: "",
downloadMedia: false,
aiEnabled: false,
aiApiKey: "",
aiApiUrl: "https://api.deepseek.com/chat/completions",
aiModel: "deepseek-chat",
};
export default class XHSSyncPlugin extends Plugin {
settings: XHSSyncSettings;
async onload() {
await this.loadSettings();
this.addRibbonIcon("book", "导入小红书笔记", async () => {
const input = await this.promptForShareText();
if (input && input.text) {
const url = this.extractURL(input.text);
if (url) {
await this.importXHSNote(url, input.category, input.downloadMedia);
} else {
new Notice("未在文本中找到有效的小红书链接。");
}
}
});
this.addCommand({
id: "import",
name: "导入小红书笔记",
callback: async () => {
const input = await this.promptForShareText();
if (input && input.text) {
const url = this.extractURL(input.text);
if (url) {
await this.importXHSNote(url, input.category, input.downloadMedia);
} else {
new Notice("未在文本中找到有效的小红书链接。");
}
}
},
});
this.addSettingTab(new XHSSyncSettingTab(this.app, this));
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
async promptForShareText(): Promise<{ text: string | null; category: string; downloadMedia: boolean } | null> {
return new Promise((resolve) => {
const modal = new XHSInputModal(this.app, this, (result) => resolve(result));
modal.open();
});
}
extractURL(shareText: string): string | null {
const mobileUrlMatch = shareText.match(/https?:\/\/xhslink\.(?:com|cn)\/[a-zA-Z0-9/?=&._-]+/);
if (mobileUrlMatch) {
return mobileUrlMatch[0];
}
const webUrlMatch = shareText.match(/https?:\/\/www\.xiaohongshu\.com\/(?:discovery\/item|explore)\/[a-zA-Z0-9]+(?:\?[^\s,,]*)?/);
if (webUrlMatch) {
return webUrlMatch[0].replace('/explore/', '/discovery/item/');
}
return null;
}
// ===== AI 调用底层方法 =====
async callAI(systemPrompt: string, userContent: string): Promise<string> {
const response = await requestUrl({
url: this.settings.aiApiUrl,
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${this.settings.aiApiKey}`,
},
body: JSON.stringify({
model: this.settings.aiModel,
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: userContent },
],
temperature: 0.7,
}),
});
const json = response.json;
const content = json?.choices?.[0]?.message?.content;
if (!content) throw new Error("AI 返回内容为空");
return content.trim();
}
// ===== AI 生成标题 =====
async generateTitleWithAI(content: string): Promise<string> {
try {
const result = await this.callAI(
"你是小红书笔记标题助手。请根据用户提供的笔记正文,生成一个简洁的中文标题。要求:不超过 20 个字,不要标点符号,不要引号,不要表情符号,只返回标题本身。",
content.substring(0, 1500)
);
let title = result.replace(/["""'']/g, "").replace(/[。!?,、;:]/g, "").trim();
title = title.substring(0, 20);
return title || "";
} catch (e) {
console.log(`AI 生成标题失败:${e.message}`);
return "";
}
}
// ===== AI 生成标签 =====
async generateTagsWithAI(content: string): Promise<string[]> {
try {
const result = await this.callAI(
"你是小红书笔记标签助手。请根据用户提供的笔记正文,生成 3-6 个中文标签。要求:每个标签不超过 8 个字,不要带 # 号,不要标点符号。只返回一个 JSON 数组,例如 [\"自然教育\",\"户外活动\"],不要有其他文字。",
content.substring(0, 2000)
);
const jsonMatch = result.match(/\[[\s\S]*\]/);
if (jsonMatch) {
const tags = JSON.parse(jsonMatch[0]);
if (Array.isArray(tags)) {
return tags
.map((t: any) => String(t).replace(/[#\s]/g, "").trim())
.filter((t: string) => t.length > 0)
.slice(0, 6);
}
}
} catch (e) {
console.log(`AI 生成标签失败:${e.message}`);
}
return [];
}
// ===== AI 生成摘要(标题扩写 + 按类型适配) =====
async generateSummaryWithAI(content: string): Promise<string> {
try {
const fullContent = content.length > 8000 ? content.substring(0, 8000) : content;
const result = await this.callAI(
`你是笔记摘要助手。请先判断这篇笔记的类型,再按对应方式写摘要:
- 观点论述型:提炼最核心的观点或结论
- 清单/数据型:概括内容主题 + 列出最重要的 1-2 个关键数据或条目
- 教程/步骤型:概括目标 + 核心步骤
摘要其实内容更丰富的标题,要让读者一眼知道这篇笔记主要讲了什么。严格控制在 60 字以内,只返回摘要本身,不要分点,不要表情符号,不要引号。`,
fullContent
);
return result.replace(/\n+/g, " ").trim();
} catch (e) {
console.log(`AI 生成摘要失败:${e.message}`);
return "";
}
}
async downloadMediaFile(url: string, folderPath: string, filename: string): Promise<string> {
try {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP 错误 ${response.status}`);
const blob = await response.blob();
const arrayBuffer = await blob.arrayBuffer();
const filePath = `${folderPath}/${filename}`;
await this.app.vault.adapter.writeBinary(filePath, arrayBuffer);
return filename;
} catch (error) {
console.log(`下载媒体失败 ${url}: ${error.message}`);
new Notice(`下载媒体失败:${error.message}`);
return url;
}
}
formatContent(rawContent: string): string {
let text = rawContent;
text = text.replace(/#[^#\s]*(?:\s+#[^#\s]*)*\s*/g, "");
const lines = text.split("\n").map((line) => line.trim());
const paragraphs: string[] = [];
let buffer: string[] = [];
for (const line of lines) {
if (line === "") {
if (buffer.length > 0) {
paragraphs.push(buffer.join(" "));
buffer = [];
}
} else {
buffer.push(line);
}
}
if (buffer.length > 0) {
paragraphs.push(buffer.join(" "));
}
return paragraphs.join("\n\n");
}
formatDateTime(date: Date): string {
const y = date.getFullYear();
const m = String(date.getMonth() + 1).padStart(2, "0");
const d = String(date.getDate()).padStart(2, "0");
const hh = String(date.getHours()).padStart(2, "0");
const mm = String(date.getMinutes()).padStart(2, "0");
const ss = String(date.getSeconds()).padStart(2, "0");
return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
}
async importXHSNote(url: string, category: string, downloadMedia: boolean) {
try {
const response = await requestUrl({ url });
const html = response.text;
let title = this.extractTitle(html);
const videoUrl = this.extractVideoUrl(html);
const images = this.extractImages(html);
const content = this.extractContent(html);
const isVideo = this.isVideoNote(html);
const author = this.extractAuthor(html);
const publishTime = this.extractPublishTime(html);
const now = new Date();
const noteDate = this.formatDateTime(now).split(" ")[0];
const importedAt = this.formatDateTime(now);
// ===== AI 处理 =====
let aiSummary = "";
let tags: string[] = [];
if (this.settings.aiEnabled && this.settings.aiApiKey) {
if (!title || title.trim().length === 0) {
new Notice("正在用 AI 生成标题...");
const aiTitle = await this.generateTitleWithAI(content);
if (aiTitle) title = aiTitle;
}
new Notice("正在用 AI 生成标签...");
tags = await this.generateTagsWithAI(content);
new Notice("正在用 AI 生成摘要...");
aiSummary = await this.generateSummaryWithAI(content);
}
if (!title || title.trim().length === 0) {
const firstLine = content.split("\n")[0].trim();
title = firstLine.substring(0, 20) || "无标题";
}
if (tags.length === 0) {
tags = this.extractTags(content);
}
const baseFolder = this.settings.defaultFolder || "xhs";
const categoryFolder = category || "未分类";
const folderPath = baseFolder ? `${baseFolder}/${categoryFolder}` : categoryFolder;
let safeTitle = title
.replace(/[/\\?%*:|"<>]/g, "-")
.replace(/[\x00-\x1f\x7f]/g, "")
.replace(/\s+/g, " ")
.trim();
safeTitle = safeTitle.length > 0 ? safeTitle : "无标题";
safeTitle = safeTitle.substring(0, 20);
const datePrefix = noteDate;
const fileBaseName = `${datePrefix}_${safeTitle}`;
const hasMedia = (images.length > 0 || (isVideo && videoUrl)) && downloadMedia;
let notePath: string;
let mediaFolder: string;
if (hasMedia) {
const noteFolder = `${folderPath}/${fileBaseName}`;
if (!await this.app.vault.adapter.exists(noteFolder)) {
await this.app.vault.createFolder(noteFolder);
}
notePath = `${noteFolder}/${fileBaseName}.md`;
mediaFolder = noteFolder;
} else {
if (!await this.app.vault.adapter.exists(folderPath)) {
await this.app.vault.createFolder(folderPath);
}
notePath = `${folderPath}/${fileBaseName}.md`;
mediaFolder = folderPath;
}
const formattedContent = this.formatContent(content);
let frontmatterTags = "tags: []\n";
if (tags.length > 0) {
frontmatterTags = "tags:\n" + tags.map((tag) => ` - ${tag}`).join("\n") + "\n";
}
let markdown = `---
title: ${title}
作者: ${author.nickname || "未知作者"}
作者主页: ${author.profileUrl || ""}
发布时间: ${publishTime || "未知"}
source: ${url}
导入时间: ${importedAt}
分类: ${category}
${frontmatterTags}---
# ${title}
`;
if (aiSummary) {
markdown += `> [!abstract] AI 摘要\n> ${aiSummary}\n\n`;
}
if (isVideo) {
if (videoUrl) {
let finalVideoUrl = videoUrl;
if (downloadMedia) {
const videoFilename = `video.mp4`;
const downloadedFilename = await this.downloadMediaFile(videoUrl, mediaFolder, videoFilename);
finalVideoUrl = downloadedFilename.startsWith("http") ? downloadedFilename : `./${downloadedFilename}`;
}
markdown += `<video controls src="${finalVideoUrl}" width="100%"></video>\n\n`;
} else if (images.length > 0) {
let finalImageUrl = images[0];
if (downloadMedia) {
const imageFilename = `1.jpg`;
const downloadedFilename = await this.downloadMediaFile(images[0], mediaFolder, imageFilename);
finalImageUrl = downloadedFilename.startsWith("http") ? downloadedFilename : `./${downloadedFilename}`;
}
markdown += `[![封面图](${finalImageUrl})](${url})\n\n`;
new Notice("未找到视频地址,已使用封面图替代。");
}
}
markdown += `${formattedContent}\n\n`;
if (!isVideo && images.length > 0) {
markdown += `---\n\n## 图片\n\n`;
let downloadedImages: string[] = [];
if (downloadMedia) {
for (let i = 0; i < images.length; i++) {
const imageFilename = `${i + 1}.jpg`;
const downloadedFilename = await this.downloadMediaFile(images[i], mediaFolder, imageFilename);
const finalImageUrl = downloadedFilename.startsWith("http") ? downloadedFilename : `./${downloadedFilename}`;
downloadedImages.push(finalImageUrl);
}
} else {
downloadedImages = images;
}
markdown += downloadedImages.map((url, idx) => `**图 ${idx + 1}**\n\n![图片](${url})`).join("\n\n") + "\n";
}
const file = await this.app.vault.create(notePath, markdown);
await this.app.workspace.getLeaf(true).openFile(file);
this.settings.lastCategory = category;
await this.saveSettings();
new Notice(`已导入小红书笔记:${notePath}`);
} catch (error) {
console.log(`导入笔记失败 ${url}: ${error.message}`);
new Notice(`导入笔记失败:${error.message}`);
}
}
extractTitle(html: string): string {
const stateMatch = html.match(/window\.__INITIAL_STATE__=(.*?)<\/script>/s);
if (stateMatch) {
try {
const jsonStr = stateMatch[1].trim();
const cleanedJson = jsonStr.replace(/undefined/g, "null");
const state = JSON.parse(cleanedJson);
const noteId = Object.keys(state.note.noteDetailMap)[0];
const note = state.note.noteDetailMap[noteId].note;
const titleFromState = note.title || note.displayTitle || "";
if (titleFromState && titleFromState.trim().length > 0) {
return titleFromState.trim();
}
} catch (e) {
console.log(`从 JSON 解析标题失败:${e.message}`);
}
}
return "";
}
extractImages(html: string): string[] {
const stateMatch = html.match(/window\.__INITIAL_STATE__=(.*?)<\/script>/s);
if (!stateMatch) return [];
try {
const jsonStr = stateMatch[1].trim();
const cleanedJson = jsonStr.replace(/undefined/g, "null");
const state = JSON.parse(cleanedJson);
const noteId = Object.keys(state.note.noteDetailMap)[0];
const imageList = state.note.noteDetailMap[noteId].note.imageList || [];
return imageList
.map((img: any) => img.urlDefault || "")
.filter((url: string) => url && url.startsWith("http"));
} catch (e) {
console.log(`解析图片失败:${e.message}`);
return [];
}
}
extractVideoUrl(html: string): string | null {
const stateMatch = html.match(/window\.__INITIAL_STATE__=(.*?)<\/script>/s);
if (!stateMatch) return null;
try {
const jsonStr = stateMatch[1].trim();
const cleanedJson = jsonStr.replace(/undefined/g, "null");
const state = JSON.parse(cleanedJson);
const noteId = Object.keys(state.note.noteDetailMap)[0];
const noteData = state.note.noteDetailMap[noteId].note;
const videoInfo = noteData.video;
if (!videoInfo || !videoInfo.media || !videoInfo.media.stream) return null;
if (videoInfo.media.stream.h264 && videoInfo.media.stream.h264.length > 0) {
return videoInfo.media.stream.h264[0].masterUrl || null;
}
if (videoInfo.media.stream.h265 && videoInfo.media.stream.h265.length > 0) {
return videoInfo.media.stream.h265[0].masterUrl || null;
}
return null;
} catch (e) {
console.log(`解析视频失败:${e.message}`);
return null;
}
}
extractContent(html: string): string {
const divMatch = html.match(/<div id="detail-desc" class="desc">([\s\S]*?)<\/div>/);
if (divMatch) {
return divMatch[1]
.replace(/<[^>]+>/g, "")
.replace(/\[话题\]/g, "")
.replace(/\[[^\]]+\]/g, "")
.trim() || "未找到正文内容";
}
const stateMatch = html.match(/window\.__INITIAL_STATE__=(.*?)<\/script>/s);
if (stateMatch) {
try {
const jsonStr = stateMatch[1].trim();
const cleanedJson = jsonStr.replace(/undefined/g, "null");
const state = JSON.parse(cleanedJson);
const noteId = Object.keys(state.note.noteDetailMap)[0];
const desc = state.note.noteDetailMap[noteId].note.desc || "";
return desc
.replace(/\[话题\]/g, "")
.replace(/\[[^\]]+\]/g, "")
.trim() || "未找到正文内容";
} catch (e) {
console.log(`解析正文失败:${e.message}`);
}
}
return "未找到正文内容";
}
isVideoNote(html: string): boolean {
const stateMatch = html.match(/window\.__INITIAL_STATE__=(.*?)<\/script>/s);
if (!stateMatch) return false;
try {
const jsonStr = stateMatch[1].trim();
const cleanedJson = jsonStr.replace(/undefined/g, "null");
const state = JSON.parse(cleanedJson);
const noteId = Object.keys(state.note.noteDetailMap)[0];
const noteType = state.note.noteDetailMap[noteId].note.type;
return noteType === "video";
} catch (e) {
console.log(`判断笔记类型失败:${e.message}`);
return false;
}
}
extractAuthor(html: string): { nickname: string; profileUrl: string } {
const stateMatch = html.match(/window\.__INITIAL_STATE__=(.*?)<\/script>/s);
if (!stateMatch) return { nickname: "", profileUrl: "" };
try {
const jsonStr = stateMatch[1].trim();
const cleanedJson = jsonStr.replace(/undefined/g, "null");
const state = JSON.parse(cleanedJson);
const noteId = Object.keys(state.note.noteDetailMap)[0];
const note = state.note.noteDetailMap[noteId].note;
const user = note.user || {};
const nickname = user.nickname || user.nickName || "";
const userId = user.userId || user.user_id || "";
const profileUrl = userId ? `https://www.xiaohongshu.com/user/profile/${userId}` : "";
return { nickname, profileUrl };
} catch (e) {
console.log(`解析作者信息失败:${e.message}`);
return { nickname: "", profileUrl: "" };
}
}
extractPublishTime(html: string): string {
const stateMatch = html.match(/window\.__INITIAL_STATE__=(.*?)<\/script>/s);
if (!stateMatch) return "";
try {
const jsonStr = stateMatch[1].trim();
const cleanedJson = jsonStr.replace(/undefined/g, "null");
const state = JSON.parse(cleanedJson);
const noteId = Object.keys(state.note.noteDetailMap)[0];
const note = state.note.noteDetailMap[noteId].note;
const rawTime = note.time || note.publishTime || "";
if (!rawTime) return "";
const date = new Date(Number(rawTime));
if (isNaN(date.getTime())) return "";
const y = date.getFullYear();
const m = String(date.getMonth() + 1).padStart(2, "0");
const d = String(date.getDate()).padStart(2, "0");
return `${y}-${m}-${d}`;
} catch (e) {
console.log(`解析发布时间失败:${e.message}`);
return "";
}
}
extractTags(content: string): string[] {
const tagMatches = content.match(/#[\w\u4e00-\u9fa5-]+/g) || [];
return tagMatches.map((tag) => tag.replace("#", "").trim());
}
onunload() {}
}
class XHSSyncSettingTab extends PluginSettingTab {
plugin: XHSSyncPlugin;
constructor(app: App, plugin: XHSSyncPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
containerEl.empty();
new Setting(containerEl)
.setName("默认存储文件夹")
.setDesc("笔记保存的基础文件夹。留空则保存到库根目录。")
.addText((text) =>
text
.setPlaceholder("xhs")
.setValue(this.plugin.settings.defaultFolder)
.onChange(async (value) => {
this.plugin.settings.defaultFolder = value.trim();
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName("默认下载媒体")
.setDesc("开启后,导入时默认将图片和视频下载到本地。每次导入时仍可单独覆盖。")
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.downloadMedia)
.onChange(async (value) => {
this.plugin.settings.downloadMedia = value;
await this.plugin.saveSettings();
})
);
const aiHeading = new Setting(containerEl)
.setName("AI 功能")
.setHeading();
aiHeading.settingEl.addClass("xhs-setting-heading");
containerEl.createEl("p", {
text: "开启后,导入笔记时会调用 AI 自动生成标题(仅无标题时)、标签和摘要。需要填写 DeepSeek API Key。",
});
new Setting(containerEl)
.setName("开启 AI 功能")
.setDesc("关闭时,标题和标签走原有逻辑,不生成摘要。")
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.aiEnabled)
.onChange(async (value) => {
this.plugin.settings.aiEnabled = value;
await this.plugin.saveSettings();
this.display();
})
);
if (this.plugin.settings.aiEnabled) {
new Setting(containerEl)
.setName("AI API Key")
.setDesc("DeepSeek 的 API Key,形如 sk-xxxxxx。")
.addText((text) =>
text
.setPlaceholder("sk-...")
.setValue(this.plugin.settings.aiApiKey)
.onChange(async (value) => {
this.plugin.settings.aiApiKey = value.trim();
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName("AI API 地址")
.setDesc("默认使用 DeepSeek 官方接口。如果使用其他兼容 OpenAI 格式的服务,可以改这里。")
.addText((text) =>
text
.setPlaceholder("https://api.deepseek.com/chat/completions")
.setValue(this.plugin.settings.aiApiUrl)
.onChange(async (value) => {
this.plugin.settings.aiApiUrl = value.trim();
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName("AI 模型名")
.setDesc("默认 deepseek-chat。")
.addText((text) =>
text
.setPlaceholder("deepseek-chat")
.setValue(this.plugin.settings.aiModel)
.onChange(async (value) => {
this.plugin.settings.aiModel = value.trim();
await this.plugin.saveSettings();
})
);
}
const headingSetting = new Setting(containerEl)
.setName("分类管理")
.setHeading();
headingSetting.settingEl.addClass("xhs-setting-heading");
containerEl.createEl("p", { text: "添加、编辑或删除用于整理笔记的分类。使用上下箭头调整顺序。" });
this.plugin.settings.categories.forEach((category, index) => {
const setting = new Setting(containerEl)
.setName(`分类 ${index + 1}`)
.addText((text) =>
text
.setValue(category)
.onChange(async (value) => {
this.plugin.settings.categories[index] = value.trim();
await this.plugin.saveSettings();
})
);
setting.addButton((button) =>
button
.setIcon("arrow-up")
.setTooltip("上移")
.setDisabled(index === 0)
.onClick(async () => {
if (index > 0) {
[this.plugin.settings.categories[index], this.plugin.settings.categories[index - 1]] =
[this.plugin.settings.categories[index - 1], this.plugin.settings.categories[index]];
await this.plugin.saveSettings();
this.display();
}
})
);
setting.addButton((button) =>
button
.setIcon("arrow-down")
.setTooltip("下移")
.setDisabled(index === this.plugin.settings.categories.length - 1)
.onClick(async () => {
if (index < this.plugin.settings.categories.length - 1) {
[this.plugin.settings.categories[index], this.plugin.settings.categories[index + 1]] =
[this.plugin.settings.categories[index + 1], this.plugin.settings.categories[index]];
await this.plugin.saveSettings();
this.display();
}
})
);
setting.addButton((button) =>
button
.setButtonText("删除")
.onClick(async () => {
this.plugin.settings.categories.splice(index, 1);
await this.plugin.saveSettings();
this.display();
})
);
});
new Setting(containerEl)
.addButton((button) =>
button
.setButtonText("添加分类")
.onClick(async () => {
this.plugin.settings.categories.push("新分类");
await this.plugin.saveSettings();
this.display();
})
);
}
}
class XHSInputModal extends Modal {
result: { text: string | null; category: string; downloadMedia: boolean } | null = null;
onSubmit: (result: { text: string | null; category: string; downloadMedia: boolean } | null) => void;
plugin: XHSSyncPlugin;
selectedCategory: string;
downloadMedia: boolean;
constructor(app: App, plugin: XHSSyncPlugin, onSubmit: (result: { text: string | null; category: string; downloadMedia: boolean } | null) => void) {
super(app);
this.plugin = plugin;
this.onSubmit = onSubmit;
this.selectedCategory = this.plugin.settings.lastCategory && this.plugin.settings.categories.includes(this.plugin.settings.lastCategory)
? this.plugin.settings.lastCategory
: this.plugin.settings.categories[0] || "其他";
this.downloadMedia = this.plugin.settings.downloadMedia;
}
onOpen() {
const { contentEl } = this;
contentEl.addClass("xhs-modal-content");
contentEl.createEl("h2", { text: "导入小红书笔记" });
const textRow = contentEl.createEl("div", { cls: "xhs-modal-row" });
textRow.createEl("p", { text: "粘贴分享文本:" });
const input = textRow.createEl("textarea", {
cls: "xhs-modal-textarea",
attr: { placeholder: "例如:64 不叫小黄了发布了一篇小红书笔记..." },
});
const categoryRow = contentEl.createEl("div", { cls: "xhs-modal-row" });
categoryRow.createEl("p", { text: "选择分类:" });
const chipContainer = categoryRow.createEl("div", { cls: "xhs-chip-container" });
const addCategoryRow = contentEl.createEl("div", { cls: "xhs-add-category-row" });
const newCategoryInput = addCategoryRow.createEl("input", {
cls: "xhs-add-category-input",
attr: { type: "text", placeholder: "新增分类名称" },
});
const addCategoryButton = addCategoryRow.createEl("button", {
text: "新增分类",
cls: "xhs-add-category-button",
});
const updateChipStyles = () => {
chipContainer.querySelectorAll("button").forEach((btn) => {
if (btn.textContent === this.selectedCategory) {
btn.classList.add("xhs-chip--selected");
} else {
btn.classList.remove("xhs-chip--selected");
}
});
};
const renderChips = () => {
chipContainer.empty();
this.plugin.settings.categories.forEach((category) => {
const chip = chipContainer.createEl("button", {
text: category,
cls: "xhs-chip",
});
if (category === this.selectedCategory) {
chip.classList.add("xhs-chip--selected");
}
chip.addEventListener("click", () => {
this.selectedCategory = category;
updateChipStyles();
});
});
const otherChip = chipContainer.createEl("button", {
text: "其他",
cls: "xhs-chip",
});
if ("其他" === this.selectedCategory) {
otherChip.classList.add("xhs-chip--selected");
}
otherChip.addEventListener("click", () => {
this.selectedCategory = "其他";
updateChipStyles();
});
};
renderChips();
const handleAddCategory = async () => {
const name = newCategoryInput.value.trim();
if (!name) {
new Notice("请输入分类名称。");
return;
}
if (name === "其他") {
new Notice("“其他”是保留分类,请换一个名称。");
return;
}
if (this.plugin.settings.categories.includes(name)) {
new Notice("该分类已存在。");
return;
}
this.plugin.settings.categories.push(name);
await this.plugin.saveSettings();
this.selectedCategory = name;
newCategoryInput.value = "";
renderChips();
new Notice(`已新增分类:${name}`);
};
addCategoryButton.addEventListener("click", handleAddCategory);
newCategoryInput.addEventListener("keypress", (e) => {
if (e.key === "Enter") {
e.preventDefault();
handleAddCategory();
}
});
const downloadRow = contentEl.createEl("div", { cls: ["xhs-modal-row", "xhs-download-row"] });
const downloadWrapper = downloadRow.createEl("div", { cls: "xhs-download-wrapper" });
const checkboxId = "download-media-checkbox";
const checkbox = downloadWrapper.createEl("input", { attr: { type: "checkbox", id: checkboxId } });
checkbox.checked = this.downloadMedia;
checkbox.addEventListener("change", () => {
this.downloadMedia = checkbox.checked;
});
downloadWrapper.createEl("label", {
text: "本次导入下载媒体到本地",
cls: "xhs-download-label",
attr: { for: checkboxId },
});
const buttonRow = contentEl.createEl("div", { cls: ["xhs-modal-row", "xhs-button-row"] });
const submitButton = buttonRow.createEl("button", {
text: "导入",
cls: "xhs-submit-button",
});
submitButton.addEventListener("click", () => {
this.result = { text: input.value.trim(), category: this.selectedCategory, downloadMedia: this.downloadMedia };
this.close();
});
input.addEventListener("keypress", (e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
this.result = { text: input.value.trim(), category: this.selectedCategory, downloadMedia: this.downloadMedia };
this.close();
}
});
}
onClose() {
this.onSubmit(this.result);
}
}